From 85b8148e20d9b8bf94ce17a91b55a822907e800e Mon Sep 17 00:00:00 2001 From: nonameShijian <2954700422@qq.com> Date: Sat, 3 Feb 2024 19:40:13 +0800 Subject: [PATCH] =?UTF-8?q?=20=E5=B0=86game/typescript.js=E7=BC=96?= =?UTF-8?q?=E8=AF=91=E5=88=B0ES2019?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- game/typescript.js | 75529 +++++++++++++++++-------------------------- 1 file changed, 29675 insertions(+), 45854 deletions(-) diff --git a/game/typescript.js b/game/typescript.js index fe732a6cb..2d4d442e2 100644 --- a/game/typescript.js +++ b/game/typescript.js @@ -13,8 +13,8 @@ See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. ***************************************************************************** */ - "use strict"; + var ts = (() => { var __defProp = Object.defineProperty; var __getOwnPropNames = Object.getOwnPropertyNames; @@ -22,11 +22,15 @@ var ts = (() => { return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res; }; var __commonJS = (cb, mod) => function __require() { - return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; + return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { + exports: {} + }).exports, mod), mod.exports; }; var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); + for (var name in all) __defProp(target, name, { + get: all[name], + enumerable: true + }); }; // src/compiler/corePublic.ts @@ -34,9 +38,10 @@ var ts = (() => { var init_corePublic = __esm({ "src/compiler/corePublic.ts"() { "use strict"; + versionMajorMinor = "5.3"; version = "5.3.3"; - Comparison = /* @__PURE__ */ ((Comparison3) => { + Comparison = /* @__PURE__ */(Comparison3 => { Comparison3[Comparison3["LessThan"] = -1] = "LessThan"; Comparison3[Comparison3["EqualTo"] = 0] = "EqualTo"; Comparison3[Comparison3["GreaterThan"] = 1] = "GreaterThan"; @@ -117,8 +122,7 @@ var ts = (() => { } 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; @@ -134,9 +138,8 @@ var ts = (() => { return true; } function find(array, predicate, startIndex) { - if (array === void 0) - return void 0; - for (let i = startIndex ?? 0; i < array.length; i++) { + if (array === void 0) return void 0; + for (let i = startIndex !== null && startIndex !== void 0 ? startIndex : 0; i < array.length; i++) { const value = array[i]; if (predicate(value, i)) { return value; @@ -145,9 +148,8 @@ var ts = (() => { return void 0; } function findLast(array, predicate, startIndex) { - if (array === void 0) - return void 0; - for (let i = startIndex ?? array.length - 1; i >= 0; i--) { + if (array === void 0) return void 0; + for (let i = startIndex !== null && startIndex !== void 0 ? startIndex : array.length - 1; i >= 0; i--) { const value = array[i]; if (predicate(value, i)) { return value; @@ -156,9 +158,8 @@ var ts = (() => { return void 0; } function findIndex(array, predicate, startIndex) { - if (array === void 0) - return -1; - for (let i = startIndex ?? 0; i < array.length; i++) { + if (array === void 0) return -1; + for (let i = startIndex !== null && startIndex !== void 0 ? startIndex : 0; i < array.length; i++) { if (predicate(array[i], i)) { return i; } @@ -166,9 +167,8 @@ var ts = (() => { return -1; } function findLastIndex(array, predicate, startIndex) { - if (array === void 0) - return -1; - for (let i = startIndex ?? array.length - 1; i >= 0; i--) { + if (array === void 0) return -1; + for (let i = startIndex !== null && startIndex !== void 0 ? startIndex : array.length - 1; i >= 0; i--) { if (predicate(array[i], i)) { return i; } @@ -221,8 +221,7 @@ var ts = (() => { 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++; @@ -331,8 +330,7 @@ var ts = (() => { function* flatMapIterator(iter, mapfn) { for (const x of iter) { const iter2 = mapfn(x); - if (!iter2) - continue; + if (!iter2) continue; yield* iter2; } } @@ -391,7 +389,7 @@ var ts = (() => { if (!map2) { return void 0; } - const result = /* @__PURE__ */ new Map(); + const result = /* @__PURE__ */new Map(); map2.forEach((value, key) => { const entry = f(key, value); if (entry !== void 0) { @@ -458,7 +456,7 @@ var ts = (() => { if (!map2) { return void 0; } - const result = /* @__PURE__ */ new Map(); + const result = /* @__PURE__ */new Map(); map2.forEach((value, key) => { const [newKey, newValue] = f(key, value); result.set(newKey, newValue); @@ -491,14 +489,11 @@ var ts = (() => { } } } - 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) { @@ -521,7 +516,7 @@ var ts = (() => { } } deduplicated.sort(); - return deduplicated.map((i) => array[i]); + return deduplicated.map(i => array[i]); } function deduplicateEquality(array, equalityComparer) { const result = []; @@ -534,8 +529,7 @@ var ts = (() => { 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++) { @@ -574,8 +568,7 @@ var ts = (() => { 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; @@ -585,17 +578,18 @@ var ts = (() => { } function detectSortCaseSensitivity(array, getString, compareStringsCaseSensitive2, compareStringsCaseInsensitive2) { let kind = 3 /* Both */; - if (array.length < 2) - return kind; + if (array.length < 2) return kind; let prevElement = getString(array[0]); for (let i = 1, len = array.length; i < len && kind !== 0 /* None */; i++) { const element = getString(array[i]); if (kind & 1 /* CaseSensitive */ && compareStringsCaseSensitive2(prevElement, element) > 0) { kind &= ~1 /* CaseSensitive */; } + if (kind & 2 /* CaseInsensitive */ && compareStringsCaseInsensitive2(prevElement, element) > 0) { kind &= ~2 /* CaseInsensitive */; } + prevElement = element; } return kind; @@ -632,59 +626,50 @@ var ts = (() => { 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++) { - if (offsetB > 0) { - Debug.assertGreaterThanOrEqual(comparer(arrayB[offsetB], arrayB[offsetB - 1]), 0 /* EqualTo */); - } - loopA: - for (const startA = offsetA; offsetA < arrayA.length; offsetA++) { - if (offsetA > startA) { - Debug.assertGreaterThanOrEqual(comparer(arrayA[offsetA], arrayA[offsetA - 1]), 0 /* EqualTo */); - } - switch (comparer(arrayB[offsetB], arrayA[offsetA])) { - case -1 /* LessThan */: - result.push(arrayB[offsetB]); - continue loopB; - case 0 /* EqualTo */: - continue loopB; - case 1 /* GreaterThan */: - continue loopA; - } - } + loopB: for (let offsetA = 0, offsetB = 0; offsetB < arrayB.length; offsetB++) { + if (offsetB > 0) { + Debug.assertGreaterThanOrEqual(comparer(arrayB[offsetB], arrayB[offsetB - 1]), 0 /* EqualTo */); } + + loopA: for (const startA = offsetA; offsetA < arrayA.length; offsetA++) { + if (offsetA > startA) { + Debug.assertGreaterThanOrEqual(comparer(arrayA[offsetA], arrayA[offsetA - 1]), 0 /* EqualTo */); + } + + switch (comparer(arrayB[offsetB], arrayA[offsetA])) { + case -1 /* LessThan */: + result.push(arrayB[offsetB]); + continue loopB; + case 0 /* EqualTo */: + continue loopB; + case 1 /* GreaterThan */: + continue loopA; + } + } + } 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++) { @@ -724,7 +709,7 @@ var ts = (() => { function stableSort(array, comparer) { const indices = indicesOf(array); stableSortIndices(array, indices, comparer); - return indices.map((i) => array[i]); + return indices.map(i => array[i]); } function rangeEquals(array1, array2, pos, end) { while (pos < end) { @@ -874,8 +859,7 @@ var ts = (() => { } 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]; @@ -885,32 +869,26 @@ var ts = (() => { 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; } function arrayToMap(array, makeKey, makeValue = identity) { - const result = /* @__PURE__ */ new Map(); + 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; } @@ -935,8 +913,9 @@ var ts = (() => { const result = {}; if (values) { for (const value of values) { + var _result$key; const key = `${keySelector(value)}`; - const array = result[key] ?? (result[key] = []); + const array = (_result$key = result[key]) !== null && _result$key !== void 0 ? _result$key : result[key] = []; array.push(value); } } @@ -976,7 +955,7 @@ var ts = (() => { return fn ? fn.bind(obj) : void 0; } function createMultiMap() { - const map2 = /* @__PURE__ */ new Map(); + const map2 = /* @__PURE__ */new Map(); map2.add = multiMapAdd; map2.remove = multiMapRemove; return map2; @@ -1017,12 +996,9 @@ var ts = (() => { headIndex++; if (headIndex > 100 && headIndex > elements.length >> 1) { const newLength = elements.length - headIndex; - elements.copyWithin( - /*target*/ - 0, - /*start*/ - headIndex - ); + elements.copyWithin( /*target*/ + 0, /*start*/ + headIndex); elements.length = newLength; headIndex = 0; } @@ -1035,7 +1011,7 @@ var ts = (() => { }; } function createSet(getHashCode, equals) { - const multiMap = /* @__PURE__ */ new Map(); + const multiMap = /* @__PURE__ */new Map(); let size = 0; function* getElementIterator() { for (const value of multiMap.values()) { @@ -1049,11 +1025,9 @@ var ts = (() => { 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; @@ -1085,8 +1059,7 @@ var ts = (() => { }, 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++) { @@ -1165,12 +1138,10 @@ var ts = (() => { 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(_) { - } + function noop(_) {} function returnFalse() { return false; } @@ -1203,8 +1174,8 @@ var ts = (() => { }; } function memoizeOne(callback) { - const map2 = /* @__PURE__ */ new Map(); - return (arg) => { + const map2 = /* @__PURE__ */new Map(); + return arg => { const key = `${typeof arg}:${arg}`; let value = map2.get(key); if (value === void 0 && !map2.has(key)) { @@ -1215,8 +1186,8 @@ var ts = (() => { }; } function memoizeWeak(callback) { - const map2 = /* @__PURE__ */ new WeakMap(); - return (arg) => { + const map2 = /* @__PURE__ */new WeakMap(); + return arg => { let value = map2.get(arg); if (value === void 0 && !map2.has(arg)) { value = callback(arg); @@ -1241,17 +1212,17 @@ var ts = (() => { for (let i = 0; i < arguments.length; i++) { args[i] = arguments[i]; } - return (t) => reduceLeft(args, (u, f) => f(u), t); + return t => reduceLeft(args, (u, f) => f(u), t); } else if (d) { - return (t) => d(c(b(a(t)))); + return t => d(c(b(a(t)))); } else if (c) { - return (t) => c(b(a(t))); + return t => c(b(a(t))); } else if (b) { - return (t) => b(a(t)); + return t => b(a(t)); } else if (a) { - return (t) => a(t); + return t => a(t); } else { - return (t) => t; + return t => t; } } function equateValues(a, b) { @@ -1266,6 +1237,7 @@ var ts = (() => { function compareComparableValues(a, b) { return a === b ? 0 /* EqualTo */ : a === void 0 ? -1 /* LessThan */ : b === void 0 ? 1 /* GreaterThan */ : a < b ? -1 /* LessThan */ : 1 /* GreaterThan */; } + function compareValues(a, b) { return compareComparableValues(a, b); } @@ -1276,27 +1248,23 @@ var ts = (() => { 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 */; } + function compareStringsCaseSensitive(a, b) { return compareComparableValues(a, b); } @@ -1364,14 +1332,10 @@ var ts = (() => { } for (let j = minJ; j <= maxJ; j++) { const substitutionDistance = s1[i - 1].toLowerCase() === s2[j - 1].toLowerCase() ? previous[j - 1] + 0.1 : previous[j - 1] + 2; - const dist = c1 === s2.charCodeAt(j - 1) ? previous[j - 1] : Math.min( - /*delete*/ - previous[j] + 1, - /*insert*/ - current[j - 1] + 1, - /*substitute*/ - substitutionDistance - ); + const dist = c1 === s2.charCodeAt(j - 1) ? previous[j - 1] : Math.min( /*delete*/ + previous[j] + 1, /*insert*/ + current[j - 1] + 1, /*substitute*/ + substitutionDistance); current[j] = dist; colMin = Math.min(colMin, dist); } @@ -1450,7 +1414,7 @@ var ts = (() => { array.pop(); } function unorderedRemoveItem(array, item) { - return unorderedRemoveFirstItemWhere(array, (element) => element === item); + return unorderedRemoveFirstItemWhere(array, element => element === item); } function unorderedRemoveFirstItemWhere(array, predicate) { for (let i = 0; i < array.length; i++) { @@ -1464,7 +1428,10 @@ var ts = (() => { function createGetCanonicalFileName(useCaseSensitiveFileNames2) { return useCaseSensitiveFileNames2 ? identity : toFileNameLowerCase; } - function patternText({ prefix, suffix }) { + function patternText({ + prefix, + suffix + }) { return `${prefix}*${suffix}`; } function matchedText(pattern, candidate) { @@ -1492,11 +1459,14 @@ var ts = (() => { function tryRemovePrefix(str, prefix, getCanonicalFileName = identity) { return startsWith(getCanonicalFileName(str), getCanonicalFileName(prefix)) ? str.substring(prefix.length) : void 0; } - function isPatternMatch({ prefix, suffix }, candidate) { + function isPatternMatch({ + prefix, + suffix + }, candidate) { return candidate.length >= prefix.length + suffix.length && startsWith(candidate, prefix) && endsWith(candidate, suffix); } function and(f, g) { - return (arg) => f(arg) && g(arg); + return arg => f(arg) && g(arg); } function or(...fs) { return (...args) => { @@ -1513,8 +1483,7 @@ var ts = (() => { function not(fn) { return (...args) => !fn(...args); } - function assertType(_) { - } + function assertType(_) {} function singleElementArray(t) { return t === void 0 ? void 0 : [t]; } @@ -1555,13 +1524,8 @@ var ts = (() => { } function cartesianProduct(arrays) { const result = []; - cartesianProductWorker( - arrays, - result, - /*outer*/ - void 0, - 0 - ); + cartesianProductWorker(arrays, result, /*outer*/ + void 0, 0); return result; } function cartesianProductWorker(arrays, result, outer, index) { @@ -1607,11 +1571,12 @@ var ts = (() => { var init_core = __esm({ "src/compiler/core.ts"() { "use strict"; + init_ts2(); emptyArray = []; - emptyMap = /* @__PURE__ */ new Map(); - emptySet = /* @__PURE__ */ new Set(); - SortKind = /* @__PURE__ */ ((SortKind2) => { + emptyMap = /* @__PURE__ */new Map(); + emptySet = /* @__PURE__ */new Set(); + SortKind = /* @__PURE__ */(SortKind2 => { SortKind2[SortKind2["None"] = 0] = "None"; SortKind2[SortKind2["CaseSensitive"] = 1] = "CaseSensitive"; SortKind2[SortKind2["CaseInsensitive"] = 2] = "CaseInsensitive"; @@ -1629,7 +1594,7 @@ var ts = (() => { }; hasOwnProperty = Object.prototype.hasOwnProperty; fileNameLowerCaseRegExp = /[^\u0130\u0131\u00DFa-z0-9\\/:\-_. ]+/g; - AssertionLevel = /* @__PURE__ */ ((AssertionLevel2) => { + AssertionLevel = /* @__PURE__ */(AssertionLevel2 => { AssertionLevel2[AssertionLevel2["None"] = 0] = "None"; AssertionLevel2[AssertionLevel2["Normal"] = 1] = "Normal"; AssertionLevel2[AssertionLevel2["Aggressive"] = 2] = "Aggressive"; @@ -1639,17 +1604,18 @@ var ts = (() => { createUIStringComparer = (() => { 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 */; } + function createIntlCollatorStringComparer(locale) { - const comparer = new Intl.Collator(locale, { usage: "sort", sensitivity: "variant" }).compare; + const comparer = new Intl.Collator(locale, { + usage: "sort", + sensitivity: "variant" + }).compare; return (a, b) => compareWithCallback(a, b, comparer); } })(); @@ -1661,9 +1627,10 @@ var ts = (() => { var init_debug = __esm({ "src/compiler/debug.ts"() { "use strict"; + init_ts2(); init_ts2(); - LogLevel = /* @__PURE__ */ ((LogLevel3) => { + LogLevel = /* @__PURE__ */(LogLevel3 => { LogLevel3[LogLevel3["Off"] = 0] = "Off"; LogLevel3[LogLevel3["Error"] = 1] = "Error"; LogLevel3[LogLevel3["Warning"] = 2] = "Warning"; @@ -1671,7 +1638,7 @@ var ts = (() => { LogLevel3[LogLevel3["Verbose"] = 4] = "Verbose"; return LogLevel3; })(LogLevel || {}); - ((Debug2) => { + (Debug2 => { let currentAssertionLevel = 0 /* None */; Debug2.currentLogLevel = 2 /* Warning */; Debug2.isDebugging = false; @@ -1688,7 +1655,7 @@ var ts = (() => { logMessage(3 /* Info */, s); } Debug2.log = log; - ((_log) => { + (_log => { function error2(s) { logMessage(1 /* Error */, s); } @@ -1731,7 +1698,10 @@ var ts = (() => { Debug2.shouldAssert = shouldAssert; function shouldAssertFunction(level, name) { if (!shouldAssert(level)) { - assertionCache[name] = { level, assertion: Debug2[name] }; + assertionCache[name] = { + level, + assertion: Debug2[name] + }; Debug2[name] = noop; return false; } @@ -1747,11 +1717,8 @@ var ts = (() => { } Debug2.fail = fail; function failBadSyntaxKind(node, message, stackCrawlMark) { - return fail( - `${message || "Unexpected node."}\r -Node ${formatSyntaxKind(node.kind)} was unexpected.`, - stackCrawlMark || failBadSyntaxKind - ); + return fail(`${message || "Unexpected node."}\r +Node ${formatSyntaxKind(node.kind)} was unexpected.`, stackCrawlMark || failBadSyntaxKind); } Debug2.failBadSyntaxKind = failBadSyntaxKind; function assert(expression, message, verboseDebugInfo, stackCrawlMark) { @@ -1818,72 +1785,41 @@ Node ${formatSyntaxKind(node.kind)} was unexpected.`, Debug2.assertNever = assertNever; function assertEachNode(nodes, test, message, stackCrawlMark) { if (shouldAssertFunction(1 /* Normal */, "assertEachNode")) { - assert( - test === void 0 || every(nodes, test), - message || "Unexpected node.", - () => `Node array did not pass test '${getFunctionName(test)}'.`, - stackCrawlMark || assertEachNode - ); + assert(test === void 0 || every(nodes, test), message || "Unexpected node.", () => `Node array did not pass test '${getFunctionName(test)}'.`, stackCrawlMark || assertEachNode); } } Debug2.assertEachNode = assertEachNode; function assertNode(node, test, message, stackCrawlMark) { if (shouldAssertFunction(1 /* Normal */, "assertNode")) { - assert( - node !== void 0 && (test === void 0 || test(node)), - message || "Unexpected node.", - () => `Node ${formatSyntaxKind(node == null ? void 0 : node.kind)} did not pass test '${getFunctionName(test)}'.`, - stackCrawlMark || assertNode - ); + assert(node !== void 0 && (test === void 0 || test(node)), message || "Unexpected node.", () => `Node ${formatSyntaxKind(node == null ? void 0 : node.kind)} did not pass test '${getFunctionName(test)}'.`, stackCrawlMark || assertNode); } } Debug2.assertNode = assertNode; function assertNotNode(node, test, message, stackCrawlMark) { if (shouldAssertFunction(1 /* Normal */, "assertNotNode")) { - assert( - node === void 0 || test === void 0 || !test(node), - message || "Unexpected node.", - () => `Node ${formatSyntaxKind(node.kind)} should not have passed test '${getFunctionName(test)}'.`, - stackCrawlMark || assertNotNode - ); + assert(node === void 0 || test === void 0 || !test(node), message || "Unexpected node.", () => `Node ${formatSyntaxKind(node.kind)} should not have passed test '${getFunctionName(test)}'.`, stackCrawlMark || assertNotNode); } } Debug2.assertNotNode = assertNotNode; function assertOptionalNode(node, test, message, stackCrawlMark) { if (shouldAssertFunction(1 /* Normal */, "assertOptionalNode")) { - assert( - test === void 0 || node === void 0 || test(node), - message || "Unexpected node.", - () => `Node ${formatSyntaxKind(node == null ? void 0 : node.kind)} did not pass test '${getFunctionName(test)}'.`, - stackCrawlMark || assertOptionalNode - ); + assert(test === void 0 || node === void 0 || test(node), message || "Unexpected node.", () => `Node ${formatSyntaxKind(node == null ? void 0 : node.kind)} did not pass test '${getFunctionName(test)}'.`, stackCrawlMark || assertOptionalNode); } } Debug2.assertOptionalNode = assertOptionalNode; function assertOptionalToken(node, kind, message, stackCrawlMark) { if (shouldAssertFunction(1 /* Normal */, "assertOptionalToken")) { - assert( - kind === void 0 || node === void 0 || node.kind === kind, - message || "Unexpected node.", - () => `Node ${formatSyntaxKind(node == null ? void 0 : node.kind)} was not a '${formatSyntaxKind(kind)}' token.`, - stackCrawlMark || assertOptionalToken - ); + assert(kind === void 0 || node === void 0 || node.kind === kind, message || "Unexpected node.", () => `Node ${formatSyntaxKind(node == null ? void 0 : node.kind)} was not a '${formatSyntaxKind(kind)}' token.`, stackCrawlMark || assertOptionalToken); } } Debug2.assertOptionalToken = assertOptionalToken; function assertMissingNode(node, message, stackCrawlMark) { if (shouldAssertFunction(1 /* Normal */, "assertMissingNode")) { - assert( - node === void 0, - message || "Unexpected node.", - () => `Node ${formatSyntaxKind(node.kind)} was unexpected'.`, - stackCrawlMark || assertMissingNode - ); + assert(node === void 0, message || "Unexpected node.", () => `Node ${formatSyntaxKind(node.kind)} was unexpected'.`, stackCrawlMark || assertMissingNode); } } Debug2.assertMissingNode = assertMissingNode; - function type(_value) { - } + function type(_value) {} Debug2.type = type; function getFunctionName(func) { if (typeof func !== "function") { @@ -1898,7 +1834,7 @@ Node ${formatSyntaxKind(node.kind)} was unexpected.`, } Debug2.getFunctionName = getFunctionName; function formatSymbol(symbol) { - return `{ name: ${unescapeLeadingUnderscores(symbol.escapedName)}; flags: ${formatSymbolFlags(symbol.flags)}; declarations: ${map(symbol.declarations, (node) => formatSyntaxKind(node.kind))} }`; + return `{ name: ${unescapeLeadingUnderscores(symbol.escapedName)}; flags: ${formatSymbolFlags(symbol.flags)}; declarations: ${map(symbol.declarations, node => formatSyntaxKind(node.kind))} }`; } Debug2.formatSymbol = formatSymbol; function formatEnum(value = 0, enumObject, isFlags) { @@ -1931,7 +1867,7 @@ Node ${formatSyntaxKind(node.kind)} was unexpected.`, return value.toString(); } Debug2.formatEnum = formatEnum; - const enumMemberCache = /* @__PURE__ */ new Map(); + const enumMemberCache = /* @__PURE__ */new Map(); function getEnumMembers(enumObject) { const existing = enumMemberCache.get(enumObject); if (existing) { @@ -1949,147 +1885,83 @@ Node ${formatSyntaxKind(node.kind)} was unexpected.`, return sorted; } function formatSyntaxKind(kind) { - return formatEnum( - kind, - SyntaxKind, - /*isFlags*/ - false - ); + return formatEnum(kind, SyntaxKind, /*isFlags*/ + false); } Debug2.formatSyntaxKind = formatSyntaxKind; function formatSnippetKind(kind) { - return formatEnum( - kind, - SnippetKind, - /*isFlags*/ - false - ); + return formatEnum(kind, SnippetKind, /*isFlags*/ + false); } Debug2.formatSnippetKind = formatSnippetKind; function formatScriptKind(kind) { - return formatEnum( - kind, - ScriptKind, - /*isFlags*/ - false - ); + return formatEnum(kind, ScriptKind, /*isFlags*/ + false); } Debug2.formatScriptKind = formatScriptKind; function formatNodeFlags(flags) { - return formatEnum( - flags, - NodeFlags, - /*isFlags*/ - true - ); + return formatEnum(flags, NodeFlags, /*isFlags*/ + true); } Debug2.formatNodeFlags = formatNodeFlags; function formatModifierFlags(flags) { - return formatEnum( - flags, - ModifierFlags, - /*isFlags*/ - true - ); + return formatEnum(flags, ModifierFlags, /*isFlags*/ + true); } Debug2.formatModifierFlags = formatModifierFlags; function formatTransformFlags(flags) { - return formatEnum( - flags, - TransformFlags, - /*isFlags*/ - true - ); + return formatEnum(flags, TransformFlags, /*isFlags*/ + true); } Debug2.formatTransformFlags = formatTransformFlags; function formatEmitFlags(flags) { - return formatEnum( - flags, - EmitFlags, - /*isFlags*/ - true - ); + return formatEnum(flags, EmitFlags, /*isFlags*/ + true); } Debug2.formatEmitFlags = formatEmitFlags; function formatSymbolFlags(flags) { - return formatEnum( - flags, - SymbolFlags, - /*isFlags*/ - true - ); + return formatEnum(flags, SymbolFlags, /*isFlags*/ + true); } Debug2.formatSymbolFlags = formatSymbolFlags; function formatTypeFlags(flags) { - return formatEnum( - flags, - TypeFlags, - /*isFlags*/ - true - ); + return formatEnum(flags, TypeFlags, /*isFlags*/ + true); } Debug2.formatTypeFlags = formatTypeFlags; function formatSignatureFlags(flags) { - return formatEnum( - flags, - SignatureFlags, - /*isFlags*/ - true - ); + return formatEnum(flags, SignatureFlags, /*isFlags*/ + true); } Debug2.formatSignatureFlags = formatSignatureFlags; function formatObjectFlags(flags) { - return formatEnum( - flags, - ObjectFlags, - /*isFlags*/ - true - ); + return formatEnum(flags, ObjectFlags, /*isFlags*/ + true); } Debug2.formatObjectFlags = formatObjectFlags; function formatFlowFlags(flags) { - return formatEnum( - flags, - FlowFlags, - /*isFlags*/ - true - ); + return formatEnum(flags, FlowFlags, /*isFlags*/ + true); } Debug2.formatFlowFlags = formatFlowFlags; function formatRelationComparisonResult(result) { - return formatEnum( - result, - RelationComparisonResult, - /*isFlags*/ - true - ); + return formatEnum(result, RelationComparisonResult, /*isFlags*/ + true); } Debug2.formatRelationComparisonResult = formatRelationComparisonResult; function formatCheckMode(mode) { - return formatEnum( - mode, - CheckMode, - /*isFlags*/ - true - ); + return formatEnum(mode, CheckMode, /*isFlags*/ + true); } Debug2.formatCheckMode = formatCheckMode; function formatSignatureCheckMode(mode) { - return formatEnum( - mode, - SignatureCheckMode, - /*isFlags*/ - true - ); + return formatEnum(mode, SignatureCheckMode, /*isFlags*/ + true); } Debug2.formatSignatureCheckMode = formatSignatureCheckMode; function formatTypeFacts(facts) { - return formatEnum( - facts, - TypeFacts, - /*isFlags*/ - true - ); + return formatEnum(facts, TypeFacts, /*isFlags*/ + true); } Debug2.formatTypeFacts = formatTypeFacts; let isDebugInfoEnabled = false; @@ -2107,12 +1979,8 @@ Node ${formatSyntaxKind(node.kind)} was unexpected.`, }, __debugFlowFlags: { get() { - return formatEnum( - this.flags, - FlowFlags, - /*isFlags*/ - true - ); + return formatEnum(this.flags, FlowFlags, /*isFlags*/ + true); } }, __debugToString: { @@ -2165,10 +2033,9 @@ Node ${formatSyntaxKind(node.kind)} was unexpected.`, } Debug2.attachNodeArrayDebugInfo = attachNodeArrayDebugInfo; function enableDebugInfo() { - if (isDebugInfoEnabled) - return; - const weakTypeTextMap = /* @__PURE__ */ new WeakMap(); - const weakNodeTextMap = /* @__PURE__ */ new WeakMap(); + if (isDebugInfoEnabled) return; + const weakTypeTextMap = /* @__PURE__ */new WeakMap(); + const weakNodeTextMap = /* @__PURE__ */new WeakMap(); Object.defineProperties(objectAllocator.getSymbolConstructor().prototype, { // for use with vscode-js-debug's new customDescriptionGenerator in launch.json __tsDebuggerDisplay: { @@ -2227,12 +2094,7 @@ Node ${formatSyntaxKind(node.kind)} was unexpected.`, } } }); - const nodeConstructors = [ - objectAllocator.getNodeConstructor(), - objectAllocator.getIdentifierConstructor(), - objectAllocator.getTokenConstructor(), - objectAllocator.getSourceFileConstructor() - ]; + const nodeConstructors = [objectAllocator.getNodeConstructor(), objectAllocator.getIdentifierConstructor(), objectAllocator.getTokenConstructor(), objectAllocator.getSourceFileConstructor()]; for (const ctor of nodeConstructors) { if (!hasProperty(ctor.prototype, "__debugKind")) { Object.defineProperties(ctor.prototype, { @@ -2275,8 +2137,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); @@ -2314,17 +2175,9 @@ Node ${formatSyntaxKind(node.kind)} was unexpected.`, case 0 /* Simple */: return `${this.source.__debugTypeToString()} -> ${this.target.__debugTypeToString()}`; case 1 /* Array */: - return zipWith( - this.sources, - this.targets || map(this.sources, () => "any"), - (s, t) => `${s.__debugTypeToString()} -> ${typeof t === "string" ? t : t.__debugTypeToString()}` - ).join(", "); + return zipWith(this.sources, this.targets || map(this.sources, () => "any"), (s, t) => `${s.__debugTypeToString()} -> ${typeof t === "string" ? t : t.__debugTypeToString()}`).join(", "); case 2 /* Deferred */: - return zipWith( - this.sources, - this.targets, - (s, t) => `${s.__debugTypeToString()} -> ${t().__debugTypeToString()}` - ).join(", "); + return zipWith(this.sources, this.targets, (s, t) => `${s.__debugTypeToString()} -> ${t().__debugTypeToString()}`).join(", "); case 5 /* Merged */: case 4 /* Composite */: return `m1: ${this.mapper1.__debugToString().split("\n").join("\n ")} @@ -2356,7 +2209,7 @@ m2: ${this.mapper2.__debugToString().split("\n").join("\n ")}`; return f.id; } let BoxCharacter; - ((BoxCharacter2) => { + (BoxCharacter2 => { BoxCharacter2["lr"] = "\u2500"; BoxCharacter2["ud"] = "\u2502"; BoxCharacter2["dr"] = "\u256D"; @@ -2370,7 +2223,7 @@ m2: ${this.mapper2.__debugToString().split("\n").join("\n ")}`; BoxCharacter2["udlr"] = "\u256B"; })(BoxCharacter || (BoxCharacter = {})); let Connection; - ((Connection2) => { + (Connection2 => { Connection2[Connection2["None"] = 0] = "None"; Connection2[Connection2["Up"] = 1] = "Up"; Connection2[Connection2["Down"] = 2] = "Down"; @@ -2391,13 +2244,11 @@ m2: ${this.mapper2.__debugToString().split("\n").join("\n ")}`; })(Connection || (Connection = {})); const hasAntecedentFlags = 16 /* Assignment */ | 96 /* Condition */ | 128 /* SwitchClause */ | 256 /* ArrayMutation */ | 512 /* Call */ | 1024 /* ReduceLabel */; const hasNodeFlags = 2 /* Start */ | 16 /* Assignment */ | 512 /* Call */ | 96 /* Condition */ | 256 /* ArrayMutation */; - const links = /* @__PURE__ */ Object.create( - /*o*/ - null - ); + const links = /* @__PURE__ */Object.create( /*o*/ + null); const nodes = []; const edges = []; - const root = buildGraphNode(flowNode, /* @__PURE__ */ new Set()); + const root = buildGraphNode(flowNode, /* @__PURE__ */new Set()); for (const node of nodes) { node.text = renderFlowNode(node.flowNode, node.circular); computeLevel(node); @@ -2409,6 +2260,7 @@ m2: ${this.mapper2.__debugToString().split("\n").join("\n ")}`; function isFlowSwitchClause(f) { return !!(f.flags & 128 /* SwitchClause */); } + function hasAntecedents(f) { return !!(f.flags & 12 /* Label */) && !!f.antecedents; } @@ -2456,7 +2308,16 @@ m2: ${this.mapper2.__debugToString().split("\n").join("\n ")}`; } seen.add(flowNode2); if (!graphNode) { - links[id] = graphNode = { id, flowNode: flowNode2, edges: [], text: "", lane: -1, endLane: -1, level: -1, circular: false }; + links[id] = graphNode = { + id, + flowNode: flowNode2, + edges: [], + text: "", + lane: -1, + endLane: -1, + level: -1, + circular: false + }; nodes.push(graphNode); if (hasAntecedents(flowNode2)) { for (const antecedent of flowNode2.antecedents) { @@ -2471,7 +2332,10 @@ m2: ${this.mapper2.__debugToString().split("\n").join("\n ")}`; } function buildGraphEdge(source, antecedent, seen) { const target = buildGraphNode(antecedent, seen); - const edge = { source, target }; + const edge = { + source, + target + }; edges.push(edge); source.edges.push(edge); target.edges.push(edge); @@ -2506,8 +2370,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) { @@ -2518,38 +2381,23 @@ m2: ${this.mapper2.__debugToString().split("\n").join("\n ")}`; } } function getHeader(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) { const sourceFile = getSourceFileOfNode(node); - return getSourceTextOfNodeFromSourceFile( - sourceFile, - node, - /*includeTrivia*/ - false - ); + return getSourceTextOfNodeFromSourceFile(sourceFile, node, /*includeTrivia*/ + false); } function renderFlowNode(flowNode2, circular) { let text = getHeader(flowNode2.flags); @@ -2586,25 +2434,21 @@ 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) { connectors[node.level][node.lane] |= 16 /* NoChildren */; } + const parents = getParents(node); 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; } } @@ -2614,10 +2458,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; } } @@ -2674,6 +2516,7 @@ ${lanes.join("\n")} case 15 /* UpDownLeftRight */: return "\u256B" /* udlr */; } + return " "; } function fill(array, value) { @@ -2705,13 +2548,10 @@ ${lanes.join("\n")} // src/compiler/semver.ts 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), @@ -2721,30 +2561,23 @@ ${lanes.join("\n")} }; } 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); @@ -2752,19 +2585,16 @@ ${lanes.join("\n")} 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); @@ -2773,77 +2603,71 @@ ${lanes.join("\n")} } 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), - isWildcard(major) || isWildcard(minor) ? 0 : parseInt(minor, 10), - isWildcard(major) || isWildcard(minor) || isWildcard(patch) ? 0 : parseInt(patch, 10), - prerelease, - build2 - ); - return { version: version2, major, minor, patch }; + const version2 = new Version(isWildcard(major) ? 0 : parseInt(major, 10), isWildcard(major) || isWildcard(minor) ? 0 : parseInt(minor, 10), isWildcard(major) || isWildcard(minor) || isWildcard(patch) ? 0 : parseInt(patch, 10), prerelease, build2); + return { + version: version2, + major, + minor, + patch + }; } 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)); } if (!isWildcard(rightResult.major)) { - comparators.push( - isWildcard(rightResult.minor) ? createComparator("<", rightResult.version.increment("major")) : isWildcard(rightResult.patch) ? createComparator("<", rightResult.version.increment("minor")) : createComparator("<=", rightResult.version) - ); + comparators.push(isWildcard(rightResult.minor) ? createComparator("<", rightResult.version.increment("major")) : isWildcard(rightResult.patch) ? createComparator("<", rightResult.version.increment("minor")) : createComparator("<=", rightResult.version)); } return true; } function parseComparator(operator, text, comparators) { const result = parsePartial(text); - if (!result) - return false; - const { version: version2, major, minor, patch } = result; + if (!result) return false; + const { + version: version2, + major, + minor, + patch + } = result; if (!isWildcard(major)) { switch (operator) { case "~": comparators.push(createComparator(">=", version2)); - comparators.push(createComparator( - "<", - version2.increment( - isWildcard(minor) ? "major" : "minor" - ) - )); + comparators.push(createComparator("<", version2.increment(isWildcard(minor) ? "major" : "minor"))); break; case "^": comparators.push(createComparator(">=", version2)); - comparators.push(createComparator( - "<", - version2.increment( - version2.major > 0 || isWildcard(minor) ? "major" : version2.minor > 0 || isWildcard(patch) ? "minor" : "patch" - ) - )); + comparators.push(createComparator("<", version2.increment(version2.major > 0 || isWildcard(minor) ? "major" : version2.minor > 0 || isWildcard(patch) ? "minor" : "patch"))); break; case "<": case ">=": - comparators.push( - isWildcard(minor) || isWildcard(patch) ? createComparator(operator, version2.with({ prerelease: "0" })) : createComparator(operator, version2) - ); + comparators.push(isWildcard(minor) || isWildcard(patch) ? createComparator(operator, version2.with({ + prerelease: "0" + })) : createComparator(operator, version2)); break; case "<=": case ">": - comparators.push( - isWildcard(minor) ? createComparator(operator === "<=" ? "<" : ">=", version2.increment("major").with({ prerelease: "0" })) : isWildcard(patch) ? createComparator(operator === "<=" ? "<" : ">=", version2.increment("minor").with({ prerelease: "0" })) : createComparator(operator, version2) - ); + comparators.push(isWildcard(minor) ? createComparator(operator === "<=" ? "<" : ">=", version2.increment("major").with({ + prerelease: "0" + })) : isWildcard(patch) ? createComparator(operator === "<=" ? "<" : ">=", version2.increment("minor").with({ + prerelease: "0" + })) : createComparator(operator, version2)); break; case "=": case void 0: if (isWildcard(minor) || isWildcard(patch)) { - comparators.push(createComparator(">=", version2.with({ prerelease: "0" }))); - comparators.push(createComparator("<", version2.increment(isWildcard(minor) ? "major" : "minor").with({ prerelease: "0" }))); + comparators.push(createComparator(">=", version2.with({ + prerelease: "0" + }))); + comparators.push(createComparator("<", version2.increment(isWildcard(minor) ? "major" : "minor").with({ + prerelease: "0" + }))); } else { comparators.push(createComparator("=", version2)); } @@ -2860,21 +2684,21 @@ ${lanes.join("\n")} return part === "*" || part === "x" || part === "X"; } function createComparator(operator, operand) { - return { 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; } @@ -2908,6 +2732,7 @@ ${lanes.join("\n")} var init_semver = __esm({ "src/compiler/semver.ts"() { "use strict"; + init_ts2(); versionRegExp = /^(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:-([a-z0-9-.]+))?(?:\+([a-z0-9-.]+))?)?)?$/i; prereleaseRegExp = /^(?:0|[1-9]\d*|[a-z-][a-z0-9-]*)(?:\.(?:0|[1-9]\d*|[a-z-][a-z0-9-]*))*$/i; @@ -2919,15 +2744,21 @@ ${lanes.join("\n")} constructor(major, minor = 0, patch = 0, prerelease = "", build2 = "") { if (typeof major === "string") { const result = Debug.checkDefined(tryParseComponents(major), "Invalid version"); - ({ major, minor, patch, prerelease, build: build2 } = result); + ({ + major, + minor, + patch, + prerelease, + build: build2 + } = result); } Debug.assert(major >= 0, "Invalid argument: major"); Debug.assert(minor >= 0, "Invalid argument: minor"); Debug.assert(patch >= 0, "Invalid argument: patch"); const prereleaseArray = prerelease ? isArray(prerelease) ? prerelease : prerelease.split(".") : emptyArray; const buildArray = build2 ? isArray(build2) ? build2 : build2.split(".") : emptyArray; - Debug.assert(every(prereleaseArray, (s) => prereleasePartRegExp.test(s)), "Invalid argument: prerelease"); - Debug.assert(every(buildArray, (s) => buildPartRegExp.test(s)), "Invalid argument: build"); + Debug.assert(every(prereleaseArray, s => prereleasePartRegExp.test(s)), "Invalid argument: prerelease"); + Debug.assert(every(buildArray, s => buildPartRegExp.test(s)), "Invalid argument: build"); this.major = major; this.minor = minor; this.patch = patch; @@ -2936,16 +2767,19 @@ ${lanes.join("\n")} } static tryParse(text) { const result = tryParseComponents(text); - if (!result) - return void 0; - const { major, minor, patch, prerelease, build: build2 } = result; + 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) { @@ -2972,10 +2806,8 @@ ${lanes.join("\n")} } 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; } }; @@ -2999,8 +2831,7 @@ ${lanes.join("\n")} * 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() { @@ -3034,7 +2865,10 @@ ${lanes.join("\n")} function tryGetNodePerformanceHooks() { if (isNodeLikeSystem()) { try { - const { performance: performance2, PerformanceObserver: PerformanceObserver2 } = require("perf_hooks"); + const { + performance: performance2, + PerformanceObserver: PerformanceObserver2 + } = require("perf_hooks"); if (hasRequiredAPI(performance2, PerformanceObserver2)) { return { // By default, only write native events when generating a cpu profile or using the v8 profiler. @@ -3043,8 +2877,7 @@ ${lanes.join("\n")} PerformanceObserver: PerformanceObserver2 }; } - } catch { - } + } catch {} } } function tryGetNativePerformanceHooks() { @@ -3054,10 +2887,11 @@ ${lanes.join("\n")} var init_performanceCore = __esm({ "src/compiler/performanceCore.ts"() { "use strict"; + init_ts2(); nativePerformanceHooks = tryGetWebPerformanceHooks() || tryGetNodePerformanceHooks(); nativePerformance = nativePerformanceHooks == null ? void 0 : nativePerformanceHooks.performance; - timestamp = nativePerformance ? () => nativePerformance.now() : Date.now ? Date.now : () => +/* @__PURE__ */ new Date(); + timestamp = nativePerformance ? () => nativePerformance.now() : Date.now ? Date.now : () => + /* @__PURE__ */new Date(); } }); @@ -3066,9 +2900,11 @@ ${lanes.join("\n")} var init_perfLogger = __esm({ "src/compiler/perfLogger.ts"() { "use strict"; + try { - const etwModulePath = process.env.TS_ETW_MODULE_PATH ?? "./node_modules/@microsoft/typescript-etw"; - etwModule = require(etwModulePath); + var _process$env$TS_ETW_M; + const etwModulePath = (_process$env$TS_ETW_M = process.env.TS_ETW_MODULE_PATH) !== null && _process$env$TS_ETW_M !== void 0 ? _process$env$TS_ETW_M : "./node_modules/@microsoft/typescript-etw"; + etwModule = require(etwModulePath); } catch (e) { etwModule = void 0; } @@ -3102,7 +2938,8 @@ ${lanes.join("\n")} } function mark(markName) { if (enabled) { - const count = counts.get(markName) ?? 0; + var _counts$get; + const count = (_counts$get = counts.get(markName)) !== null && _counts$get !== void 0 ? _counts$get : 0; counts.set(markName, count + 1); marks.set(markName, timestamp()); performanceImpl == null ? void 0 : performanceImpl.mark(markName); @@ -3113,8 +2950,9 @@ ${lanes.join("\n")} } function measure(measureName, startMarkName, endMarkName) { if (enabled) { - const end = (endMarkName !== void 0 ? marks.get(endMarkName) : void 0) ?? timestamp(); - const start = (startMarkName !== void 0 ? marks.get(startMarkName) : void 0) ?? timeorigin; + var _ref2, _ref3; + const end = (_ref2 = endMarkName !== void 0 ? marks.get(endMarkName) : void 0) !== null && _ref2 !== void 0 ? _ref2 : timestamp(); + const start = (_ref3 = startMarkName !== void 0 ? marks.get(startMarkName) : void 0) !== null && _ref3 !== void 0 ? _ref3 : timeorigin; const previousDuration = durations.get(measureName) || 0; durations.set(measureName, previousDuration + (end - start)); performanceImpl == null ? void 0 : performanceImpl.measure(measureName, startMarkName, endMarkName); @@ -3133,10 +2971,7 @@ ${lanes.join("\n")} 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) { @@ -3179,13 +3014,17 @@ ${lanes.join("\n")} var init_performance = __esm({ "src/compiler/performance.ts"() { "use strict"; + init_ts2(); - nullTimer = { enter: noop, exit: noop }; + nullTimer = { + enter: noop, + exit: noop + }; enabled = false; timeorigin = timestamp(); - marks = /* @__PURE__ */ new Map(); - counts = /* @__PURE__ */ new Map(); - durations = /* @__PURE__ */ new Map(); + marks = /* @__PURE__ */new Map(); + counts = /* @__PURE__ */new Map(); + durations = /* @__PURE__ */new Map(); } }); @@ -3210,6 +3049,7 @@ ${lanes.join("\n")} var init_ts_performance = __esm({ "src/compiler/_namespaces/ts.performance.ts"() { "use strict"; + init_performance(); } }); @@ -3219,9 +3059,10 @@ ${lanes.join("\n")} var init_tracing = __esm({ "src/compiler/tracing.ts"() { "use strict"; + init_ts2(); init_ts_performance(); - ((tracingEnabled2) => { + (tracingEnabled2 => { let fs; let traceCount = 0; let traceFd = 0; @@ -3233,7 +3074,7 @@ ${lanes.join("\n")} Debug.assert(!tracing, "Tracing already started"); if (fs === void 0) { try { - fs = require("fs"); + fs = require("fs"); } catch (e) { throw new Error(`tracing requires having fs (original error: ${e.message || e})`); @@ -3245,7 +3086,9 @@ ${lanes.join("\n")} legendPath = combinePaths(traceDir, "legend.json"); } if (!fs.existsSync(traceDir)) { - fs.mkdirSync(traceDir, { recursive: true }); + fs.mkdirSync(traceDir, { + recursive: true + }); } const countPart = mode === "build" ? `.${process.pid}-${++traceCount}` : mode === "server" ? `.${process.pid}` : ``; const tracePath = combinePaths(traceDir, `trace${countPart}.json`); @@ -3257,11 +3100,30 @@ ${lanes.join("\n")} }); traceFd = fs.openSync(tracePath, "w"); tracing = tracingEnabled2; - const meta = { cat: "__metadata", ph: "M", ts: 1e3 * timestamp(), pid: 1, tid: 1 }; - fs.writeSync( - traceFd, - "[\n" + [{ name: "process_name", args: { name: "tsc" }, ...meta }, { name: "thread_name", args: { name: "Main" }, ...meta }, { name: "TracingStartedInBrowser", ...meta, cat: "disabled-by-default-devtools.timeline" }].map((v) => JSON.stringify(v)).join(",\n") - ); + const meta = { + cat: "__metadata", + ph: "M", + ts: 1e3 * timestamp(), + pid: 1, + tid: 1 + }; + fs.writeSync(traceFd, "[\n" + [{ + name: "process_name", + args: { + name: "tsc" + }, + ...meta + }, { + name: "thread_name", + args: { + name: "Main" + }, + ...meta + }, { + name: "TracingStartedInBrowser", + ...meta, + cat: "disabled-by-default-devtools.timeline" + }].map(v => JSON.stringify(v)).join(",\n")); } tracingEnabled2.startTracing = startTracing2; function stopTracing() { @@ -3286,7 +3148,7 @@ ${lanes.join("\n")} } tracingEnabled2.recordType = recordType; let Phase; - ((Phase2) => { + (Phase2 => { Phase2["Parse"] = "parse"; Phase2["Program"] = "program"; Phase2["Bind"] = "bind"; @@ -3304,7 +3166,13 @@ ${lanes.join("\n")} if (separateBeginAndEnd) { writeEvent("B", phase, name, args); } - eventStack.push({ phase, name, args, time: 1e3 * timestamp(), separateBeginAndEnd }); + eventStack.push({ + phase, + name, + args, + time: 1e3 * timestamp(), + separateBeginAndEnd + }); } tracingEnabled2.push = push; function pop(results) { @@ -3323,32 +3191,31 @@ ${lanes.join("\n")} tracingEnabled2.popAll = popAll; const sampleInterval = 1e3 * 10; function writeStackEvent(index, endTime, results) { - const { phase, name, args, time, separateBeginAndEnd } = eventStack[index]; + const { + phase, + name, + args, + time, + separateBeginAndEnd + } = eventStack[index]; if (separateBeginAndEnd) { Debug.assert(!results, "`results` are not supported for events with `separateBeginAndEnd`"); - writeEvent( - "E", - phase, - name, - args, - /*extras*/ - void 0, - endTime - ); + writeEvent("E", phase, name, args, /*extras*/ + void 0, endTime); } else if (sampleInterval - time % sampleInterval <= endTime - time) { - writeEvent("X", phase, name, { ...args, results }, `"dur":${endTime - time}`, time); + writeEvent("X", phase, name, { + ...args, + results + }, `"dur":${endTime - time}`, time); } } 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"); @@ -3372,13 +3239,14 @@ ${lanes.join("\n")} mark("beginDumpTypes"); const typesPath = legend[legend.length - 1].typesPath; const typesFd = fs.openSync(typesPath, "w"); - const recursionIdentityMap = /* @__PURE__ */ new Map(); + const recursionIdentityMap = /* @__PURE__ */new Map(); fs.writeSync(typesFd, "["); const numTypes = types.length; for (let i = 0; i < numTypes; i++) { + var _type$aliasSymbol; const type = types[i]; const objectFlags = type.objectFlags; - const symbol = type.aliasSymbol ?? type.symbol; + const symbol = (_type$aliasSymbol = type.aliasSymbol) !== null && _type$aliasSymbol !== void 0 ? _type$aliasSymbol : type.symbol; let display; if (objectFlags & 16 /* Anonymous */ | type.flags & 2944 /* Literal */) { try { @@ -3400,18 +3268,19 @@ ${lanes.join("\n")} const referenceType = type; referenceProperties = { instantiatedType: (_d = referenceType.target) == null ? void 0 : _d.id, - typeArguments: (_e = referenceType.resolvedTypeArguments) == null ? void 0 : _e.map((t) => t.id), + typeArguments: (_e = referenceType.resolvedTypeArguments) == null ? void 0 : _e.map(t => t.id), referenceLocation: getLocation(referenceType.node) }; } let conditionalProperties = {}; if (type.flags & 16777216 /* Conditional */) { + var _ref4, _ref5; const conditionalType = type; conditionalProperties = { conditionalCheckType: (_f = conditionalType.checkType) == null ? void 0 : _f.id, conditionalExtendsType: (_g = conditionalType.extendsType) == null ? void 0 : _g.id, - conditionalTrueType: ((_h = conditionalType.resolvedTrueType) == null ? void 0 : _h.id) ?? -1, - conditionalFalseType: ((_i = conditionalType.resolvedFalseType) == null ? void 0 : _i.id) ?? -1 + conditionalTrueType: (_ref4 = (_h = conditionalType.resolvedTrueType) == null ? void 0 : _h.id) !== null && _ref4 !== void 0 ? _ref4 : -1, + conditionalFalseType: (_ref5 = (_i = conditionalType.resolvedFalseType) == null ? void 0 : _i.id) !== null && _ref5 !== void 0 ? _ref5 : -1 }; } let substitutionProperties = {}; @@ -3454,9 +3323,9 @@ ${lanes.join("\n")} symbolName: (symbol == null ? void 0 : symbol.escapedName) && unescapeLeadingUnderscores(symbol.escapedName), recursionId: recursionToken, isTuple: objectFlags & 8 /* Tuple */ ? true : void 0, - unionTypes: type.flags & 1048576 /* Union */ ? (_p = type.types) == null ? void 0 : _p.map((t) => t.id) : void 0, - intersectionTypes: type.flags & 2097152 /* Intersection */ ? type.types.map((t) => t.id) : void 0, - aliasTypeArguments: (_q = type.aliasTypeArguments) == null ? void 0 : _q.map((t) => t.id), + unionTypes: type.flags & 1048576 /* Union */ ? (_p = type.types) == null ? void 0 : _p.map(t => t.id) : void 0, + intersectionTypes: type.flags & 2097152 /* Intersection */ ? type.types.map(t => t.id) : void 0, + aliasTypeArguments: (_q = type.aliasTypeArguments) == null ? void 0 : _q.map(t => t.id), keyofType: type.flags & 4194304 /* Index */ ? (_r = type.type) == null ? void 0 : _r.id : void 0, ...indexedAccessProperties, ...referenceProperties, @@ -3501,7 +3370,8 @@ ${lanes.join("\n")} var init_types = __esm({ "src/compiler/types.ts"() { "use strict"; - SyntaxKind = /* @__PURE__ */ ((SyntaxKind5) => { + + SyntaxKind = /* @__PURE__ */(SyntaxKind5 => { SyntaxKind5[SyntaxKind5["Unknown"] = 0] = "Unknown"; SyntaxKind5[SyntaxKind5["EndOfFileToken"] = 1] = "EndOfFileToken"; SyntaxKind5[SyntaxKind5["SingleLineCommentTrivia"] = 2] = "SingleLineCommentTrivia"; @@ -3904,7 +3774,7 @@ ${lanes.join("\n")} SyntaxKind5[SyntaxKind5["LastContextualKeyword"] = 165 /* OfKeyword */] = "LastContextualKeyword"; return SyntaxKind5; })(SyntaxKind || {}); - NodeFlags = /* @__PURE__ */ ((NodeFlags3) => { + NodeFlags = /* @__PURE__ */(NodeFlags3 => { NodeFlags3[NodeFlags3["None"] = 0] = "None"; NodeFlags3[NodeFlags3["Let"] = 1] = "Let"; NodeFlags3[NodeFlags3["Const"] = 2] = "Const"; @@ -3948,7 +3818,7 @@ ${lanes.join("\n")} NodeFlags3[NodeFlags3["IdentifierIsInJSDocNamespace"] = 4096 /* HasAsyncFunctions */] = "IdentifierIsInJSDocNamespace"; return NodeFlags3; })(NodeFlags || {}); - ModifierFlags = /* @__PURE__ */ ((ModifierFlags3) => { + ModifierFlags = /* @__PURE__ */(ModifierFlags3 => { ModifierFlags3[ModifierFlags3["None"] = 0] = "None"; ModifierFlags3[ModifierFlags3["Public"] = 1] = "Public"; ModifierFlags3[ModifierFlags3["Private"] = 2] = "Private"; @@ -3989,14 +3859,14 @@ ${lanes.join("\n")} ModifierFlags3[ModifierFlags3["Modifier"] = 98303] = "Modifier"; return ModifierFlags3; })(ModifierFlags || {}); - JsxFlags = /* @__PURE__ */ ((JsxFlags2) => { + JsxFlags = /* @__PURE__ */(JsxFlags2 => { JsxFlags2[JsxFlags2["None"] = 0] = "None"; JsxFlags2[JsxFlags2["IntrinsicNamedElement"] = 1] = "IntrinsicNamedElement"; JsxFlags2[JsxFlags2["IntrinsicIndexedElement"] = 2] = "IntrinsicIndexedElement"; JsxFlags2[JsxFlags2["IntrinsicElement"] = 3] = "IntrinsicElement"; return JsxFlags2; })(JsxFlags || {}); - RelationComparisonResult = /* @__PURE__ */ ((RelationComparisonResult3) => { + RelationComparisonResult = /* @__PURE__ */(RelationComparisonResult3 => { RelationComparisonResult3[RelationComparisonResult3["Succeeded"] = 1] = "Succeeded"; RelationComparisonResult3[RelationComparisonResult3["Failed"] = 2] = "Failed"; RelationComparisonResult3[RelationComparisonResult3["Reported"] = 4] = "Reported"; @@ -4005,7 +3875,7 @@ ${lanes.join("\n")} RelationComparisonResult3[RelationComparisonResult3["ReportsMask"] = 24] = "ReportsMask"; return RelationComparisonResult3; })(RelationComparisonResult || {}); - GeneratedIdentifierFlags = /* @__PURE__ */ ((GeneratedIdentifierFlags2) => { + GeneratedIdentifierFlags = /* @__PURE__ */(GeneratedIdentifierFlags2 => { GeneratedIdentifierFlags2[GeneratedIdentifierFlags2["None"] = 0] = "None"; GeneratedIdentifierFlags2[GeneratedIdentifierFlags2["Auto"] = 1] = "Auto"; GeneratedIdentifierFlags2[GeneratedIdentifierFlags2["Loop"] = 2] = "Loop"; @@ -4018,7 +3888,7 @@ ${lanes.join("\n")} GeneratedIdentifierFlags2[GeneratedIdentifierFlags2["AllowNameSubstitution"] = 64] = "AllowNameSubstitution"; return GeneratedIdentifierFlags2; })(GeneratedIdentifierFlags || {}); - TokenFlags = /* @__PURE__ */ ((TokenFlags2) => { + TokenFlags = /* @__PURE__ */(TokenFlags2 => { TokenFlags2[TokenFlags2["None"] = 0] = "None"; TokenFlags2[TokenFlags2["PrecedingLineBreak"] = 1] = "PrecedingLineBreak"; TokenFlags2[TokenFlags2["PrecedingJSDocComment"] = 2] = "PrecedingJSDocComment"; @@ -4043,7 +3913,7 @@ ${lanes.join("\n")} TokenFlags2[TokenFlags2["IsInvalid"] = 26656] = "IsInvalid"; return TokenFlags2; })(TokenFlags || {}); - FlowFlags = /* @__PURE__ */ ((FlowFlags2) => { + FlowFlags = /* @__PURE__ */(FlowFlags2 => { FlowFlags2[FlowFlags2["Unreachable"] = 1] = "Unreachable"; FlowFlags2[FlowFlags2["Start"] = 2] = "Start"; FlowFlags2[FlowFlags2["BranchLabel"] = 4] = "BranchLabel"; @@ -4061,14 +3931,13 @@ ${lanes.join("\n")} FlowFlags2[FlowFlags2["Condition"] = 96] = "Condition"; return FlowFlags2; })(FlowFlags || {}); - CommentDirectiveType = /* @__PURE__ */ ((CommentDirectiveType2) => { + CommentDirectiveType = /* @__PURE__ */(CommentDirectiveType2 => { CommentDirectiveType2[CommentDirectiveType2["ExpectError"] = 0] = "ExpectError"; CommentDirectiveType2[CommentDirectiveType2["Ignore"] = 1] = "Ignore"; return CommentDirectiveType2; })(CommentDirectiveType || {}); - OperationCanceledException = class { - }; - FileIncludeKind = /* @__PURE__ */ ((FileIncludeKind2) => { + OperationCanceledException = class {}; + FileIncludeKind = /* @__PURE__ */(FileIncludeKind2 => { FileIncludeKind2[FileIncludeKind2["RootFile"] = 0] = "RootFile"; FileIncludeKind2[FileIncludeKind2["SourceFromProjectReference"] = 1] = "SourceFromProjectReference"; FileIncludeKind2[FileIncludeKind2["OutputFromProjectReference"] = 2] = "OutputFromProjectReference"; @@ -4080,24 +3949,24 @@ ${lanes.join("\n")} FileIncludeKind2[FileIncludeKind2["AutomaticTypeDirectiveFile"] = 8] = "AutomaticTypeDirectiveFile"; return FileIncludeKind2; })(FileIncludeKind || {}); - FilePreprocessingDiagnosticsKind = /* @__PURE__ */ ((FilePreprocessingDiagnosticsKind2) => { + FilePreprocessingDiagnosticsKind = /* @__PURE__ */(FilePreprocessingDiagnosticsKind2 => { FilePreprocessingDiagnosticsKind2[FilePreprocessingDiagnosticsKind2["FilePreprocessingReferencedDiagnostic"] = 0] = "FilePreprocessingReferencedDiagnostic"; FilePreprocessingDiagnosticsKind2[FilePreprocessingDiagnosticsKind2["FilePreprocessingFileExplainingDiagnostic"] = 1] = "FilePreprocessingFileExplainingDiagnostic"; FilePreprocessingDiagnosticsKind2[FilePreprocessingDiagnosticsKind2["ResolutionDiagnostics"] = 2] = "ResolutionDiagnostics"; return FilePreprocessingDiagnosticsKind2; })(FilePreprocessingDiagnosticsKind || {}); - EmitOnly = /* @__PURE__ */ ((EmitOnly4) => { + EmitOnly = /* @__PURE__ */(EmitOnly4 => { EmitOnly4[EmitOnly4["Js"] = 0] = "Js"; EmitOnly4[EmitOnly4["Dts"] = 1] = "Dts"; return EmitOnly4; })(EmitOnly || {}); - StructureIsReused = /* @__PURE__ */ ((StructureIsReused2) => { + StructureIsReused = /* @__PURE__ */(StructureIsReused2 => { StructureIsReused2[StructureIsReused2["Not"] = 0] = "Not"; StructureIsReused2[StructureIsReused2["SafeModules"] = 1] = "SafeModules"; StructureIsReused2[StructureIsReused2["Completely"] = 2] = "Completely"; return StructureIsReused2; })(StructureIsReused || {}); - ExitStatus = /* @__PURE__ */ ((ExitStatus2) => { + ExitStatus = /* @__PURE__ */(ExitStatus2 => { ExitStatus2[ExitStatus2["Success"] = 0] = "Success"; ExitStatus2[ExitStatus2["DiagnosticsPresent_OutputsSkipped"] = 1] = "DiagnosticsPresent_OutputsSkipped"; ExitStatus2[ExitStatus2["DiagnosticsPresent_OutputsGenerated"] = 2] = "DiagnosticsPresent_OutputsGenerated"; @@ -4105,19 +3974,19 @@ ${lanes.join("\n")} ExitStatus2[ExitStatus2["ProjectReferenceCycle_OutputsSkipped"] = 4] = "ProjectReferenceCycle_OutputsSkipped"; return ExitStatus2; })(ExitStatus || {}); - MemberOverrideStatus = /* @__PURE__ */ ((MemberOverrideStatus2) => { + MemberOverrideStatus = /* @__PURE__ */(MemberOverrideStatus2 => { MemberOverrideStatus2[MemberOverrideStatus2["Ok"] = 0] = "Ok"; MemberOverrideStatus2[MemberOverrideStatus2["NeedsOverride"] = 1] = "NeedsOverride"; MemberOverrideStatus2[MemberOverrideStatus2["HasInvalidOverride"] = 2] = "HasInvalidOverride"; return MemberOverrideStatus2; })(MemberOverrideStatus || {}); - UnionReduction = /* @__PURE__ */ ((UnionReduction2) => { + UnionReduction = /* @__PURE__ */(UnionReduction2 => { UnionReduction2[UnionReduction2["None"] = 0] = "None"; UnionReduction2[UnionReduction2["Literal"] = 1] = "Literal"; UnionReduction2[UnionReduction2["Subtype"] = 2] = "Subtype"; return UnionReduction2; })(UnionReduction || {}); - ContextFlags = /* @__PURE__ */ ((ContextFlags3) => { + ContextFlags = /* @__PURE__ */(ContextFlags3 => { ContextFlags3[ContextFlags3["None"] = 0] = "None"; ContextFlags3[ContextFlags3["Signature"] = 1] = "Signature"; ContextFlags3[ContextFlags3["NoConstraints"] = 2] = "NoConstraints"; @@ -4125,7 +3994,7 @@ ${lanes.join("\n")} ContextFlags3[ContextFlags3["SkipBindingPatterns"] = 8] = "SkipBindingPatterns"; return ContextFlags3; })(ContextFlags || {}); - NodeBuilderFlags = /* @__PURE__ */ ((NodeBuilderFlags2) => { + NodeBuilderFlags = /* @__PURE__ */(NodeBuilderFlags2 => { NodeBuilderFlags2[NodeBuilderFlags2["None"] = 0] = "None"; NodeBuilderFlags2[NodeBuilderFlags2["NoTruncation"] = 1] = "NoTruncation"; NodeBuilderFlags2[NodeBuilderFlags2["WriteArrayAsGenericType"] = 2] = "WriteArrayAsGenericType"; @@ -4161,7 +4030,7 @@ ${lanes.join("\n")} NodeBuilderFlags2[NodeBuilderFlags2["InInitialEntityName"] = 16777216] = "InInitialEntityName"; return NodeBuilderFlags2; })(NodeBuilderFlags || {}); - TypeFormatFlags = /* @__PURE__ */ ((TypeFormatFlags2) => { + TypeFormatFlags = /* @__PURE__ */(TypeFormatFlags2 => { TypeFormatFlags2[TypeFormatFlags2["None"] = 0] = "None"; TypeFormatFlags2[TypeFormatFlags2["NoTruncation"] = 1] = "NoTruncation"; TypeFormatFlags2[TypeFormatFlags2["WriteArrayAsGenericType"] = 2] = "WriteArrayAsGenericType"; @@ -4187,7 +4056,7 @@ ${lanes.join("\n")} TypeFormatFlags2[TypeFormatFlags2["NodeBuilderFlagsMask"] = 848330091] = "NodeBuilderFlagsMask"; return TypeFormatFlags2; })(TypeFormatFlags || {}); - SymbolFormatFlags = /* @__PURE__ */ ((SymbolFormatFlags2) => { + SymbolFormatFlags = /* @__PURE__ */(SymbolFormatFlags2 => { SymbolFormatFlags2[SymbolFormatFlags2["None"] = 0] = "None"; SymbolFormatFlags2[SymbolFormatFlags2["WriteTypeParametersOrArguments"] = 1] = "WriteTypeParametersOrArguments"; SymbolFormatFlags2[SymbolFormatFlags2["UseOnlyExternalAliasing"] = 2] = "UseOnlyExternalAliasing"; @@ -4197,25 +4066,25 @@ ${lanes.join("\n")} SymbolFormatFlags2[SymbolFormatFlags2["DoNotIncludeSymbolChain"] = 32] = "DoNotIncludeSymbolChain"; return SymbolFormatFlags2; })(SymbolFormatFlags || {}); - SymbolAccessibility = /* @__PURE__ */ ((SymbolAccessibility2) => { + SymbolAccessibility = /* @__PURE__ */(SymbolAccessibility2 => { SymbolAccessibility2[SymbolAccessibility2["Accessible"] = 0] = "Accessible"; SymbolAccessibility2[SymbolAccessibility2["NotAccessible"] = 1] = "NotAccessible"; SymbolAccessibility2[SymbolAccessibility2["CannotBeNamed"] = 2] = "CannotBeNamed"; return SymbolAccessibility2; })(SymbolAccessibility || {}); - SyntheticSymbolKind = /* @__PURE__ */ ((SyntheticSymbolKind2) => { + SyntheticSymbolKind = /* @__PURE__ */(SyntheticSymbolKind2 => { SyntheticSymbolKind2[SyntheticSymbolKind2["UnionOrIntersection"] = 0] = "UnionOrIntersection"; SyntheticSymbolKind2[SyntheticSymbolKind2["Spread"] = 1] = "Spread"; return SyntheticSymbolKind2; })(SyntheticSymbolKind || {}); - TypePredicateKind = /* @__PURE__ */ ((TypePredicateKind2) => { + TypePredicateKind = /* @__PURE__ */(TypePredicateKind2 => { TypePredicateKind2[TypePredicateKind2["This"] = 0] = "This"; TypePredicateKind2[TypePredicateKind2["Identifier"] = 1] = "Identifier"; TypePredicateKind2[TypePredicateKind2["AssertsThis"] = 2] = "AssertsThis"; TypePredicateKind2[TypePredicateKind2["AssertsIdentifier"] = 3] = "AssertsIdentifier"; return TypePredicateKind2; })(TypePredicateKind || {}); - TypeReferenceSerializationKind = /* @__PURE__ */ ((TypeReferenceSerializationKind2) => { + TypeReferenceSerializationKind = /* @__PURE__ */(TypeReferenceSerializationKind2 => { TypeReferenceSerializationKind2[TypeReferenceSerializationKind2["Unknown"] = 0] = "Unknown"; TypeReferenceSerializationKind2[TypeReferenceSerializationKind2["TypeWithConstructSignatureAndValue"] = 1] = "TypeWithConstructSignatureAndValue"; TypeReferenceSerializationKind2[TypeReferenceSerializationKind2["VoidNullableOrNeverType"] = 2] = "VoidNullableOrNeverType"; @@ -4230,7 +4099,7 @@ ${lanes.join("\n")} TypeReferenceSerializationKind2[TypeReferenceSerializationKind2["ObjectType"] = 11] = "ObjectType"; return TypeReferenceSerializationKind2; })(TypeReferenceSerializationKind || {}); - SymbolFlags = /* @__PURE__ */ ((SymbolFlags3) => { + SymbolFlags = /* @__PURE__ */(SymbolFlags3 => { SymbolFlags3[SymbolFlags3["None"] = 0] = "None"; SymbolFlags3[SymbolFlags3["FunctionScopedVariable"] = 1] = "FunctionScopedVariable"; SymbolFlags3[SymbolFlags3["BlockScopedVariable"] = 2] = "BlockScopedVariable"; @@ -4298,12 +4167,12 @@ ${lanes.join("\n")} SymbolFlags3[SymbolFlags3["LateBindingContainer"] = 6256] = "LateBindingContainer"; return SymbolFlags3; })(SymbolFlags || {}); - EnumKind = /* @__PURE__ */ ((EnumKind2) => { + EnumKind = /* @__PURE__ */(EnumKind2 => { EnumKind2[EnumKind2["Numeric"] = 0] = "Numeric"; EnumKind2[EnumKind2["Literal"] = 1] = "Literal"; return EnumKind2; })(EnumKind || {}); - CheckFlags = /* @__PURE__ */ ((CheckFlags2) => { + CheckFlags = /* @__PURE__ */(CheckFlags2 => { CheckFlags2[CheckFlags2["None"] = 0] = "None"; CheckFlags2[CheckFlags2["Instantiated"] = 1] = "Instantiated"; CheckFlags2[CheckFlags2["SyntheticProperty"] = 2] = "SyntheticProperty"; @@ -4331,7 +4200,7 @@ ${lanes.join("\n")} CheckFlags2[CheckFlags2["Partial"] = 48] = "Partial"; return CheckFlags2; })(CheckFlags || {}); - InternalSymbolName = /* @__PURE__ */ ((InternalSymbolName2) => { + InternalSymbolName = /* @__PURE__ */(InternalSymbolName2 => { InternalSymbolName2["Call"] = "__call"; InternalSymbolName2["Constructor"] = "__constructor"; InternalSymbolName2["New"] = "__new"; @@ -4351,7 +4220,7 @@ ${lanes.join("\n")} InternalSymbolName2["This"] = "this"; return InternalSymbolName2; })(InternalSymbolName || {}); - NodeCheckFlags = /* @__PURE__ */ ((NodeCheckFlags2) => { + NodeCheckFlags = /* @__PURE__ */(NodeCheckFlags2 => { NodeCheckFlags2[NodeCheckFlags2["None"] = 0] = "None"; NodeCheckFlags2[NodeCheckFlags2["TypeChecked"] = 1] = "TypeChecked"; NodeCheckFlags2[NodeCheckFlags2["LexicalThis"] = 2] = "LexicalThis"; @@ -4378,7 +4247,7 @@ ${lanes.join("\n")} NodeCheckFlags2[NodeCheckFlags2["InCheckIdentifier"] = 4194304] = "InCheckIdentifier"; return NodeCheckFlags2; })(NodeCheckFlags || {}); - TypeFlags = /* @__PURE__ */ ((TypeFlags2) => { + TypeFlags = /* @__PURE__ */(TypeFlags2 => { TypeFlags2[TypeFlags2["Any"] = 1] = "Any"; TypeFlags2[TypeFlags2["Unknown"] = 2] = "Unknown"; TypeFlags2[TypeFlags2["String"] = 4] = "String"; @@ -4448,7 +4317,7 @@ ${lanes.join("\n")} TypeFlags2[TypeFlags2["NotPrimitiveUnion"] = 36323331] = "NotPrimitiveUnion"; return TypeFlags2; })(TypeFlags || {}); - ObjectFlags = /* @__PURE__ */ ((ObjectFlags3) => { + ObjectFlags = /* @__PURE__ */(ObjectFlags3 => { ObjectFlags3[ObjectFlags3["None"] = 0] = "None"; ObjectFlags3[ObjectFlags3["Class"] = 1] = "Class"; ObjectFlags3[ObjectFlags3["Interface"] = 2] = "Interface"; @@ -4493,7 +4362,7 @@ ${lanes.join("\n")} ObjectFlags3[ObjectFlags3["IsNeverIntersection"] = 33554432] = "IsNeverIntersection"; return ObjectFlags3; })(ObjectFlags || {}); - VarianceFlags = /* @__PURE__ */ ((VarianceFlags2) => { + VarianceFlags = /* @__PURE__ */(VarianceFlags2 => { VarianceFlags2[VarianceFlags2["Invariant"] = 0] = "Invariant"; VarianceFlags2[VarianceFlags2["Covariant"] = 1] = "Covariant"; VarianceFlags2[VarianceFlags2["Contravariant"] = 2] = "Contravariant"; @@ -4505,7 +4374,7 @@ ${lanes.join("\n")} VarianceFlags2[VarianceFlags2["AllowsStructuralFallback"] = 24] = "AllowsStructuralFallback"; return VarianceFlags2; })(VarianceFlags || {}); - ElementFlags = /* @__PURE__ */ ((ElementFlags2) => { + ElementFlags = /* @__PURE__ */(ElementFlags2 => { ElementFlags2[ElementFlags2["Required"] = 1] = "Required"; ElementFlags2[ElementFlags2["Optional"] = 2] = "Optional"; ElementFlags2[ElementFlags2["Rest"] = 4] = "Rest"; @@ -4516,7 +4385,7 @@ ${lanes.join("\n")} ElementFlags2[ElementFlags2["NonRest"] = 11] = "NonRest"; return ElementFlags2; })(ElementFlags || {}); - AccessFlags = /* @__PURE__ */ ((AccessFlags2) => { + AccessFlags = /* @__PURE__ */(AccessFlags2 => { AccessFlags2[AccessFlags2["None"] = 0] = "None"; AccessFlags2[AccessFlags2["IncludeUndefined"] = 1] = "IncludeUndefined"; AccessFlags2[AccessFlags2["NoIndexSignatures"] = 2] = "NoIndexSignatures"; @@ -4530,25 +4399,25 @@ ${lanes.join("\n")} AccessFlags2[AccessFlags2["Persistent"] = 1 /* IncludeUndefined */] = "Persistent"; return AccessFlags2; })(AccessFlags || {}); - IndexFlags = /* @__PURE__ */ ((IndexFlags2) => { + IndexFlags = /* @__PURE__ */(IndexFlags2 => { IndexFlags2[IndexFlags2["None"] = 0] = "None"; IndexFlags2[IndexFlags2["StringsOnly"] = 1] = "StringsOnly"; IndexFlags2[IndexFlags2["NoIndexSignatures"] = 2] = "NoIndexSignatures"; IndexFlags2[IndexFlags2["NoReducibleCheck"] = 4] = "NoReducibleCheck"; return IndexFlags2; })(IndexFlags || {}); - JsxReferenceKind = /* @__PURE__ */ ((JsxReferenceKind2) => { + JsxReferenceKind = /* @__PURE__ */(JsxReferenceKind2 => { JsxReferenceKind2[JsxReferenceKind2["Component"] = 0] = "Component"; JsxReferenceKind2[JsxReferenceKind2["Function"] = 1] = "Function"; JsxReferenceKind2[JsxReferenceKind2["Mixed"] = 2] = "Mixed"; return JsxReferenceKind2; })(JsxReferenceKind || {}); - SignatureKind = /* @__PURE__ */ ((SignatureKind2) => { + SignatureKind = /* @__PURE__ */(SignatureKind2 => { SignatureKind2[SignatureKind2["Call"] = 0] = "Call"; SignatureKind2[SignatureKind2["Construct"] = 1] = "Construct"; return SignatureKind2; })(SignatureKind || {}); - SignatureFlags = /* @__PURE__ */ ((SignatureFlags5) => { + SignatureFlags = /* @__PURE__ */(SignatureFlags5 => { SignatureFlags5[SignatureFlags5["None"] = 0] = "None"; SignatureFlags5[SignatureFlags5["HasRestParameter"] = 1] = "HasRestParameter"; SignatureFlags5[SignatureFlags5["HasLiteralTypes"] = 2] = "HasLiteralTypes"; @@ -4562,12 +4431,12 @@ ${lanes.join("\n")} SignatureFlags5[SignatureFlags5["CallChainFlags"] = 24] = "CallChainFlags"; return SignatureFlags5; })(SignatureFlags || {}); - IndexKind = /* @__PURE__ */ ((IndexKind2) => { + IndexKind = /* @__PURE__ */(IndexKind2 => { IndexKind2[IndexKind2["String"] = 0] = "String"; IndexKind2[IndexKind2["Number"] = 1] = "Number"; return IndexKind2; })(IndexKind || {}); - TypeMapKind = /* @__PURE__ */ ((TypeMapKind2) => { + TypeMapKind = /* @__PURE__ */(TypeMapKind2 => { TypeMapKind2[TypeMapKind2["Simple"] = 0] = "Simple"; TypeMapKind2[TypeMapKind2["Array"] = 1] = "Array"; TypeMapKind2[TypeMapKind2["Deferred"] = 2] = "Deferred"; @@ -4576,7 +4445,7 @@ ${lanes.join("\n")} TypeMapKind2[TypeMapKind2["Merged"] = 5] = "Merged"; return TypeMapKind2; })(TypeMapKind || {}); - InferencePriority = /* @__PURE__ */ ((InferencePriority2) => { + InferencePriority = /* @__PURE__ */(InferencePriority2 => { InferencePriority2[InferencePriority2["None"] = 0] = "None"; InferencePriority2[InferencePriority2["NakedTypeVariable"] = 1] = "NakedTypeVariable"; InferencePriority2[InferencePriority2["SpeculativeTuple"] = 2] = "SpeculativeTuple"; @@ -4594,21 +4463,21 @@ ${lanes.join("\n")} InferencePriority2[InferencePriority2["Circularity"] = -1] = "Circularity"; return InferencePriority2; })(InferencePriority || {}); - InferenceFlags = /* @__PURE__ */ ((InferenceFlags2) => { + InferenceFlags = /* @__PURE__ */(InferenceFlags2 => { InferenceFlags2[InferenceFlags2["None"] = 0] = "None"; InferenceFlags2[InferenceFlags2["NoDefault"] = 1] = "NoDefault"; InferenceFlags2[InferenceFlags2["AnyDefault"] = 2] = "AnyDefault"; InferenceFlags2[InferenceFlags2["SkippedGenericFunction"] = 4] = "SkippedGenericFunction"; return InferenceFlags2; })(InferenceFlags || {}); - Ternary = /* @__PURE__ */ ((Ternary2) => { + Ternary = /* @__PURE__ */(Ternary2 => { Ternary2[Ternary2["False"] = 0] = "False"; Ternary2[Ternary2["Unknown"] = 1] = "Unknown"; Ternary2[Ternary2["Maybe"] = 3] = "Maybe"; Ternary2[Ternary2["True"] = -1] = "True"; return Ternary2; })(Ternary || {}); - AssignmentDeclarationKind = /* @__PURE__ */ ((AssignmentDeclarationKind2) => { + AssignmentDeclarationKind = /* @__PURE__ */(AssignmentDeclarationKind2 => { AssignmentDeclarationKind2[AssignmentDeclarationKind2["None"] = 0] = "None"; AssignmentDeclarationKind2[AssignmentDeclarationKind2["ExportsProperty"] = 1] = "ExportsProperty"; AssignmentDeclarationKind2[AssignmentDeclarationKind2["ModuleExports"] = 2] = "ModuleExports"; @@ -4621,14 +4490,14 @@ ${lanes.join("\n")} AssignmentDeclarationKind2[AssignmentDeclarationKind2["ObjectDefinePrototypeProperty"] = 9] = "ObjectDefinePrototypeProperty"; return AssignmentDeclarationKind2; })(AssignmentDeclarationKind || {}); - DiagnosticCategory = /* @__PURE__ */ ((DiagnosticCategory2) => { + DiagnosticCategory = /* @__PURE__ */(DiagnosticCategory2 => { DiagnosticCategory2[DiagnosticCategory2["Warning"] = 0] = "Warning"; DiagnosticCategory2[DiagnosticCategory2["Error"] = 1] = "Error"; DiagnosticCategory2[DiagnosticCategory2["Suggestion"] = 2] = "Suggestion"; DiagnosticCategory2[DiagnosticCategory2["Message"] = 3] = "Message"; return DiagnosticCategory2; })(DiagnosticCategory || {}); - ModuleResolutionKind = /* @__PURE__ */ ((ModuleResolutionKind3) => { + ModuleResolutionKind = /* @__PURE__ */(ModuleResolutionKind3 => { ModuleResolutionKind3[ModuleResolutionKind3["Classic"] = 1] = "Classic"; ModuleResolutionKind3[ModuleResolutionKind3["NodeJs"] = 2] = "NodeJs"; ModuleResolutionKind3[ModuleResolutionKind3["Node10"] = 2] = "Node10"; @@ -4637,13 +4506,13 @@ ${lanes.join("\n")} ModuleResolutionKind3[ModuleResolutionKind3["Bundler"] = 100] = "Bundler"; return ModuleResolutionKind3; })(ModuleResolutionKind || {}); - ModuleDetectionKind = /* @__PURE__ */ ((ModuleDetectionKind2) => { + ModuleDetectionKind = /* @__PURE__ */(ModuleDetectionKind2 => { ModuleDetectionKind2[ModuleDetectionKind2["Legacy"] = 1] = "Legacy"; ModuleDetectionKind2[ModuleDetectionKind2["Auto"] = 2] = "Auto"; ModuleDetectionKind2[ModuleDetectionKind2["Force"] = 3] = "Force"; return ModuleDetectionKind2; })(ModuleDetectionKind || {}); - WatchFileKind = /* @__PURE__ */ ((WatchFileKind3) => { + WatchFileKind = /* @__PURE__ */(WatchFileKind3 => { WatchFileKind3[WatchFileKind3["FixedPollingInterval"] = 0] = "FixedPollingInterval"; WatchFileKind3[WatchFileKind3["PriorityPollingInterval"] = 1] = "PriorityPollingInterval"; WatchFileKind3[WatchFileKind3["DynamicPriorityPolling"] = 2] = "DynamicPriorityPolling"; @@ -4652,21 +4521,21 @@ ${lanes.join("\n")} WatchFileKind3[WatchFileKind3["UseFsEventsOnParentDirectory"] = 5] = "UseFsEventsOnParentDirectory"; return WatchFileKind3; })(WatchFileKind || {}); - WatchDirectoryKind = /* @__PURE__ */ ((WatchDirectoryKind3) => { + WatchDirectoryKind = /* @__PURE__ */(WatchDirectoryKind3 => { WatchDirectoryKind3[WatchDirectoryKind3["UseFsEvents"] = 0] = "UseFsEvents"; WatchDirectoryKind3[WatchDirectoryKind3["FixedPollingInterval"] = 1] = "FixedPollingInterval"; WatchDirectoryKind3[WatchDirectoryKind3["DynamicPriorityPolling"] = 2] = "DynamicPriorityPolling"; WatchDirectoryKind3[WatchDirectoryKind3["FixedChunkSizePolling"] = 3] = "FixedChunkSizePolling"; return WatchDirectoryKind3; })(WatchDirectoryKind || {}); - PollingWatchKind = /* @__PURE__ */ ((PollingWatchKind3) => { + PollingWatchKind = /* @__PURE__ */(PollingWatchKind3 => { PollingWatchKind3[PollingWatchKind3["FixedInterval"] = 0] = "FixedInterval"; PollingWatchKind3[PollingWatchKind3["PriorityInterval"] = 1] = "PriorityInterval"; PollingWatchKind3[PollingWatchKind3["DynamicPriority"] = 2] = "DynamicPriority"; PollingWatchKind3[PollingWatchKind3["FixedChunkSize"] = 3] = "FixedChunkSize"; return PollingWatchKind3; })(PollingWatchKind || {}); - ModuleKind = /* @__PURE__ */ ((ModuleKind3) => { + ModuleKind = /* @__PURE__ */(ModuleKind3 => { ModuleKind3[ModuleKind3["None"] = 0] = "None"; ModuleKind3[ModuleKind3["CommonJS"] = 1] = "CommonJS"; ModuleKind3[ModuleKind3["AMD"] = 2] = "AMD"; @@ -4680,7 +4549,7 @@ ${lanes.join("\n")} ModuleKind3[ModuleKind3["NodeNext"] = 199] = "NodeNext"; return ModuleKind3; })(ModuleKind || {}); - JsxEmit = /* @__PURE__ */ ((JsxEmit3) => { + JsxEmit = /* @__PURE__ */(JsxEmit3 => { JsxEmit3[JsxEmit3["None"] = 0] = "None"; JsxEmit3[JsxEmit3["Preserve"] = 1] = "Preserve"; JsxEmit3[JsxEmit3["React"] = 2] = "React"; @@ -4689,18 +4558,18 @@ ${lanes.join("\n")} JsxEmit3[JsxEmit3["ReactJSXDev"] = 5] = "ReactJSXDev"; return JsxEmit3; })(JsxEmit || {}); - ImportsNotUsedAsValues = /* @__PURE__ */ ((ImportsNotUsedAsValues2) => { + ImportsNotUsedAsValues = /* @__PURE__ */(ImportsNotUsedAsValues2 => { ImportsNotUsedAsValues2[ImportsNotUsedAsValues2["Remove"] = 0] = "Remove"; ImportsNotUsedAsValues2[ImportsNotUsedAsValues2["Preserve"] = 1] = "Preserve"; ImportsNotUsedAsValues2[ImportsNotUsedAsValues2["Error"] = 2] = "Error"; return ImportsNotUsedAsValues2; })(ImportsNotUsedAsValues || {}); - NewLineKind = /* @__PURE__ */ ((NewLineKind3) => { + NewLineKind = /* @__PURE__ */(NewLineKind3 => { NewLineKind3[NewLineKind3["CarriageReturnLineFeed"] = 0] = "CarriageReturnLineFeed"; NewLineKind3[NewLineKind3["LineFeed"] = 1] = "LineFeed"; return NewLineKind3; })(NewLineKind || {}); - ScriptKind = /* @__PURE__ */ ((ScriptKind7) => { + ScriptKind = /* @__PURE__ */(ScriptKind7 => { ScriptKind7[ScriptKind7["Unknown"] = 0] = "Unknown"; ScriptKind7[ScriptKind7["JS"] = 1] = "JS"; ScriptKind7[ScriptKind7["JSX"] = 2] = "JSX"; @@ -4711,7 +4580,7 @@ ${lanes.join("\n")} ScriptKind7[ScriptKind7["Deferred"] = 7] = "Deferred"; return ScriptKind7; })(ScriptKind || {}); - ScriptTarget = /* @__PURE__ */ ((ScriptTarget11) => { + ScriptTarget = /* @__PURE__ */(ScriptTarget11 => { ScriptTarget11[ScriptTarget11["ES3"] = 0] = "ES3"; ScriptTarget11[ScriptTarget11["ES5"] = 1] = "ES5"; ScriptTarget11[ScriptTarget11["ES2015"] = 2] = "ES2015"; @@ -4727,17 +4596,17 @@ ${lanes.join("\n")} ScriptTarget11[ScriptTarget11["Latest"] = 99 /* ESNext */] = "Latest"; return ScriptTarget11; })(ScriptTarget || {}); - LanguageVariant = /* @__PURE__ */ ((LanguageVariant4) => { + LanguageVariant = /* @__PURE__ */(LanguageVariant4 => { LanguageVariant4[LanguageVariant4["Standard"] = 0] = "Standard"; LanguageVariant4[LanguageVariant4["JSX"] = 1] = "JSX"; return LanguageVariant4; })(LanguageVariant || {}); - WatchDirectoryFlags = /* @__PURE__ */ ((WatchDirectoryFlags3) => { + WatchDirectoryFlags = /* @__PURE__ */(WatchDirectoryFlags3 => { WatchDirectoryFlags3[WatchDirectoryFlags3["None"] = 0] = "None"; WatchDirectoryFlags3[WatchDirectoryFlags3["Recursive"] = 1] = "Recursive"; return WatchDirectoryFlags3; })(WatchDirectoryFlags || {}); - CharacterCodes = /* @__PURE__ */ ((CharacterCodes2) => { + CharacterCodes = /* @__PURE__ */(CharacterCodes2 => { CharacterCodes2[CharacterCodes2["nullCharacter"] = 0] = "nullCharacter"; CharacterCodes2[CharacterCodes2["maxAsciiCharacter"] = 127] = "maxAsciiCharacter"; CharacterCodes2[CharacterCodes2["lineFeed"] = 10] = "lineFeed"; @@ -4865,7 +4734,7 @@ ${lanes.join("\n")} CharacterCodes2[CharacterCodes2["verticalTab"] = 11] = "verticalTab"; return CharacterCodes2; })(CharacterCodes || {}); - Extension = /* @__PURE__ */ ((Extension2) => { + Extension = /* @__PURE__ */(Extension2 => { Extension2["Ts"] = ".ts"; Extension2["Tsx"] = ".tsx"; Extension2["Dts"] = ".d.ts"; @@ -4881,7 +4750,7 @@ ${lanes.join("\n")} Extension2["Dcts"] = ".d.cts"; return Extension2; })(Extension || {}); - TransformFlags = /* @__PURE__ */ ((TransformFlags3) => { + TransformFlags = /* @__PURE__ */(TransformFlags3 => { TransformFlags3[TransformFlags3["None"] = 0] = "None"; TransformFlags3[TransformFlags3["ContainsTypeScript"] = 1] = "ContainsTypeScript"; TransformFlags3[TransformFlags3["ContainsJsx"] = 2] = "ContainsJsx"; @@ -4948,14 +4817,14 @@ ${lanes.join("\n")} TransformFlags3[TransformFlags3["PropertyNamePropagatingFlags"] = 134234112] = "PropertyNamePropagatingFlags"; return TransformFlags3; })(TransformFlags || {}); - SnippetKind = /* @__PURE__ */ ((SnippetKind3) => { + SnippetKind = /* @__PURE__ */(SnippetKind3 => { SnippetKind3[SnippetKind3["TabStop"] = 0] = "TabStop"; SnippetKind3[SnippetKind3["Placeholder"] = 1] = "Placeholder"; SnippetKind3[SnippetKind3["Choice"] = 2] = "Choice"; SnippetKind3[SnippetKind3["Variable"] = 3] = "Variable"; return SnippetKind3; })(SnippetKind || {}); - EmitFlags = /* @__PURE__ */ ((EmitFlags3) => { + EmitFlags = /* @__PURE__ */(EmitFlags3 => { EmitFlags3[EmitFlags3["None"] = 0] = "None"; EmitFlags3[EmitFlags3["SingleLine"] = 1] = "SingleLine"; EmitFlags3[EmitFlags3["MultiLine"] = 2] = "MultiLine"; @@ -4987,7 +4856,7 @@ ${lanes.join("\n")} EmitFlags3[EmitFlags3["NoAsciiEscaping"] = 16777216] = "NoAsciiEscaping"; return EmitFlags3; })(EmitFlags || {}); - InternalEmitFlags = /* @__PURE__ */ ((InternalEmitFlags3) => { + InternalEmitFlags = /* @__PURE__ */(InternalEmitFlags3 => { InternalEmitFlags3[InternalEmitFlags3["None"] = 0] = "None"; InternalEmitFlags3[InternalEmitFlags3["TypeScriptClassWrapper"] = 1] = "TypeScriptClassWrapper"; InternalEmitFlags3[InternalEmitFlags3["NeverApplyImportHelper"] = 2] = "NeverApplyImportHelper"; @@ -4997,7 +4866,7 @@ ${lanes.join("\n")} InternalEmitFlags3[InternalEmitFlags3["TransformPrivateStaticElements"] = 32] = "TransformPrivateStaticElements"; return InternalEmitFlags3; })(InternalEmitFlags || {}); - ExternalEmitHelpers = /* @__PURE__ */ ((ExternalEmitHelpers2) => { + ExternalEmitHelpers = /* @__PURE__ */(ExternalEmitHelpers2 => { ExternalEmitHelpers2[ExternalEmitHelpers2["Extends"] = 1] = "Extends"; ExternalEmitHelpers2[ExternalEmitHelpers2["Assign"] = 2] = "Assign"; ExternalEmitHelpers2[ExternalEmitHelpers2["Rest"] = 4] = "Rest"; @@ -5034,7 +4903,7 @@ ${lanes.join("\n")} ExternalEmitHelpers2[ExternalEmitHelpers2["SpreadIncludes"] = 1536] = "SpreadIncludes"; return ExternalEmitHelpers2; })(ExternalEmitHelpers || {}); - EmitHint = /* @__PURE__ */ ((EmitHint6) => { + EmitHint = /* @__PURE__ */(EmitHint6 => { EmitHint6[EmitHint6["SourceFile"] = 0] = "SourceFile"; EmitHint6[EmitHint6["Expression"] = 1] = "Expression"; EmitHint6[EmitHint6["IdentifierName"] = 2] = "IdentifierName"; @@ -5044,7 +4913,7 @@ ${lanes.join("\n")} EmitHint6[EmitHint6["JsxAttributeValue"] = 6] = "JsxAttributeValue"; return EmitHint6; })(EmitHint || {}); - OuterExpressionKinds = /* @__PURE__ */ ((OuterExpressionKinds2) => { + OuterExpressionKinds = /* @__PURE__ */(OuterExpressionKinds2 => { OuterExpressionKinds2[OuterExpressionKinds2["Parentheses"] = 1] = "Parentheses"; OuterExpressionKinds2[OuterExpressionKinds2["TypeAssertions"] = 2] = "TypeAssertions"; OuterExpressionKinds2[OuterExpressionKinds2["NonNullAssertions"] = 4] = "NonNullAssertions"; @@ -5054,13 +4923,13 @@ ${lanes.join("\n")} OuterExpressionKinds2[OuterExpressionKinds2["ExcludeJSDocTypeAssertion"] = 16] = "ExcludeJSDocTypeAssertion"; return OuterExpressionKinds2; })(OuterExpressionKinds || {}); - LexicalEnvironmentFlags = /* @__PURE__ */ ((LexicalEnvironmentFlags2) => { + LexicalEnvironmentFlags = /* @__PURE__ */(LexicalEnvironmentFlags2 => { LexicalEnvironmentFlags2[LexicalEnvironmentFlags2["None"] = 0] = "None"; LexicalEnvironmentFlags2[LexicalEnvironmentFlags2["InParameters"] = 1] = "InParameters"; LexicalEnvironmentFlags2[LexicalEnvironmentFlags2["VariablesHoistedInParameters"] = 2] = "VariablesHoistedInParameters"; return LexicalEnvironmentFlags2; })(LexicalEnvironmentFlags || {}); - BundleFileSectionKind = /* @__PURE__ */ ((BundleFileSectionKind2) => { + BundleFileSectionKind = /* @__PURE__ */(BundleFileSectionKind2 => { BundleFileSectionKind2["Prologue"] = "prologue"; BundleFileSectionKind2["EmitHelpers"] = "emitHelpers"; BundleFileSectionKind2["NoDefaultLib"] = "no-default-lib"; @@ -5074,7 +4943,7 @@ ${lanes.join("\n")} BundleFileSectionKind2["Internal"] = "internal"; return BundleFileSectionKind2; })(BundleFileSectionKind || {}); - ListFormat = /* @__PURE__ */ ((ListFormat2) => { + ListFormat = /* @__PURE__ */(ListFormat2 => { ListFormat2[ListFormat2["None"] = 0] = "None"; ListFormat2[ListFormat2["SingleLine"] = 0] = "SingleLine"; ListFormat2[ListFormat2["MultiLine"] = 1] = "MultiLine"; @@ -5146,7 +5015,7 @@ ${lanes.join("\n")} ListFormat2[ListFormat2["JSDocComment"] = 33] = "JSDocComment"; return ListFormat2; })(ListFormat || {}); - PragmaKindFlags = /* @__PURE__ */ ((PragmaKindFlags2) => { + PragmaKindFlags = /* @__PURE__ */(PragmaKindFlags2 => { PragmaKindFlags2[PragmaKindFlags2["None"] = 0] = "None"; PragmaKindFlags2[PragmaKindFlags2["TripleSlashXML"] = 1] = "TripleSlashXML"; PragmaKindFlags2[PragmaKindFlags2["SingleLine"] = 2] = "SingleLine"; @@ -5157,47 +5026,83 @@ ${lanes.join("\n")} })(PragmaKindFlags || {}); commentPragmas = { "reference": { - args: [ - { name: "types", optional: true, captureSpan: true }, - { name: "lib", optional: true, captureSpan: true }, - { name: "path", optional: true, captureSpan: true }, - { name: "no-default-lib", optional: true }, - { name: "resolution-mode", optional: true } - ], + args: [{ + name: "types", + optional: true, + captureSpan: true + }, { + name: "lib", + optional: true, + captureSpan: true + }, { + name: "path", + optional: true, + captureSpan: true + }, { + name: "no-default-lib", + optional: true + }, { + name: "resolution-mode", + optional: true + }], kind: 1 /* TripleSlashXML */ }, + "amd-dependency": { - args: [{ name: "path" }, { name: "name", optional: true }], + args: [{ + name: "path" + }, { + name: "name", + optional: true + }], kind: 1 /* TripleSlashXML */ }, + "amd-module": { - args: [{ name: "name" }], + args: [{ + name: "name" + }], kind: 1 /* TripleSlashXML */ }, + "ts-check": { kind: 2 /* SingleLine */ }, + "ts-nocheck": { kind: 2 /* SingleLine */ }, + "jsx": { - args: [{ name: "factory" }], + args: [{ + name: "factory" + }], kind: 4 /* MultiLine */ }, + "jsxfrag": { - args: [{ name: "factory" }], + args: [{ + name: "factory" + }], kind: 4 /* MultiLine */ }, + "jsximportsource": { - args: [{ name: "factory" }], + args: [{ + name: "factory" + }], kind: 4 /* MultiLine */ }, + "jsxruntime": { - args: [{ name: "factory" }], + args: [{ + name: "factory" + }], kind: 4 /* MultiLine */ } }; - JSDocParsingMode = /* @__PURE__ */ ((JSDocParsingMode6) => { + + JSDocParsingMode = /* @__PURE__ */(JSDocParsingMode6 => { JSDocParsingMode6[JSDocParsingMode6["ParseAll"] = 0] = "ParseAll"; JSDocParsingMode6[JSDocParsingMode6["ParseNone"] = 1] = "ParseNone"; JSDocParsingMode6[JSDocParsingMode6["ParseForTypeErrors"] = 2] = "ParseForTypeErrors"; @@ -5268,7 +5173,10 @@ ${lanes.join("\n")} } function getCustomPollingBasedLevels(baseVariable, defaultLevels) { const customLevels = getCustomLevels(baseVariable); - return (pollingIntervalChanged || customLevels) && createPollingIntervalBasedLevels(customLevels ? { ...defaultLevels, ...customLevels } : defaultLevels); + return (pollingIntervalChanged || customLevels) && createPollingIntervalBasedLevels(customLevels ? { + ...defaultLevels, + ...customLevels + } : defaultLevels); } } function pollWatchedFileQueue(host, queue, pollIndex, chunkSize, callbackOnWatchFileStat) { @@ -5348,26 +5256,16 @@ ${lanes.join("\n")} } } function pollLowPollingIntervalQueue(_timeoutType, queue) { - pollQueue( - changedFilesInLastPoll, - 250 /* Low */, - /*pollIndex*/ - 0, - changedFilesInLastPoll.length - ); + pollQueue(changedFilesInLastPoll, 250 /* Low */, /*pollIndex*/ + 0, changedFilesInLastPoll.length); pollPollingIntervalQueue(_timeoutType, queue); if (!queue.pollScheduled && changedFilesInLastPoll.length) { scheduleNextPoll(250 /* Low */); } } + function pollQueue(queue, pollingInterval, pollIndex, chunkSize) { - return pollWatchedFileQueue( - host, - queue, - pollIndex, - chunkSize, - onWatchFileStat - ); + return pollWatchedFileQueue(host, queue, pollIndex, chunkSize, onWatchFileStat); function onWatchFileStat(watchedFile, pollIndex2, fileChanged) { if (fileChanged) { watchedFile.unchangedPolls = 0; @@ -5388,6 +5286,7 @@ ${lanes.join("\n")} } } } + function pollingIntervalQueue(pollingInterval) { switch (pollingInterval) { case 250 /* Low */: @@ -5406,6 +5305,7 @@ ${lanes.join("\n")} changedFilesInLastPoll.push(file); scheduleNextPollIfNotAlreadyScheduled(250 /* Low */); } + function scheduleNextPollIfNotAlreadyScheduled(pollingInterval) { if (!pollingIntervalQueue(pollingInterval).pollScheduled) { scheduleNextPoll(pollingInterval); @@ -5417,7 +5317,7 @@ ${lanes.join("\n")} } function createUseFsEventsOnParentDirectoryWatchFile(fsWatch, useCaseSensitiveFileNames2) { const fileWatcherCallbacks = createMultiMap(); - const dirWatchers = /* @__PURE__ */ new Map(); + const dirWatchers = /* @__PURE__ */new Map(); const toCanonicalName = createGetCanonicalFileName(useCaseSensitiveFileNames2); return nonPollingWatchFile; function nonPollingWatchFile(fileName, callback, _pollingInterval, fallbackOptions) { @@ -5439,25 +5339,17 @@ ${lanes.join("\n")} }; } function createDirectoryWatcher(dirName, dirPath, fallbackOptions) { - const watcher = fsWatch( - dirName, - 1 /* Directory */, - (_eventName, relativeFileName, modifiedTime) => { - if (!isString(relativeFileName)) - return; - const fileName = getNormalizedAbsolutePath(relativeFileName, dirName); - const callbacks = fileName && fileWatcherCallbacks.get(toCanonicalName(fileName)); - if (callbacks) { - for (const fileCallback of callbacks) { - fileCallback(fileName, 1 /* Changed */, modifiedTime); - } + const watcher = fsWatch(dirName, 1 /* Directory */, (_eventName, relativeFileName, modifiedTime) => { + if (!isString(relativeFileName)) return; + const fileName = getNormalizedAbsolutePath(relativeFileName, dirName); + const callbacks = fileName && fileWatcherCallbacks.get(toCanonicalName(fileName)); + if (callbacks) { + for (const fileCallback of callbacks) { + fileCallback(fileName, 1 /* Changed */, modifiedTime); } - }, - /*recursive*/ - false, - 500 /* Medium */, - fallbackOptions - ); + } + }, /*recursive*/ + false, 500 /* Medium */, fallbackOptions); watcher.referenceCount = 0; dirWatchers.set(dirPath, watcher); return watcher; @@ -5489,8 +5381,7 @@ ${lanes.join("\n")} scheduleNextPoll(); } function scheduleNextPoll() { - if (!watchedFiles.length || pollScheduled) - return; + if (!watchedFiles.length || pollScheduled) return; pollScheduled = host.setTimeout(pollQueue, 2e3 /* High */, "pollQueue"); } } @@ -5503,22 +5394,19 @@ ${lanes.join("\n")} } else { cache.set(path, { watcher: createWatcher( - // Cant infer types correctly so lets satisfy checker - (param1, param2, param3) => { - var _a; - return (_a = cache.get(path)) == null ? void 0 : _a.callbacks.slice().forEach((cb) => cb(param1, param2, param3)); - } - ), + // Cant infer types correctly so lets satisfy checker + (param1, param2, param3) => { + var _a; + return (_a = cache.get(path)) == null ? void 0 : _a.callbacks.slice().forEach(cb => cb(param1, param2, param3)); + }), callbacks: [callback] }); } 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); } @@ -5537,6 +5425,7 @@ ${lanes.join("\n")} function getFileWatcherEventKind(oldTime, newTime) { return oldTime === 0 ? 0 /* Created */ : newTime === 0 ? 2 /* Deleted */ : 1 /* Changed */; } + function sysLog(s) { return curSysLog(s); } @@ -5553,9 +5442,9 @@ ${lanes.join("\n")} setTimeout: setTimeout2, clearTimeout: clearTimeout2 }) { - const cache = /* @__PURE__ */ new Map(); + const cache = /* @__PURE__ */new Map(); const callbackCache = createMultiMap(); - const cacheToUpdateChildWatches = /* @__PURE__ */ new Map(); + const cacheToUpdateChildWatches = /* @__PURE__ */new Map(); let timerToUpdateChildWatches; const filePathComparer = getStringComparer(!useCaseSensitiveFileNames2); const toCanonicalFilePath = createGetCanonicalFileName(useCaseSensitiveFileNames2); @@ -5567,29 +5456,26 @@ ${lanes.join("\n")} directoryWatcher.refCount++; } else { directoryWatcher = { - watcher: watchDirectory( - dirName, - (fileName) => { - if (isIgnoredPath(fileName, options)) - return; - if (options == null ? void 0 : options.synchronousWatchDirectory) { - invokeCallbacks(dirPath, fileName); - updateChildWatches(dirName, dirPath, options); - } else { - nonSyncUpdateChildWatches(dirName, dirPath, fileName, options); - } - }, - /*recursive*/ - false, - options - ), + watcher: watchDirectory(dirName, fileName => { + if (isIgnoredPath(fileName, options)) return; + if (options == null ? void 0 : options.synchronousWatchDirectory) { + invokeCallbacks(dirPath, fileName); + updateChildWatches(dirName, dirPath, options); + } else { + nonSyncUpdateChildWatches(dirName, dirPath, fileName, options); + } + }, /*recursive*/ + false, options), refCount: 1, childWatches: emptyArray }; cache.set(dirPath, directoryWatcher); updateChildWatches(dirName, dirPath, options); } - const callbackToAdd = callback && { dirName, callback }; + const callbackToAdd = callback && { + dirName, + callback + }; if (callbackToAdd) { callbackCache.add(dirPath, callbackToAdd); } @@ -5597,11 +5483,9 @@ ${lanes.join("\n")} dirName, close: () => { const directoryWatcher2 = Debug.checkDefined(cache.get(dirPath)); - if (callbackToAdd) - callbackCache.remove(dirPath, callbackToAdd); + if (callbackToAdd) callbackCache.remove(dirPath, callbackToAdd); directoryWatcher2.refCount--; - if (directoryWatcher2.refCount) - return; + if (directoryWatcher2.refCount) return; cache.delete(dirPath); closeFileWatcherOf(directoryWatcher2); directoryWatcher2.childWatches.forEach(closeFileWatcher); @@ -5617,8 +5501,7 @@ ${lanes.join("\n")} 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) { @@ -5632,7 +5515,9 @@ ${lanes.join("\n")} invokeMap.set(rootDirName, true); } } else { - callbacks.forEach(({ callback }) => callback(fileName)); + callbacks.forEach(({ + callback + }) => callback(fileName)); } } }); @@ -5651,7 +5536,11 @@ ${lanes.join("\n")} if (existing) { existing.fileNames.push(fileName); } else { - cacheToUpdateChildWatches.set(dirPath, { dirName, options, fileNames: [fileName] }); + cacheToUpdateChildWatches.set(dirPath, { + dirName, + options, + fileNames: [fileName] + }); } if (timerToUpdateChildWatches) { clearTimeout2(timerToUpdateChildWatches); @@ -5663,11 +5552,17 @@ ${lanes.join("\n")} timerToUpdateChildWatches = void 0; sysLog(`sysLog:: onTimerToUpdateChildWatches:: ${cacheToUpdateChildWatches.size}`); const start = timestamp(); - const invokeMap = /* @__PURE__ */ new Map(); + const invokeMap = /* @__PURE__ */new Map(); while (!timerToUpdateChildWatches && cacheToUpdateChildWatches.size) { const result = cacheToUpdateChildWatches.entries().next(); Debug.assert(!result.done); - const { value: [dirPath, { dirName, options, fileNames }] } = result; + const { + value: [dirPath, { + dirName, + options, + fileNames + }] + } = result; cacheToUpdateChildWatches.delete(dirPath); const hasChanges = updateChildWatches(dirName, dirPath, options); invokeCallbacks(dirPath, invokeMap, hasChanges ? void 0 : fileNames); @@ -5676,7 +5571,10 @@ ${lanes.join("\n")} callbackCache.forEach((callbacks, rootDirName) => { const existing = invokeMap.get(rootDirName); if (existing) { - callbacks.forEach(({ callback, dirName }) => { + callbacks.forEach(({ + callback, + dirName + }) => { if (isArray(existing)) { existing.forEach(callback); } else { @@ -5689,8 +5587,7 @@ ${lanes.join("\n")} 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) { @@ -5700,20 +5597,12 @@ ${lanes.join("\n")} } function updateChildWatches(parentDir, parentDirPath, options) { const parentWatcher = cache.get(parentDirPath); - if (!parentWatcher) - return false; + if (!parentWatcher) return false; let newChildWatches; - const hasChanges = enumerateInsertsAndDeletes( - fileSystemEntryExists(parentDir, 1 /* Directory */) ? mapDefined(getAccessibleSortedChildDirectories(parentDir), (child) => { - const childFullName = getNormalizedAbsolutePath(child, parentDir); - return !isIgnoredPath(childFullName, options) && filePathComparer(childFullName, normalizePath(realpath(childFullName))) === 0 /* EqualTo */ ? childFullName : void 0; - }) : emptyArray, - parentWatcher.childWatches, - (child, childWatcher) => filePathComparer(child, childWatcher.dirName), - createAndAddChildDirectoryWatcher, - closeFileWatcher, - addChildDirectoryWatcher - ); + const hasChanges = enumerateInsertsAndDeletes(fileSystemEntryExists(parentDir, 1 /* Directory */) ? mapDefined(getAccessibleSortedChildDirectories(parentDir), child => { + const childFullName = getNormalizedAbsolutePath(child, parentDir); + return !isIgnoredPath(childFullName, options) && filePathComparer(childFullName, normalizePath(realpath(childFullName))) === 0 /* EqualTo */ ? childFullName : void 0; + }) : emptyArray, parentWatcher.childWatches, (child, childWatcher) => filePathComparer(child, childWatcher.dirName), createAndAddChildDirectoryWatcher, closeFileWatcher, addChildDirectoryWatcher); parentWatcher.childWatches = newChildWatches || emptyArray; return hasChanges; function createAndAddChildDirectoryWatcher(childName) { @@ -5725,13 +5614,11 @@ ${lanes.join("\n")} } } function isIgnoredPath(path, options) { - return some(ignoredPaths, (searchPath) => isInPath(path, searchPath)) || isIgnoredByWatchOptions(path, options, useCaseSensitiveFileNames2, getCurrentDirectory); + 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); } } @@ -5779,9 +5666,9 @@ ${lanes.join("\n")} inodeWatching, sysLog: sysLog2 }) { - const pollingWatches = /* @__PURE__ */ new Map(); - const fsWatches = /* @__PURE__ */ new Map(); - const fsWatchesRecursive = /* @__PURE__ */ new Map(); + const pollingWatches = /* @__PURE__ */new Map(); + const fsWatches = /* @__PURE__ */new Map(); + const fsWatchesRecursive = /* @__PURE__ */new Map(); let dynamicPollingWatchFile; let fixedChunkSizePollingWatchFile; let nonPollingWatchFile; @@ -5796,48 +5683,21 @@ ${lanes.join("\n")} const watchFileKind = Debug.checkDefined(options.watchFile); switch (watchFileKind) { case 0 /* FixedPollingInterval */: - return pollingWatchFile( - fileName, - callback, - 250 /* Low */, - /*options*/ - void 0 - ); + return pollingWatchFile(fileName, callback, 250 /* Low */, /*options*/ + void 0); case 1 /* PriorityPollingInterval */: - return pollingWatchFile( - fileName, - callback, - pollingInterval, - /*options*/ - void 0 - ); + return pollingWatchFile(fileName, callback, pollingInterval, /*options*/ + void 0); case 2 /* DynamicPriorityPolling */: - return ensureDynamicPollingWatchFile()( - fileName, - callback, - pollingInterval, - /*options*/ - void 0 - ); + return ensureDynamicPollingWatchFile()(fileName, callback, pollingInterval, /*options*/ + void 0); case 3 /* FixedChunkSizePolling */: - return ensureFixedChunkSizePollingWatchFile()( - fileName, - callback, - /* pollingInterval */ - void 0, - /*options*/ - void 0 - ); + return ensureFixedChunkSizePollingWatchFile()(fileName, callback, /* pollingInterval */ + void 0, /*options*/ + void 0); case 4 /* UseFsEvents */: - return fsWatch( - fileName, - 0 /* File */, - createFsWatchCallbackForFileWatcherCallback(fileName, callback, getModifiedTime3), - /*recursive*/ - false, - pollingInterval, - getFallbackOptions(options) - ); + return fsWatch(fileName, 0 /* File */, createFsWatchCallbackForFileWatcherCallback(fileName, callback, getModifiedTime3), /*recursive*/ + false, pollingInterval, getFallbackOptions(options)); case 5 /* UseFsEventsOnParentDirectory */: if (!nonPollingWatchFile) { nonPollingWatchFile = createUseFsEventsOnParentDirectoryWatchFile(fsWatch, useCaseSensitiveFileNames2); @@ -5848,19 +5708,28 @@ ${lanes.join("\n")} } } function ensureDynamicPollingWatchFile() { - return dynamicPollingWatchFile || (dynamicPollingWatchFile = createDynamicPriorityPollingWatchFile({ getModifiedTime: getModifiedTime3, setTimeout: setTimeout2 })); + return dynamicPollingWatchFile || (dynamicPollingWatchFile = createDynamicPriorityPollingWatchFile({ + getModifiedTime: getModifiedTime3, + setTimeout: setTimeout2 + })); } function ensureFixedChunkSizePollingWatchFile() { - return fixedChunkSizePollingWatchFile || (fixedChunkSizePollingWatchFile = createFixedChunkSizePollingWatchFile({ getModifiedTime: getModifiedTime3, setTimeout: setTimeout2 })); + 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 */ }; + return { + watchFile: 1 /* PriorityPollingInterval */ + }; case "DynamicPriorityPolling": - return { watchFile: 2 /* DynamicPriorityPolling */ }; + return { + watchFile: 2 /* DynamicPriorityPolling */ + }; case "UseFsEvents": return generateWatchFileOptions(4 /* UseFsEvents */, 1 /* PriorityInterval */, options); case "UseFsEventsWithFallbackDynamicPolling": @@ -5868,15 +5737,16 @@ ${lanes.join("\n")} case "UseFsEventsOnParentDirectory": useNonPollingWatchers2 = true; default: - return useNonPollingWatchers2 ? ( - // Use notifications from FS to watch with falling back to fs.watchFile - generateWatchFileOptions(5 /* UseFsEventsOnParentDirectory */, 1 /* PriorityInterval */, options) - ) : ( - // Default to using fs events - { watchFile: 4 /* UseFsEvents */ } - ); + return useNonPollingWatchers2 ? + // Use notifications from FS to watch with falling back to fs.watchFile + generateWatchFileOptions(5 /* UseFsEventsOnParentDirectory */, 1 /* PriorityInterval */, options) : + // Default to using fs events + { + watchFile: 4 /* UseFsEvents */ + }; } } + function generateWatchFileOptions(watchFile3, fallbackPolling, options) { const defaultFallbackPolling = options == null ? void 0 : options.fallbackPolling; return { @@ -5886,14 +5756,7 @@ ${lanes.join("\n")} } function watchDirectory(directoryName, callback, recursive, options) { if (fsSupportsRecursiveFsWatch) { - return fsWatch( - directoryName, - 1 /* Directory */, - createFsWatchCallbackForDirectoryWatcherCallback(directoryName, callback, options, useCaseSensitiveFileNames2, getCurrentDirectory), - recursive, - 500 /* Medium */, - getFallbackOptions(options) - ); + return fsWatch(directoryName, 1 /* Directory */, createFsWatchCallbackForDirectoryWatcherCallback(directoryName, callback, options, useCaseSensitiveFileNames2, getCurrentDirectory), recursive, 500 /* Medium */, getFallbackOptions(options)); } if (!hostRecursiveDirectoryWatcher) { hostRecursiveDirectoryWatcher = createDirectoryWatcherSupportingRecursive({ @@ -5915,51 +5778,32 @@ ${lanes.join("\n")} const watchDirectoryKind = Debug.checkDefined(watchDirectoryOptions.watchDirectory); switch (watchDirectoryKind) { case 1 /* FixedPollingInterval */: - return pollingWatchFile( - directoryName, - () => callback(directoryName), - 500 /* Medium */, - /*options*/ - void 0 - ); + return pollingWatchFile(directoryName, () => callback(directoryName), 500 /* Medium */, /*options*/ + void 0); case 2 /* DynamicPriorityPolling */: - return ensureDynamicPollingWatchFile()( - directoryName, - () => callback(directoryName), - 500 /* Medium */, - /*options*/ - void 0 - ); + return ensureDynamicPollingWatchFile()(directoryName, () => callback(directoryName), 500 /* Medium */, /*options*/ + void 0); case 3 /* FixedChunkSizePolling */: - return ensureFixedChunkSizePollingWatchFile()( - directoryName, - () => callback(directoryName), - /* pollingInterval */ - void 0, - /*options*/ - void 0 - ); + return ensureFixedChunkSizePollingWatchFile()(directoryName, () => callback(directoryName), /* pollingInterval */ + void 0, /*options*/ + void 0); case 0 /* UseFsEvents */: - return fsWatch( - directoryName, - 1 /* Directory */, - createFsWatchCallbackForDirectoryWatcherCallback(directoryName, callback, options, useCaseSensitiveFileNames2, getCurrentDirectory), - recursive, - 500 /* Medium */, - getFallbackOptions(watchDirectoryOptions) - ); + return fsWatch(directoryName, 1 /* Directory */, createFsWatchCallbackForDirectoryWatcherCallback(directoryName, callback, options, useCaseSensitiveFileNames2, getCurrentDirectory), recursive, 500 /* Medium */, getFallbackOptions(watchDirectoryOptions)); default: Debug.assertNever(watchDirectoryKind); } } 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 */ }; + return { + watchDirectory: 1 /* FixedPollingInterval */ + }; case "RecursiveDirectoryUsingDynamicPriorityPolling": - return { watchDirectory: 2 /* DynamicPriorityPolling */ }; + return { + watchDirectory: 2 /* DynamicPriorityPolling */ + }; default: const defaultFallbackPolling = options == null ? void 0 : options.fallbackPolling; return { @@ -5969,22 +5813,10 @@ ${lanes.join("\n")} } } function pollingWatchFile(fileName, callback, pollingInterval, options) { - return createSingleWatcherPerName( - pollingWatches, - useCaseSensitiveFileNames2, - fileName, - callback, - (cb) => pollingWatchFileWorker(fileName, cb, pollingInterval, options) - ); + return createSingleWatcherPerName(pollingWatches, useCaseSensitiveFileNames2, fileName, callback, cb => pollingWatchFileWorker(fileName, cb, pollingInterval, options)); } function fsWatch(fileOrDirectory, entryKind, callback, recursive, fallbackPollingInterval, fallbackOptions) { - return createSingleWatcherPerName( - recursive ? fsWatchesRecursive : fsWatches, - useCaseSensitiveFileNames2, - fileOrDirectory, - callback, - (cb) => fsWatchHandlingExistenceOnHost(fileOrDirectory, entryKind, cb, recursive, fallbackPollingInterval, fallbackOptions) - ); + return createSingleWatcherPerName(recursive ? fsWatchesRecursive : fsWatches, useCaseSensitiveFileNames2, fileOrDirectory, callback, cb => fsWatchHandlingExistenceOnHost(fileOrDirectory, entryKind, cb, recursive, fallbackPollingInterval, fallbackOptions)); } function fsWatchHandlingExistenceOnHost(fileOrDirectory, entryKind, callback, recursive, fallbackPollingInterval, fallbackOptions) { let lastDirectoryPartWithDirectorySeparator; @@ -6015,11 +5847,7 @@ ${lanes.join("\n")} return watchPresentFileSystemEntryWithFsWatchFile(); } try { - const presentWatcher = fsWatchWorker( - fileOrDirectory, - recursive, - inodeWatching ? callbackChangingToMissingFileSystemEntry : callback - ); + const presentWatcher = fsWatchWorker(fileOrDirectory, recursive, inodeWatching ? callbackChangingToMissingFileSystemEntry : callback); presentWatcher.on("error", () => { callback("rename", ""); updateWatcher(watchMissingFileSystemEntry); @@ -6039,8 +5867,7 @@ ${lanes.join("\n")} } 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); @@ -6048,47 +5875,29 @@ ${lanes.join("\n")} updateWatcher(watchMissingFileSystemEntry); } } else { - if (originalRelativeName) - callback(event, originalRelativeName); + if (originalRelativeName) callback(event, originalRelativeName); callback(event, relativeName); } } function watchPresentFileSystemEntryWithFsWatchFile() { - return watchFile2( - fileOrDirectory, - createFileWatcherCallback(callback), - fallbackPollingInterval, - fallbackOptions - ); + return watchFile2(fileOrDirectory, createFileWatcherCallback(callback), fallbackPollingInterval, fallbackOptions); } function watchMissingFileSystemEntry() { - return watchFile2( - fileOrDirectory, - (_fileName, eventKind, modifiedTime) => { - if (eventKind === 0 /* Created */) { - modifiedTime || (modifiedTime = getModifiedTime3(fileOrDirectory) || missingFileModifiedTime); - if (modifiedTime !== missingFileModifiedTime) { - callback("rename", "", modifiedTime); - updateWatcher(watchPresentFileSystemEntry); - } + return watchFile2(fileOrDirectory, (_fileName, eventKind, modifiedTime) => { + if (eventKind === 0 /* Created */) { + modifiedTime || (modifiedTime = getModifiedTime3(fileOrDirectory) || missingFileModifiedTime); + if (modifiedTime !== missingFileModifiedTime) { + callback("rename", "", modifiedTime); + updateWatcher(watchPresentFileSystemEntry); } - }, - fallbackPollingInterval, - fallbackOptions - ); + } + }, fallbackPollingInterval, fallbackOptions); } } } function patchWriteFileEnsuringDirectory(sys2) { const originalWriteFile = sys2.writeFile; - sys2.writeFile = (path, data, writeBom) => writeFileEnsuringDirectories( - path, - data, - !!writeBom, - (path2, data2, writeByteOrderMark) => originalWriteFile.call(sys2, path2, data2, writeByteOrderMark), - (path2) => sys2.createDirectory(path2), - (path2) => sys2.directoryExists(path2) - ); + sys2.writeFile = (path, data, writeBom) => writeFileEnsuringDirectories(path, data, !!writeBom, (path2, data2, writeByteOrderMark) => originalWriteFile.call(sys2, path2, data2, writeByteOrderMark), path2 => sys2.createDirectory(path2), path2 => sys2.directoryExists(path2)); } function setSys(s) { sys = s; @@ -6097,26 +5906,31 @@ ${lanes.join("\n")} var init_sys = __esm({ "src/compiler/sys.ts"() { "use strict"; + init_ts2(); - FileWatcherEventKind = /* @__PURE__ */ ((FileWatcherEventKind2) => { + FileWatcherEventKind = /* @__PURE__ */(FileWatcherEventKind2 => { FileWatcherEventKind2[FileWatcherEventKind2["Created"] = 0] = "Created"; FileWatcherEventKind2[FileWatcherEventKind2["Changed"] = 1] = "Changed"; FileWatcherEventKind2[FileWatcherEventKind2["Deleted"] = 2] = "Deleted"; return FileWatcherEventKind2; })(FileWatcherEventKind || {}); - PollingInterval = /* @__PURE__ */ ((PollingInterval3) => { + PollingInterval = /* @__PURE__ */(PollingInterval3 => { PollingInterval3[PollingInterval3["High"] = 2e3] = "High"; PollingInterval3[PollingInterval3["Medium"] = 500] = "Medium"; PollingInterval3[PollingInterval3["Low"] = 250] = "Low"; return PollingInterval3; })(PollingInterval || {}); - missingFileModifiedTime = /* @__PURE__ */ new Date(0); - defaultChunkLevels = { Low: 32, Medium: 64, High: 256 }; + missingFileModifiedTime = /* @__PURE__ */new Date(0); + defaultChunkLevels = { + Low: 32, + Medium: 64, + High: 256 + }; pollingChunkSize = createPollingIntervalBasedLevels(defaultChunkLevels); unchangedPollThresholds = createPollingIntervalBasedLevels(defaultChunkLevels); ignoredPaths = ["/node_modules/.", "/.git", "/.#"]; curSysLog = noop; - FileSystemEntryKind = /* @__PURE__ */ ((FileSystemEntryKind2) => { + FileSystemEntryKind = /* @__PURE__ */(FileSystemEntryKind2 => { FileSystemEntryKind2[FileSystemEntryKind2["File"] = 0] = "File"; FileSystemEntryKind2[FileSystemEntryKind2["Directory"] = 1] = "Directory"; return FileSystemEntryKind2; @@ -6125,18 +5939,18 @@ ${lanes.join("\n")} const byteOrderMarkIndicator = "\uFEFF"; function getNodeSystem() { const nativePattern = /^native |^\([^)]+\)$|^(internal[\\/]|[a-zA-Z0-9_\s]+(\.js)?$)/; - const _fs = require("fs"); - const _path = require("path"); - const _os = require("os"); + const _fs = require("fs"); + const _path = require("path"); + const _os = require("os"); let _crypto; try { - _crypto = require("crypto"); + _crypto = require("crypto"); } catch { _crypto = void 0; } let activeSession; let profilePath = "./profile.cpuprofile"; - const Buffer2 = require("buffer").Buffer; + const Buffer2 = require("buffer").Buffer; const isLinuxOrMacOs = process.platform === "linux" || process.platform === "darwin"; const platform = _os.platform(); const useCaseSensitiveFileNames2 = isFileSystemCaseSensitive(); @@ -6144,7 +5958,10 @@ ${lanes.join("\n")} const executingFilePath = __filename.endsWith("sys.js") ? _path.join(_path.dirname(__dirname), "__fake__.js") : __filename; const fsSupportsRecursiveFsWatch = process.platform === "win32" || process.platform === "darwin"; const getCurrentDirectory = memoize(() => process.cwd()); - const { watchFile: watchFile2, watchDirectory } = createSystemWatchFunctions({ + const { + watchFile: watchFile2, + watchDirectory + } = createSystemWatchFunctions({ pollingWatchFileWorker: fsWatchFileWorker, getModifiedTime: getModifiedTime3, setTimeout, @@ -6156,7 +5973,7 @@ ${lanes.join("\n")} // Node 4.0 `fs.watch` function supports the "recursive" option on both OSX and Windows // (ref: https://github.com/nodejs/node/pull/2649 and https://github.com/Microsoft/TypeScript/issues/4643) fsSupportsRecursiveFsWatch, - getAccessibleSortedChildDirectories: (path) => getAccessibleFileSystemEntries(path).directories, + getAccessibleSortedChildDirectories: path => getAccessibleFileSystemEntries(path).directories, realpath, tscWatchFile: process.env.TSC_WATCHFILE, useNonPollingWatchers: !!process.env.TSC_NONPOLLING_WATCHER, @@ -6181,7 +5998,7 @@ ${lanes.join("\n")} writeFile: writeFile2, watchFile: watchFile2, watchDirectory, - resolvePath: (path) => _path.resolve(path), + resolvePath: path => _path.resolve(path), fileExists, directoryExists, createDirectory(directoryName) { @@ -6221,8 +6038,7 @@ ${lanes.join("\n")} if (stat == null ? void 0 : stat.isFile()) { return stat.size; } - } catch { - } + } catch {} return 0; }, exit(exitCode) { @@ -6232,12 +6048,11 @@ ${lanes.join("\n")} disableCPUProfiler, cpuProfilingEnabled: () => !!activeSession || contains(process.execArgv, "--cpu-prof") || contains(process.execArgv, "--prof"), realpath, - debugMode: !!process.env.NODE_INSPECTOR_IPC || !!process.env.VSCODE_INSPECTOR_OPTIONS || some(process.execArgv, (arg) => /^--(inspect|debug)(-brk)?(=\d+)?$/i.test(arg)) || !!process.recordreplay, + debugMode: !!process.env.NODE_INSPECTOR_IPC || !!process.env.VSCODE_INSPECTOR_OPTIONS || some(process.execArgv, arg => /^--(inspect|debug)(-brk)?(=\d+)?$/i.test(arg)) || !!process.recordreplay, tryEnableSourceMapsForHost() { try { - require("source-map-support").install(); - } catch { - } + require("source-map-support").install(); + } catch {} }, setTimeout, clearTimeout, @@ -6252,27 +6067,37 @@ ${lanes.join("\n")} } }, bufferFrom, - base64decode: (input) => bufferFrom(input, "base64").toString("utf8"), - base64encode: (input) => bufferFrom(input).toString("base64"), + base64decode: input => bufferFrom(input, "base64").toString("utf8"), + base64encode: input => bufferFrom(input).toString("base64"), require: (baseDir, moduleName) => { try { const modulePath = resolveJSModule(moduleName, baseDir, nodeSystem); - return { module: require(modulePath), modulePath, error: void 0 }; + return { + module: require(modulePath), + modulePath, + error: void 0 + }; } catch (error2) { - return { module: void 0, modulePath: void 0, error: error2 }; + return { + module: void 0, + modulePath: void 0, + error: error2 + }; } } }; return nodeSystem; function statSync(path) { - return _fs.statSync(path, { throwIfNoEntry: false }); + return _fs.statSync(path, { + throwIfNoEntry: false + }); } function enableCPUProfiler(path, cb) { if (activeSession) { cb(); return false; } - const inspector = require("inspector"); + const inspector = require("inspector"); if (!inspector || !inspector.Session) { cb(); return false; @@ -6290,21 +6115,15 @@ ${lanes.join("\n")} } function cleanupPaths(profile) { let externalFileCounter = 0; - const remappedPaths = /* @__PURE__ */ new Map(); + const remappedPaths = /* @__PURE__ */new Map(); const normalizedDir = normalizeSlashes(_path.dirname(executingFilePath)); const fileUrlRoot = `file://${getRootLength(normalizedDir) === 1 ? "" : "/"}${normalizedDir}`; for (const node of profile.nodes) { if (node.callFrame.url) { const url = normalizeSlashes(node.callFrame.url); if (containsPath(fileUrlRoot, url, useCaseSensitiveFileNames2)) { - node.callFrame.url = getRelativePathToDirectoryOrUrl( - fileUrlRoot, - url, - fileUrlRoot, - createGetCanonicalFileName(useCaseSensitiveFileNames2), - /*isAbsolutePathAnUrl*/ - true - ); + node.callFrame.url = getRelativePathToDirectoryOrUrl(fileUrlRoot, url, fileUrlRoot, createGetCanonicalFileName(useCaseSensitiveFileNames2), /*isAbsolutePathAnUrl*/ + true); } else if (!nativePattern.test(url)) { node.callFrame.url = (remappedPaths.has(url) ? remappedPaths : remappedPaths.set(url, `external${externalFileCounter}.js`)).get(url); externalFileCounter++; @@ -6316,19 +6135,21 @@ ${lanes.join("\n")} function disableCPUProfiler(cb) { if (activeSession && activeSession !== "stopping") { const s = activeSession; - activeSession.post("Profiler.stop", (err, { profile }) => { + activeSession.post("Profiler.stop", (err, { + profile + }) => { var _a; if (!err) { try { if ((_a = statSync(profilePath)) == null ? void 0 : _a.isDirectory()) { - profilePath = _path.join(profilePath, `${(/* @__PURE__ */ new Date()).toISOString().replace(/:/g, "-")}+P${process.pid}.cpuprofile`); + profilePath = _path.join(profilePath, `${/* @__PURE__ */new Date().toISOString().replace(/:/g, "-")}+P${process.pid}.cpuprofile`); } - } catch { - } + } catch {} try { - _fs.mkdirSync(_path.dirname(profilePath), { recursive: true }); - } catch { - } + _fs.mkdirSync(_path.dirname(profilePath), { + recursive: true + }); + } catch {} _fs.writeFileSync(profilePath, JSON.stringify(cleanupPaths(profile))); } activeSession = void 0; @@ -6352,13 +6173,16 @@ ${lanes.join("\n")} return !fileExists(swapCase(__filename)); } function swapCase(s) { - return s.replace(/\w/g, (ch) => { + return s.replace(/\w/g, ch => { const up = ch.toUpperCase(); return ch === up ? ch.toLowerCase() : up; }); } function fsWatchFileWorker(fileName, callback, pollingInterval) { - _fs.watchFile(fileName, { persistent: true, interval: pollingInterval }, fileChanged); + _fs.watchFile(fileName, { + persistent: true, + interval: pollingInterval + }, fileChanged); let eventKind; return { close: () => _fs.unwatchFile(fileName, fileChanged) @@ -6377,15 +6201,17 @@ ${lanes.join("\n")} } else { eventKind = 1 /* Changed */; } + callback(fileName, eventKind, curr.mtime); } } function fsWatchWorker(fileOrDirectory, recursive, callback) { - return _fs.watch( - fileOrDirectory, - fsSupportsRecursiveFsWatch ? { persistent: true, recursive: !!recursive } : { persistent: true }, - callback - ); + return _fs.watch(fileOrDirectory, fsSupportsRecursiveFsWatch ? { + persistent: true, + recursive: !!recursive + } : { + persistent: true + }, callback); } function readFileWorker(fileName, _encoding) { let buffer; @@ -6428,13 +6254,8 @@ ${lanes.join("\n")} let fd; try { fd = _fs.openSync(fileName, "w"); - _fs.writeSync( - fd, - data, - /*position*/ - void 0, - "utf8" - ); + _fs.writeSync(fd, data, /*position*/ + void 0, "utf8"); } finally { if (fd !== void 0) { _fs.closeSync(fd); @@ -6445,7 +6266,9 @@ ${lanes.join("\n")} var _a; (_a = perfLogger) == null ? void 0 : _a.logEvent("ReadDir: " + (path || ".")); try { - const entries = _fs.readdirSync(path || ".", { withFileTypes: true }); + const entries = _fs.readdirSync(path || ".", { + withFileTypes: true + }); const files = []; const directories = []; for (const dirent of entries) { @@ -6475,7 +6298,10 @@ ${lanes.join("\n")} } files.sort(); directories.sort(); - return { files, directories }; + return { + files, + directories + }; } catch (e) { return emptyFileSystemEntries; } @@ -6508,9 +6334,11 @@ ${lanes.join("\n")} function fileExists(path) { return fileSystemEntryExists(path, 0 /* File */); } + function directoryExists(path) { return fileSystemEntryExists(path, 1 /* Directory */); } + function getDirectories(path) { return getAccessibleFileSystemEntries(path).directories.slice(); } @@ -6567,10 +6395,9 @@ ${lanes.join("\n")} })(); if (sys && sys.getEnvironmentVariable) { setCustomPollingValues(sys); - Debug.setAssertionLevel( - /^development$/i.test(sys.getEnvironmentVariable("NODE_ENV")) ? 1 /* Normal */ : 0 /* None */ - ); + Debug.setAssertionLevel(/^development$/i.test(sys.getEnvironmentVariable("NODE_ENV")) ? 1 /* Normal */ : 0 /* None */); } + if (sys && sys.debugMode) { Debug.isDebugging = true; } @@ -6581,6 +6408,7 @@ ${lanes.join("\n")} function isAnyDirectorySeparator(charCode) { return charCode === 47 /* slash */ || charCode === 92 /* backslash */; } + function isUrl(path) { return getEncodedRootLength(path) < 0; } @@ -6620,35 +6448,29 @@ ${lanes.join("\n")} function isVolumeCharacter(charCode) { return charCode >= 97 /* a */ && charCode <= 122 /* z */ || charCode >= 65 /* A */ && charCode <= 90 /* Z */; } + 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) { @@ -6681,24 +6503,21 @@ ${lanes.join("\n")} 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)) { @@ -6712,8 +6531,7 @@ ${lanes.join("\n")} } for (const extension of extensions) { const result = tryGetExtensionFromPath(path, extension, stringEqualityComparer); - if (result) - return result; + if (result) return result; } return ""; } @@ -6731,8 +6549,7 @@ ${lanes.join("\n")} 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 = "") { @@ -6740,8 +6557,7 @@ ${lanes.join("\n")} 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); } @@ -6749,34 +6565,28 @@ ${lanes.join("\n")} 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; @@ -6811,8 +6621,7 @@ ${lanes.join("\n")} 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) { @@ -6842,12 +6651,9 @@ ${lanes.join("\n")} return pathext ? path.slice(0, path.length - pathext.length) + (startsWith(ext, ".") ? ext : "." + ext) : path; } 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); @@ -6892,10 +6698,8 @@ ${lanes.join("\n")} } 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) { @@ -6923,8 +6727,7 @@ ${lanes.join("\n")} 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; @@ -6944,25 +6747,14 @@ ${lanes.join("\n")} return getPathFromPathComponents(pathComponents2); } function convertToRelativePath(absoluteOrRelativePath, basePath, getCanonicalFileName) { - return !isRootedDiskPath(absoluteOrRelativePath) ? absoluteOrRelativePath : getRelativePathToDirectoryOrUrl( - basePath, - absoluteOrRelativePath, - basePath, - getCanonicalFileName, - /*isAbsolutePathAnUrl*/ - false - ); + return !isRootedDiskPath(absoluteOrRelativePath) ? absoluteOrRelativePath : getRelativePathToDirectoryOrUrl(basePath, absoluteOrRelativePath, basePath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ + false); } function getRelativePathFromFile(from, to, getCanonicalFileName) { return ensurePathIsNonModuleName(getRelativePathFromDirectory(getDirectoryPath(from), to, getCanonicalFileName)); } function getRelativePathToDirectoryOrUrl(directoryPathOrUrl, relativeOrAbsolutePath, currentDirectory, getCanonicalFileName, isAbsolutePathAnUrl) { - const pathComponents2 = getPathComponentsRelativeTo( - resolvePath(currentDirectory, directoryPathOrUrl), - resolvePath(currentDirectory, relativeOrAbsolutePath), - equateStringsCaseSensitive, - getCanonicalFileName - ); + const pathComponents2 = getPathComponentsRelativeTo(resolvePath(currentDirectory, directoryPathOrUrl), resolvePath(currentDirectory, relativeOrAbsolutePath), equateStringsCaseSensitive, getCanonicalFileName); const firstComponent = pathComponents2[0]; if (isAbsolutePathAnUrl && isRootedDiskPath(firstComponent)) { const prefix = firstComponent.charAt(0) === directorySeparator ? "file://" : "file:///"; @@ -6990,6 +6782,7 @@ ${lanes.join("\n")} var init_path = __esm({ "src/compiler/path.ts"() { "use strict"; + init_ts2(); directorySeparator = "/"; altDirectorySeparator = "\\"; @@ -7001,12 +6794,21 @@ ${lanes.join("\n")} // src/compiler/diagnosticInformationMap.generated.ts function diag(code, category, key, message, reportsUnnecessary, elidedInCompatabilityPyramid, reportsDeprecated) { - return { code, category, key, message, reportsUnnecessary, elidedInCompatabilityPyramid, reportsDeprecated }; + return { + code, + category, + key, + message, + reportsUnnecessary, + elidedInCompatabilityPyramid, + reportsDeprecated + }; } var Diagnostics; var init_diagnosticInformationMap_generated = __esm({ "src/compiler/diagnosticInformationMap.generated.ts"() { "use strict"; + init_types(); Diagnostics = { Unterminated_string_literal: diag(1002, 1 /* Error */, "Unterminated_string_literal_1002", "Unterminated string literal."), @@ -7419,46 +7221,18 @@ ${lanes.join("\n")} Identifier_string_literal_or_number_literal_expected: diag(1496, 1 /* Error */, "Identifier_string_literal_or_number_literal_expected_1496", "Identifier, string literal, or number literal expected."), The_types_of_0_are_incompatible_between_these_types: diag(2200, 1 /* Error */, "The_types_of_0_are_incompatible_between_these_types_2200", "The types of '{0}' are incompatible between these types."), The_types_returned_by_0_are_incompatible_between_these_types: diag(2201, 1 /* Error */, "The_types_returned_by_0_are_incompatible_between_these_types_2201", "The types returned by '{0}' are incompatible between these types."), - Call_signature_return_types_0_and_1_are_incompatible: diag( - 2202, - 1 /* Error */, - "Call_signature_return_types_0_and_1_are_incompatible_2202", - "Call signature return types '{0}' and '{1}' are incompatible.", - /*reportsUnnecessary*/ - void 0, - /*elidedInCompatabilityPyramid*/ - true - ), - Construct_signature_return_types_0_and_1_are_incompatible: diag( - 2203, - 1 /* Error */, - "Construct_signature_return_types_0_and_1_are_incompatible_2203", - "Construct signature return types '{0}' and '{1}' are incompatible.", - /*reportsUnnecessary*/ - void 0, - /*elidedInCompatabilityPyramid*/ - true - ), - Call_signatures_with_no_arguments_have_incompatible_return_types_0_and_1: diag( - 2204, - 1 /* Error */, - "Call_signatures_with_no_arguments_have_incompatible_return_types_0_and_1_2204", - "Call signatures with no arguments have incompatible return types '{0}' and '{1}'.", - /*reportsUnnecessary*/ - void 0, - /*elidedInCompatabilityPyramid*/ - true - ), - Construct_signatures_with_no_arguments_have_incompatible_return_types_0_and_1: diag( - 2205, - 1 /* Error */, - "Construct_signatures_with_no_arguments_have_incompatible_return_types_0_and_1_2205", - "Construct signatures with no arguments have incompatible return types '{0}' and '{1}'.", - /*reportsUnnecessary*/ - void 0, - /*elidedInCompatabilityPyramid*/ - true - ), + Call_signature_return_types_0_and_1_are_incompatible: diag(2202, 1 /* Error */, "Call_signature_return_types_0_and_1_are_incompatible_2202", "Call signature return types '{0}' and '{1}' are incompatible.", /*reportsUnnecessary*/ + void 0, /*elidedInCompatabilityPyramid*/ + true), + Construct_signature_return_types_0_and_1_are_incompatible: diag(2203, 1 /* Error */, "Construct_signature_return_types_0_and_1_are_incompatible_2203", "Construct signature return types '{0}' and '{1}' are incompatible.", /*reportsUnnecessary*/ + void 0, /*elidedInCompatabilityPyramid*/ + true), + Call_signatures_with_no_arguments_have_incompatible_return_types_0_and_1: diag(2204, 1 /* Error */, "Call_signatures_with_no_arguments_have_incompatible_return_types_0_and_1_2204", "Call signatures with no arguments have incompatible return types '{0}' and '{1}'.", /*reportsUnnecessary*/ + void 0, /*elidedInCompatabilityPyramid*/ + true), + Construct_signatures_with_no_arguments_have_incompatible_return_types_0_and_1: diag(2205, 1 /* Error */, "Construct_signatures_with_no_arguments_have_incompatible_return_types_0_and_1_2205", "Construct signatures with no arguments have incompatible return types '{0}' and '{1}'.", /*reportsUnnecessary*/ + void 0, /*elidedInCompatabilityPyramid*/ + true), The_type_modifier_cannot_be_used_on_a_named_import_when_import_type_is_used_on_its_import_statement: diag(2206, 1 /* Error */, "The_type_modifier_cannot_be_used_on_a_named_import_when_import_type_is_used_on_its_import_statement_2206", "The 'type' modifier cannot be used on a named import when 'import type' is used on its import statement."), The_type_modifier_cannot_be_used_on_a_named_export_when_export_type_is_used_on_its_export_statement: diag(2207, 1 /* Error */, "The_type_modifier_cannot_be_used_on_a_named_export_when_export_type_is_used_on_its_export_statement_2207", "The 'type' modifier cannot be used on a named export when 'export type' is used on its export statement."), This_type_parameter_might_need_an_extends_0_constraint: diag(2208, 1 /* Error */, "This_type_parameter_might_need_an_extends_0_constraint_2208", "This type parameter might need an `extends {0}` constraint."), @@ -7812,14 +7586,8 @@ ${lanes.join("\n")} _0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible: diag(2692, 1 /* Error */, "_0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible_2692", "'{0}' is a primitive, but '{1}' is a wrapper object. Prefer using '{0}' when possible."), _0_only_refers_to_a_type_but_is_being_used_as_a_value_here: diag(2693, 1 /* Error */, "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_2693", "'{0}' only refers to a type, but is being used as a value here."), Namespace_0_has_no_exported_member_1: diag(2694, 1 /* Error */, "Namespace_0_has_no_exported_member_1_2694", "Namespace '{0}' has no exported member '{1}'."), - Left_side_of_comma_operator_is_unused_and_has_no_side_effects: diag( - 2695, - 1 /* Error */, - "Left_side_of_comma_operator_is_unused_and_has_no_side_effects_2695", - "Left side of comma operator is unused and has no side effects.", - /*reportsUnnecessary*/ - true - ), + Left_side_of_comma_operator_is_unused_and_has_no_side_effects: diag(2695, 1 /* Error */, "Left_side_of_comma_operator_is_unused_and_has_no_side_effects_2695", "Left side of comma operator is unused and has no side effects.", /*reportsUnnecessary*/ + true), The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead: diag(2696, 1 /* Error */, "The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead_2696", "The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead?"), An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option: diag(2697, 1 /* Error */, "An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_in_2697", "An async function or method must return a 'Promise'. Make sure you have a declaration for 'Promise' or include 'ES2015' in your '--lib' option."), Spread_types_may_only_be_created_from_object_types: diag(2698, 1 /* Error */, "Spread_types_may_only_be_created_from_object_types_2698", "Spread types may only be created from object types."), @@ -8267,26 +8035,14 @@ ${lanes.join("\n")} Resolving_real_path_for_0_result_1: diag(6130, 3 /* Message */, "Resolving_real_path_for_0_result_1_6130", "Resolving real path for '{0}', result '{1}'."), Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system: diag(6131, 1 /* Error */, "Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system_6131", "Cannot compile modules using option '{0}' unless the '--module' flag is 'amd' or 'system'."), File_name_0_has_a_1_extension_stripping_it: diag(6132, 3 /* Message */, "File_name_0_has_a_1_extension_stripping_it_6132", "File name '{0}' has a '{1}' extension - stripping it."), - _0_is_declared_but_its_value_is_never_read: diag( - 6133, - 1 /* Error */, - "_0_is_declared_but_its_value_is_never_read_6133", - "'{0}' is declared but its value is never read.", - /*reportsUnnecessary*/ - true - ), + _0_is_declared_but_its_value_is_never_read: diag(6133, 1 /* Error */, "_0_is_declared_but_its_value_is_never_read_6133", "'{0}' is declared but its value is never read.", /*reportsUnnecessary*/ + true), Report_errors_on_unused_locals: diag(6134, 3 /* Message */, "Report_errors_on_unused_locals_6134", "Report errors on unused locals."), Report_errors_on_unused_parameters: diag(6135, 3 /* Message */, "Report_errors_on_unused_parameters_6135", "Report errors on unused parameters."), The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files: diag(6136, 3 /* Message */, "The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files_6136", "The maximum dependency depth to search under node_modules and load JavaScript files."), Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1: diag(6137, 1 /* Error */, "Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1_6137", "Cannot import type declaration files. Consider importing '{0}' instead of '{1}'."), - Property_0_is_declared_but_its_value_is_never_read: diag( - 6138, - 1 /* Error */, - "Property_0_is_declared_but_its_value_is_never_read_6138", - "Property '{0}' is declared but its value is never read.", - /*reportsUnnecessary*/ - true - ), + Property_0_is_declared_but_its_value_is_never_read: diag(6138, 1 /* Error */, "Property_0_is_declared_but_its_value_is_never_read_6138", "Property '{0}' is declared but its value is never read.", /*reportsUnnecessary*/ + true), Import_emit_helpers_from_tslib: diag(6139, 3 /* Message */, "Import_emit_helpers_from_tslib_6139", "Import emit helpers from 'tslib'."), Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2: diag(6140, 1 /* Error */, "Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using__6140", "Auto discovery for typings is enabled in project '{0}'. Running extra resolution pass for module '{1}' using cache location '{2}'."), Parse_in_strict_mode_and_emit_use_strict_for_each_source_file: diag(6141, 3 /* Message */, "Parse_in_strict_mode_and_emit_use_strict_for_each_source_file_6141", 'Parse in strict mode and emit "use strict" for each source file.'), @@ -8329,42 +8085,18 @@ ${lanes.join("\n")} Numeric_separators_are_not_allowed_here: diag(6188, 1 /* Error */, "Numeric_separators_are_not_allowed_here_6188", "Numeric separators are not allowed here."), Multiple_consecutive_numeric_separators_are_not_permitted: diag(6189, 1 /* Error */, "Multiple_consecutive_numeric_separators_are_not_permitted_6189", "Multiple consecutive numeric separators are not permitted."), Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen: diag(6191, 3 /* Message */, "Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen_6191", "Whether to keep outdated console output in watch mode instead of clearing the screen."), - All_imports_in_import_declaration_are_unused: diag( - 6192, - 1 /* Error */, - "All_imports_in_import_declaration_are_unused_6192", - "All imports in import declaration are unused.", - /*reportsUnnecessary*/ - true - ), + All_imports_in_import_declaration_are_unused: diag(6192, 1 /* Error */, "All_imports_in_import_declaration_are_unused_6192", "All imports in import declaration are unused.", /*reportsUnnecessary*/ + true), Found_1_error_Watching_for_file_changes: diag(6193, 3 /* Message */, "Found_1_error_Watching_for_file_changes_6193", "Found 1 error. Watching for file changes."), Found_0_errors_Watching_for_file_changes: diag(6194, 3 /* Message */, "Found_0_errors_Watching_for_file_changes_6194", "Found {0} errors. Watching for file changes."), Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols: diag(6195, 3 /* Message */, "Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols_6195", "Resolve 'keyof' to string valued property names only (no numbers or symbols)."), - _0_is_declared_but_never_used: diag( - 6196, - 1 /* Error */, - "_0_is_declared_but_never_used_6196", - "'{0}' is declared but never used.", - /*reportsUnnecessary*/ - true - ), + _0_is_declared_but_never_used: diag(6196, 1 /* Error */, "_0_is_declared_but_never_used_6196", "'{0}' is declared but never used.", /*reportsUnnecessary*/ + true), Include_modules_imported_with_json_extension: diag(6197, 3 /* Message */, "Include_modules_imported_with_json_extension_6197", "Include modules imported with '.json' extension"), - All_destructured_elements_are_unused: diag( - 6198, - 1 /* Error */, - "All_destructured_elements_are_unused_6198", - "All destructured elements are unused.", - /*reportsUnnecessary*/ - true - ), - All_variables_are_unused: diag( - 6199, - 1 /* Error */, - "All_variables_are_unused_6199", - "All variables are unused.", - /*reportsUnnecessary*/ - true - ), + All_destructured_elements_are_unused: diag(6198, 1 /* Error */, "All_destructured_elements_are_unused_6198", "All destructured elements are unused.", /*reportsUnnecessary*/ + true), + All_variables_are_unused: diag(6199, 1 /* Error */, "All_variables_are_unused_6199", "All variables are unused.", /*reportsUnnecessary*/ + true), Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0: diag(6200, 1 /* Error */, "Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0_6200", "Definitions of the following identifiers conflict with those in another file: {0}"), Conflicts_are_in_this_file: diag(6201, 3 /* Message */, "Conflicts_are_in_this_file_6201", "Conflicts are in this file."), Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0: diag(6202, 1 /* Error */, "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202", "Project references may not form a circular graph. Cycle detected: {0}"), @@ -8479,31 +8211,15 @@ ${lanes.join("\n")} Skipping_build_of_project_0_because_its_dependency_1_was_not_built: diag(6382, 3 /* Message */, "Skipping_build_of_project_0_because_its_dependency_1_was_not_built_6382", "Skipping build of project '{0}' because its dependency '{1}' was not built"), Project_0_can_t_be_built_because_its_dependency_1_was_not_built: diag(6383, 3 /* Message */, "Project_0_can_t_be_built_because_its_dependency_1_was_not_built_6383", "Project '{0}' can't be built because its dependency '{1}' was not built"), Have_recompiles_in_incremental_and_watch_assume_that_changes_within_a_file_will_only_affect_files_directly_depending_on_it: diag(6384, 3 /* Message */, "Have_recompiles_in_incremental_and_watch_assume_that_changes_within_a_file_will_only_affect_files_di_6384", "Have recompiles in '--incremental' and '--watch' assume that changes within a file will only affect files directly depending on it."), - _0_is_deprecated: diag( - 6385, - 2 /* Suggestion */, - "_0_is_deprecated_6385", - "'{0}' is deprecated.", - /*reportsUnnecessary*/ - void 0, - /*elidedInCompatabilityPyramid*/ - void 0, - /*reportsDeprecated*/ - true - ), + _0_is_deprecated: diag(6385, 2 /* Suggestion */, "_0_is_deprecated_6385", "'{0}' is deprecated.", /*reportsUnnecessary*/ + void 0, /*elidedInCompatabilityPyramid*/ + void 0, /*reportsDeprecated*/ + true), Performance_timings_for_diagnostics_or_extendedDiagnostics_are_not_available_in_this_session_A_native_implementation_of_the_Web_Performance_API_could_not_be_found: diag(6386, 3 /* Message */, "Performance_timings_for_diagnostics_or_extendedDiagnostics_are_not_available_in_this_session_A_nativ_6386", "Performance timings for '--diagnostics' or '--extendedDiagnostics' are not available in this session. A native implementation of the Web Performance API could not be found."), - The_signature_0_of_1_is_deprecated: diag( - 6387, - 2 /* Suggestion */, - "The_signature_0_of_1_is_deprecated_6387", - "The signature '{0}' of '{1}' is deprecated.", - /*reportsUnnecessary*/ - void 0, - /*elidedInCompatabilityPyramid*/ - void 0, - /*reportsDeprecated*/ - true - ), + The_signature_0_of_1_is_deprecated: diag(6387, 2 /* Suggestion */, "The_signature_0_of_1_is_deprecated_6387", "The signature '{0}' of '{1}' is deprecated.", /*reportsUnnecessary*/ + void 0, /*elidedInCompatabilityPyramid*/ + void 0, /*reportsDeprecated*/ + true), Project_0_is_being_forcibly_rebuilt: diag(6388, 3 /* Message */, "Project_0_is_being_forcibly_rebuilt_6388", "Project '{0}' is being forcibly rebuilt"), Reusing_resolution_of_module_0_from_1_of_old_program_it_was_not_resolved: diag(6389, 3 /* Message */, "Reusing_resolution_of_module_0_from_1_of_old_program_it_was_not_resolved_6389", "Reusing resolution of module '{0}' from '{1}' of old program, it was not resolved."), Reusing_resolution_of_type_reference_directive_0_from_1_of_old_program_it_was_successfully_resolved_to_2: diag(6390, 3 /* Message */, "Reusing_resolution_of_type_reference_directive_0_from_1_of_old_program_it_was_successfully_resolved__6390", "Reusing resolution of type reference directive '{0}' from '{1}' of old program, it was successfully resolved to '{2}'."), @@ -8710,22 +8426,10 @@ ${lanes.join("\n")} Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions: diag(7024, 1 /* Error */, "Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_ref_7024", "Function implicitly has return type 'any' because it does not have a return type annotation and is referenced directly or indirectly in one of its return expressions."), Generator_implicitly_has_yield_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_type_annotation: diag(7025, 1 /* Error */, "Generator_implicitly_has_yield_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_retu_7025", "Generator implicitly has yield type '{0}' because it does not yield any values. Consider supplying a return type annotation."), JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists: diag(7026, 1 /* Error */, "JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists_7026", "JSX element implicitly has type 'any' because no interface 'JSX.{0}' exists."), - Unreachable_code_detected: diag( - 7027, - 1 /* Error */, - "Unreachable_code_detected_7027", - "Unreachable code detected.", - /*reportsUnnecessary*/ - true - ), - Unused_label: diag( - 7028, - 1 /* Error */, - "Unused_label_7028", - "Unused label.", - /*reportsUnnecessary*/ - true - ), + Unreachable_code_detected: diag(7027, 1 /* Error */, "Unreachable_code_detected_7027", "Unreachable code detected.", /*reportsUnnecessary*/ + true), + Unused_label: diag(7028, 1 /* Error */, "Unused_label_7028", "Unused label.", /*reportsUnnecessary*/ + true), Fallthrough_case_in_switch: diag(7029, 1 /* Error */, "Fallthrough_case_in_switch_7029", "Fallthrough case in switch."), Not_all_code_paths_return_a_value: diag(7030, 1 /* Error */, "Not_all_code_paths_return_a_value_7030", "Not all code paths return a value."), Binding_element_0_implicitly_has_an_1_type: diag(7031, 1 /* Error */, "Binding_element_0_implicitly_has_an_1_type_7031", "Binding element '{0}' implicitly has an '{1}' type."), @@ -9108,6 +8812,7 @@ ${lanes.join("\n")} function tokenIsIdentifierOrKeyword(token) { return token >= 80 /* Identifier */; } + function tokenIsIdentifierOrKeywordOrGreaterThan(token) { return token === 32 /* GreaterThanToken */ || tokenIsIdentifierOrKeyword(token); } @@ -9219,8 +8924,7 @@ ${lanes.join("\n")} 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; @@ -9238,21 +8942,26 @@ ${lanes.join("\n")} function isWhiteSpaceSingleLine(ch) { return ch === 32 /* space */ || ch === 9 /* tab */ || ch === 11 /* verticalTab */ || ch === 12 /* formFeed */ || ch === 160 /* nonBreakingSpace */ || ch === 133 /* nextLine */ || ch === 5760 /* ogham */ || ch >= 8192 /* enQuad */ && ch <= 8203 /* zeroWidthSpace */ || ch === 8239 /* narrowNoBreakSpace */ || ch === 8287 /* mathematicalSpace */ || ch === 12288 /* ideographicSpace */ || ch === 65279 /* byteOrderMark */; } + function isLineBreak(ch) { return ch === 10 /* lineFeed */ || ch === 13 /* carriageReturn */ || ch === 8232 /* lineSeparator */ || ch === 8233 /* paragraphSeparator */; } + function isDigit(ch) { return ch >= 48 /* _0 */ && ch <= 57 /* _9 */; } + function isHexDigit(ch) { return isDigit(ch) || ch >= 65 /* A */ && ch <= 70 /* F */ || ch >= 97 /* a */ && ch <= 102 /* f */; } + function isCodePoint(code) { return code <= 1114111; } function isOctalDigit(ch) { return ch >= 48 /* _0 */ && ch <= 55 /* _7 */; } + function couldStartTrivia(text, pos) { const ch = text.charCodeAt(pos); switch (ch) { @@ -9274,6 +8983,7 @@ ${lanes.join("\n")} return ch > 127 /* maxAsciiCharacter */; } } + function skipTrivia(text, pos, stopAfterLineBreak, stopAtComments, inJSDoc) { if (positionIsSynthesized(pos)) { return pos; @@ -9374,6 +9084,7 @@ ${lanes.join("\n")} return ch === 61 /* equals */ || text.charCodeAt(pos + mergeConflictMarkerLength) === 32 /* space */; } } + return false; } function scanConflictMarkerTrivia(text, pos, error2) { @@ -9422,161 +9133,123 @@ ${lanes.join("\n")} pos = shebang.length; } } - scan: - while (pos >= 0 && pos < text.length) { - const ch = text.charCodeAt(pos); - switch (ch) { - case 13 /* carriageReturn */: - if (text.charCodeAt(pos + 1) === 10 /* lineFeed */) { - pos++; - } - case 10 /* lineFeed */: + scan: while (pos >= 0 && pos < text.length) { + const ch = text.charCodeAt(pos); + switch (ch) { + case 13 /* carriageReturn */: + if (text.charCodeAt(pos + 1) === 10 /* lineFeed */) { pos++; - if (trailing) { - break scan; + } + case 10 /* lineFeed */: + pos++; + if (trailing) { + break scan; + } + collecting = true; + if (hasPendingCommentRange) { + pendingHasTrailingNewLine = true; + } + continue; + case 9 /* tab */: + case 11 /* verticalTab */: + case 12 /* formFeed */: + case 32 /* space */: + pos++; + continue; + case 47 /* slash */: + const nextChar = text.charCodeAt(pos + 1); + let hasTrailingNewLine = false; + if (nextChar === 47 /* slash */ || nextChar === 42 /* asterisk */) { + const kind = nextChar === 47 /* slash */ ? 2 /* SingleLineCommentTrivia */ : 3 /* MultiLineCommentTrivia */; + const startPos = pos; + pos += 2; + if (nextChar === 47 /* slash */) { + while (pos < text.length) { + if (isLineBreak(text.charCodeAt(pos))) { + hasTrailingNewLine = true; + break; + } + pos++; + } + } else { + while (pos < text.length) { + if (text.charCodeAt(pos) === 42 /* asterisk */ && text.charCodeAt(pos + 1) === 47 /* slash */) { + pos += 2; + break; + } + pos++; + } } - collecting = true; - if (hasPendingCommentRange) { + if (collecting) { + if (hasPendingCommentRange) { + accumulator = cb(pendingPos, pendingEnd, pendingKind, pendingHasTrailingNewLine, state, accumulator); + if (!reduce && accumulator) { + return accumulator; + } + } + pendingPos = startPos; + pendingEnd = pos; + pendingKind = kind; + pendingHasTrailingNewLine = hasTrailingNewLine; + hasPendingCommentRange = true; + } + continue; + } + break scan; + default: + if (ch > 127 /* maxAsciiCharacter */ && isWhiteSpaceLike(ch)) { + if (hasPendingCommentRange && isLineBreak(ch)) { pendingHasTrailingNewLine = true; } - continue; - case 9 /* tab */: - case 11 /* verticalTab */: - case 12 /* formFeed */: - case 32 /* space */: pos++; continue; - case 47 /* slash */: - const nextChar = text.charCodeAt(pos + 1); - let hasTrailingNewLine = false; - if (nextChar === 47 /* slash */ || nextChar === 42 /* asterisk */) { - const kind = nextChar === 47 /* slash */ ? 2 /* SingleLineCommentTrivia */ : 3 /* MultiLineCommentTrivia */; - const startPos = pos; - pos += 2; - if (nextChar === 47 /* slash */) { - while (pos < text.length) { - if (isLineBreak(text.charCodeAt(pos))) { - hasTrailingNewLine = true; - break; - } - pos++; - } - } else { - while (pos < text.length) { - if (text.charCodeAt(pos) === 42 /* asterisk */ && text.charCodeAt(pos + 1) === 47 /* slash */) { - pos += 2; - break; - } - pos++; - } - } - if (collecting) { - if (hasPendingCommentRange) { - accumulator = cb(pendingPos, pendingEnd, pendingKind, pendingHasTrailingNewLine, state, accumulator); - if (!reduce && accumulator) { - return accumulator; - } - } - pendingPos = startPos; - pendingEnd = pos; - pendingKind = kind; - pendingHasTrailingNewLine = hasTrailingNewLine; - hasPendingCommentRange = true; - } - continue; - } - break scan; - default: - if (ch > 127 /* maxAsciiCharacter */ && isWhiteSpaceLike(ch)) { - if (hasPendingCommentRange && isLineBreak(ch)) { - pendingHasTrailingNewLine = true; - } - pos++; - continue; - } - break scan; - } + } + break scan; } + } if (hasPendingCommentRange) { accumulator = cb(pendingPos, pendingEnd, pendingKind, pendingHasTrailingNewLine, state, accumulator); } return accumulator; } function forEachLeadingCommentRange(text, pos, cb, state) { - return iterateCommentRanges( - /*reduce*/ - false, - text, - pos, - /*trailing*/ - false, - cb, - state - ); + return iterateCommentRanges( /*reduce*/ + false, text, pos, /*trailing*/ + false, cb, state); } function forEachTrailingCommentRange(text, pos, cb, state) { - return iterateCommentRanges( - /*reduce*/ - false, - text, - pos, - /*trailing*/ - true, - cb, - state - ); + return iterateCommentRanges( /*reduce*/ + false, text, pos, /*trailing*/ + true, cb, state); } function reduceEachLeadingCommentRange(text, pos, cb, state, initial) { - return iterateCommentRanges( - /*reduce*/ - true, - text, - pos, - /*trailing*/ - false, - cb, - state, - initial - ); + return iterateCommentRanges( /*reduce*/ + true, text, pos, /*trailing*/ + false, cb, state, initial); } function reduceEachTrailingCommentRange(text, pos, cb, state, initial) { - return iterateCommentRanges( - /*reduce*/ - true, - text, - pos, - /*trailing*/ - true, - cb, - state, - initial - ); + return iterateCommentRanges( /*reduce*/ + true, text, pos, /*trailing*/ + true, cb, state, initial); } function appendCommentRange(pos, end, kind, hasTrailingNewLine, _state, comments = []) { - comments.push({ kind, pos, end, hasTrailingNewLine }); + comments.push({ + kind, + pos, + end, + hasTrailingNewLine + }); return comments; } function getLeadingCommentRanges(text, pos) { - return reduceEachLeadingCommentRange( - text, - pos, - appendCommentRange, - /*state*/ - void 0, - /*initial*/ - void 0 - ); + return reduceEachLeadingCommentRange(text, pos, appendCommentRange, /*state*/ + void 0, /*initial*/ + void 0); } function getTrailingCommentRanges(text, pos) { - return reduceEachTrailingCommentRange( - text, - pos, - appendCommentRange, - /*state*/ - void 0, - /*initial*/ - void 0 - ); + return reduceEachTrailingCommentRange(text, pos, appendCommentRange, /*state*/ + void 0, /*initial*/ + void 0); } function getShebang(text) { const match = shebangTriviaRegex.exec(text); @@ -9588,8 +9261,9 @@ ${lanes.join("\n")} return ch >= 65 /* A */ && ch <= 90 /* Z */ || ch >= 97 /* a */ && ch <= 122 /* z */ || ch === 36 /* $ */ || ch === 95 /* _ */ || ch > 127 /* maxAsciiCharacter */ && isUnicodeIdentifierStart(ch, languageVersion); } function isIdentifierPart(ch, languageVersion, identifierVariant) { - return ch >= 65 /* A */ && ch <= 90 /* Z */ || ch >= 97 /* a */ && ch <= 122 /* z */ || ch >= 48 /* _0 */ && ch <= 57 /* _9 */ || ch === 36 /* $ */ || ch === 95 /* _ */ || // "-" and ":" are valid in JSX Identifiers - (identifierVariant === 1 /* JSX */ ? ch === 45 /* minus */ || ch === 58 /* colon */ : false) || ch > 127 /* maxAsciiCharacter */ && isUnicodeIdentifierPart(ch, languageVersion); + return ch >= 65 /* A */ && ch <= 90 /* Z */ || ch >= 97 /* a */ && ch <= 122 /* z */ || ch >= 48 /* _0 */ && ch <= 57 /* _9 */ || ch === 36 /* $ */ || ch === 95 /* _ */ || ( + // "-" and ":" are valid in JSX Identifiers + identifierVariant === 1 /* JSX */ ? ch === 45 /* minus */ || ch === 58 /* colon */ : false) || ch > 127 /* maxAsciiCharacter */ && isUnicodeIdentifierPart(ch, languageVersion); } function isIdentifierText(name, languageVersion, identifierVariant) { let ch = codePointAt(name, 0); @@ -9745,8 +9419,7 @@ ${lanes.join("\n")} 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 */; } @@ -9763,8 +9436,7 @@ ${lanes.join("\n")} if (text.charCodeAt(pos) === 69 /* E */ || text.charCodeAt(pos) === 101 /* e */) { pos++; tokenFlags |= 16 /* Scientific */; - if (text.charCodeAt(pos) === 43 /* plus */ || text.charCodeAt(pos) === 45 /* minus */) - pos++; + if (text.charCodeAt(pos) === 43 /* plus */ || text.charCodeAt(pos) === 45 /* minus */) pos++; const preNumericPart = pos; const finalFragment = scanNumberFragment(); if (!finalFragment) { @@ -9791,6 +9463,7 @@ ${lanes.join("\n")} tokenValue = "" + +result; return 9 /* NumericLiteral */; } + if (decimalFragment !== void 0 || tokenFlags & 16 /* Scientific */) { checkForIdentifierStartAfterNumericLiteral(start2, decimalFragment === void 0 && !!(tokenFlags & 16 /* Scientific */)); tokenValue = "" + +result; @@ -9807,7 +9480,9 @@ ${lanes.join("\n")} return; } const identifierStart = pos; - const { length: length3 } = scanIdentifierParts(); + const { + length: length3 + } = scanIdentifierParts(); if (length3 === 1 && text[identifierStart] === "n") { if (isScientific) { error2(Diagnostics.A_bigint_literal_cannot_use_exponential_notation, numericStart, identifierStart - numericStart + 1); @@ -9832,23 +9507,15 @@ ${lanes.join("\n")} return isOctal; } function scanExactNumberOfHexDigits(count, canHaveSeparators) { - const valueString = scanHexDigits( - /*minCount*/ - count, - /*scanAsManyAsPossible*/ - false, - canHaveSeparators - ); + const valueString = scanHexDigits( /*minCount*/ + count, /*scanAsManyAsPossible*/ + false, canHaveSeparators); return valueString ? parseInt(valueString, 16) : -1; } function scanMinimumNumberOfHexDigits(count, canHaveSeparators) { - return scanHexDigits( - /*minCount*/ - count, - /*scanAsManyAsPossible*/ - true, - canHaveSeparators - ); + return scanHexDigits( /*minCount*/ + count, /*scanAsManyAsPossible*/ + true, canHaveSeparators); } function scanHexDigits(minCount, scanAsManyAsPossible, canHaveSeparators) { let valueChars = []; @@ -9907,10 +9574,8 @@ ${lanes.join("\n")} } if (ch === 92 /* backslash */ && !jsxAttributeString) { result += text.substring(start2, pos); - result += scanEscapeSequence( - /*shouldEmitInvalidEscapeError*/ - true - ); + result += scanEscapeSequence( /*shouldEmitInvalidEscapeError*/ + true); start2 = pos; continue; } @@ -10034,11 +9699,8 @@ ${lanes.join("\n")} case 117 /* u */: if (pos < end && text.charCodeAt(pos) === 123 /* openBrace */) { pos++; - const escapedValueString = scanMinimumNumberOfHexDigits( - 1, - /*canHaveSeparators*/ - false - ); + const escapedValueString = scanMinimumNumberOfHexDigits(1, /*canHaveSeparators*/ + false); const escapedValue = escapedValueString ? parseInt(escapedValueString, 16) : -1; if (escapedValue < 0) { tokenFlags |= 2048 /* ContainsInvalidEscape */; @@ -10108,11 +9770,8 @@ ${lanes.join("\n")} } } function scanExtendedUnicodeEscape() { - const escapedValueString = scanMinimumNumberOfHexDigits( - 1, - /*canHaveSeparators*/ - false - ); + const escapedValueString = scanMinimumNumberOfHexDigits(1, /*canHaveSeparators*/ + false); const escapedValue = escapedValueString ? parseInt(escapedValueString, 16) : -1; let isInvalidExtendedEscape = false; if (escapedValue < 0) { @@ -10140,11 +9799,8 @@ ${lanes.join("\n")} if (pos + 5 < end && text.charCodeAt(pos + 1) === 117 /* u */) { const start2 = pos; pos += 2; - const value = scanExactNumberOfHexDigits( - 4, - /*canHaveSeparators*/ - false - ); + const value = scanExactNumberOfHexDigits(4, /*canHaveSeparators*/ + false); pos = start2; return value; } @@ -10154,11 +9810,8 @@ ${lanes.join("\n")} if (codePointAt(text, pos + 1) === 117 /* u */ && codePointAt(text, pos + 2) === 123 /* openBrace */) { const start2 = pos; pos += 3; - const escapedValueString = scanMinimumNumberOfHexDigits( - 1, - /*canHaveSeparators*/ - false - ); + const escapedValueString = scanMinimumNumberOfHexDigits(1, /*canHaveSeparators*/ + false); const escapedValue = escapedValueString ? parseInt(escapedValueString, 16) : -1; pos = start2; return escapedValue; @@ -10210,6 +9863,7 @@ ${lanes.join("\n")} } return token = 80 /* Identifier */; } + function scanBinaryOrOctalDigits(base) { let value = ""; let separatorAllowed = false; @@ -10256,6 +9910,7 @@ ${lanes.join("\n")} return 9 /* NumericLiteral */; } } + function scan() { fullStartPos = pos; tokenFlags = 0 /* None */; @@ -10265,6 +9920,7 @@ ${lanes.join("\n")} if (pos >= end) { return token = 1 /* EndOfFileToken */; } + const ch = codePointAt(text, pos); if (pos === 0) { if (ch === 65533 /* replacementCharacter */) { @@ -10272,6 +9928,7 @@ ${lanes.join("\n")} pos = end; return token = 8 /* NonTextFileMarkerTrivia */; } + if (ch === 35 /* hash */ && isShebangTrivia(text, pos)) { pos = scanShebangTrivia(text, pos); if (skipTrivia2) { @@ -10281,6 +9938,7 @@ ${lanes.join("\n")} } } } + switch (ch) { case 10 /* lineFeed */: case 13 /* carriageReturn */: @@ -10296,6 +9954,7 @@ ${lanes.join("\n")} } return token = 4 /* NewLineTrivia */; } + case 9 /* tab */: case 11 /* verticalTab */: case 12 /* formFeed */: @@ -10327,13 +9986,16 @@ ${lanes.join("\n")} } return token = 5 /* WhitespaceTrivia */; } + case 33 /* exclamation */: if (text.charCodeAt(pos + 1) === 61 /* equals */) { if (text.charCodeAt(pos + 2) === 61 /* equals */) { return pos += 3, token = 38 /* ExclamationEqualsEqualsToken */; } + return pos += 2, token = 36 /* ExclamationEqualsToken */; } + pos++; return token = 54 /* ExclamationToken */; case 34 /* doubleQuote */: @@ -10341,14 +10003,13 @@ ${lanes.join("\n")} tokenValue = scanString(); return token = 11 /* StringLiteral */; case 96 /* backtick */: - return token = scanTemplateAndSetTokenValue( - /*shouldEmitInvalidEscapeError*/ - false - ); + return token = scanTemplateAndSetTokenValue( /*shouldEmitInvalidEscapeError*/ + false); case 37 /* percent */: if (text.charCodeAt(pos + 1) === 61 /* equals */) { return pos += 2, token = 70 /* PercentEqualsToken */; } + pos++; return token = 45 /* PercentToken */; case 38 /* ampersand */: @@ -10356,11 +10017,14 @@ ${lanes.join("\n")} if (text.charCodeAt(pos + 2) === 61 /* equals */) { return pos += 3, token = 77 /* AmpersandAmpersandEqualsToken */; } + return pos += 2, token = 56 /* AmpersandAmpersandToken */; } + if (text.charCodeAt(pos + 1) === 61 /* equals */) { return pos += 2, token = 74 /* AmpersandEqualsToken */; } + pos++; return token = 51 /* AmpersandToken */; case 40 /* openParen */: @@ -10373,12 +10037,15 @@ ${lanes.join("\n")} if (text.charCodeAt(pos + 1) === 61 /* equals */) { return pos += 2, token = 67 /* AsteriskEqualsToken */; } + if (text.charCodeAt(pos + 1) === 42 /* asterisk */) { if (text.charCodeAt(pos + 2) === 61 /* equals */) { return pos += 3, token = 68 /* AsteriskAsteriskEqualsToken */; } + return pos += 2, token = 43 /* AsteriskAsteriskToken */; } + pos++; if (inJSDocType && !asteriskSeen && tokenFlags & 1 /* PrecedingLineBreak */) { asteriskSeen = true; @@ -10389,9 +10056,11 @@ ${lanes.join("\n")} if (text.charCodeAt(pos + 1) === 43 /* plus */) { return pos += 2, token = 46 /* PlusPlusToken */; } + if (text.charCodeAt(pos + 1) === 61 /* equals */) { return pos += 2, token = 65 /* PlusEqualsToken */; } + pos++; return token = 40 /* PlusToken */; case 44 /* comma */: @@ -10401,9 +10070,11 @@ ${lanes.join("\n")} if (text.charCodeAt(pos + 1) === 45 /* minus */) { return pos += 2, token = 47 /* MinusMinusToken */; } + if (text.charCodeAt(pos + 1) === 61 /* equals */) { return pos += 2, token = 66 /* MinusEqualsToken */; } + pos++; return token = 41 /* MinusToken */; case 46 /* dot */: @@ -10411,9 +10082,11 @@ ${lanes.join("\n")} scanNumber(); return token = 9 /* NumericLiteral */; } + if (text.charCodeAt(pos + 1) === 46 /* dot */ && text.charCodeAt(pos + 2) === 46 /* dot */) { return pos += 3, token = 26 /* DotDotDotToken */; } + pos++; return token = 25 /* DotToken */; case 47 /* slash */: @@ -10425,18 +10098,14 @@ ${lanes.join("\n")} } pos++; } - commentDirectives = appendIfCommentDirective( - commentDirectives, - text.slice(tokenStart, pos), - commentDirectiveRegExSingleLine, - tokenStart - ); + commentDirectives = appendIfCommentDirective(commentDirectives, text.slice(tokenStart, pos), commentDirectiveRegExSingleLine, tokenStart); if (skipTrivia2) { continue; } else { return token = 2 /* SingleLineCommentTrivia */; } } + if (text.charCodeAt(pos + 1) === 42 /* asterisk */) { pos += 2; const isJSDoc2 = text.charCodeAt(pos) === 42 /* asterisk */ && text.charCodeAt(pos + 1) !== 47 /* slash */; @@ -10455,9 +10124,11 @@ ${lanes.join("\n")} tokenFlags |= 1 /* PrecedingLineBreak */; } } + if (isJSDoc2 && shouldParseJSDoc()) { tokenFlags |= 2 /* PrecedingJSDocComment */; } + commentDirectives = appendIfCommentDirective(commentDirectives, text.slice(lastLineStart, pos), commentDirectiveRegExMultiLine, lastLineStart); if (!commentClosed) { error2(Diagnostics.Asterisk_Slash_expected); @@ -10468,22 +10139,22 @@ ${lanes.join("\n")} if (!commentClosed) { tokenFlags |= 4 /* Unterminated */; } + return token = 3 /* MultiLineCommentTrivia */; } } + if (text.charCodeAt(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 */)) { pos += 2; - tokenValue = scanMinimumNumberOfHexDigits( - 1, - /*canHaveSeparators*/ - true - ); + tokenValue = scanMinimumNumberOfHexDigits(1, /*canHaveSeparators*/ + true); if (!tokenValue) { error2(Diagnostics.Hexadecimal_digit_expected); tokenValue = "0"; @@ -10493,10 +10164,8 @@ ${lanes.join("\n")} return token = checkBigIntSuffix(); } else if (pos + 2 < end && (text.charCodeAt(pos + 1) === 66 /* B */ || text.charCodeAt(pos + 1) === 98 /* b */)) { pos += 2; - tokenValue = scanBinaryOrOctalDigits( - /* base */ - 2 - ); + tokenValue = scanBinaryOrOctalDigits( /* base */ + 2); if (!tokenValue) { error2(Diagnostics.Binary_digit_expected); tokenValue = "0"; @@ -10506,10 +10175,8 @@ ${lanes.join("\n")} return token = checkBigIntSuffix(); } else if (pos + 2 < end && (text.charCodeAt(pos + 1) === 79 /* O */ || text.charCodeAt(pos + 1) === 111 /* o */)) { pos += 2; - tokenValue = scanBinaryOrOctalDigits( - /* base */ - 8 - ); + tokenValue = scanBinaryOrOctalDigits( /* base */ + 8); if (!tokenValue) { error2(Diagnostics.Octal_digit_expected); tokenValue = "0"; @@ -10543,18 +10210,23 @@ ${lanes.join("\n")} return token = 7 /* ConflictMarkerTrivia */; } } + if (text.charCodeAt(pos + 1) === 60 /* lessThan */) { if (text.charCodeAt(pos + 2) === 61 /* equals */) { return pos += 3, token = 71 /* LessThanLessThanEqualsToken */; } + return pos += 2, token = 48 /* LessThanLessThanToken */; } + if (text.charCodeAt(pos + 1) === 61 /* equals */) { return pos += 2, token = 33 /* LessThanEqualsToken */; } + if (languageVariant === 1 /* JSX */ && text.charCodeAt(pos + 1) === 47 /* slash */ && text.charCodeAt(pos + 2) !== 42 /* asterisk */) { return pos += 2, token = 31 /* LessThanSlashToken */; } + pos++; return token = 30 /* LessThanToken */; case 61 /* equals */: @@ -10566,15 +10238,19 @@ ${lanes.join("\n")} return token = 7 /* ConflictMarkerTrivia */; } } + if (text.charCodeAt(pos + 1) === 61 /* equals */) { if (text.charCodeAt(pos + 2) === 61 /* equals */) { return pos += 3, token = 37 /* EqualsEqualsEqualsToken */; } + return pos += 2, token = 35 /* EqualsEqualsToken */; } + if (text.charCodeAt(pos + 1) === 62 /* greaterThan */) { return pos += 2, token = 39 /* EqualsGreaterThanToken */; } + pos++; return token = 64 /* EqualsToken */; case 62 /* greaterThan */: @@ -10586,18 +10262,22 @@ ${lanes.join("\n")} return token = 7 /* ConflictMarkerTrivia */; } } + pos++; return token = 32 /* GreaterThanToken */; case 63 /* question */: if (text.charCodeAt(pos + 1) === 46 /* dot */ && !isDigit(text.charCodeAt(pos + 2))) { return pos += 2, token = 29 /* QuestionDotToken */; } + if (text.charCodeAt(pos + 1) === 63 /* question */) { if (text.charCodeAt(pos + 2) === 61 /* equals */) { return pos += 3, token = 78 /* QuestionQuestionEqualsToken */; } + return pos += 2, token = 61 /* QuestionQuestionToken */; } + pos++; return token = 58 /* QuestionToken */; case 91 /* openBracket */: @@ -10610,6 +10290,7 @@ ${lanes.join("\n")} if (text.charCodeAt(pos + 1) === 61 /* equals */) { return pos += 2, token = 79 /* CaretEqualsToken */; } + pos++; return token = 53 /* CaretToken */; case 123 /* openBrace */: @@ -10624,15 +10305,19 @@ ${lanes.join("\n")} return token = 7 /* ConflictMarkerTrivia */; } } + if (text.charCodeAt(pos + 1) === 124 /* bar */) { if (text.charCodeAt(pos + 2) === 61 /* equals */) { return pos += 3, token = 76 /* BarBarEqualsToken */; } + return pos += 2, token = 57 /* BarBarToken */; } + if (text.charCodeAt(pos + 1) === 61 /* equals */) { return pos += 2, token = 75 /* BarEqualsToken */; } + pos++; return token = 52 /* BarToken */; case 125 /* closeBrace */: @@ -10668,6 +10353,7 @@ ${lanes.join("\n")} pos++; return token = 0 /* Unknown */; } + const charAfterHash = codePointAt(text, pos + 1); if (charAfterHash === 92 /* backslash */) { pos++; @@ -10678,6 +10364,7 @@ ${lanes.join("\n")} tokenValue = "#" + scanExtendedUnicodeEscape() + scanIdentifierParts(); return token = 81 /* PrivateIdentifier */; } + const cookedChar2 = peekUnicodeEscape(); if (cookedChar2 >= 0 && isIdentifierStart(cookedChar2, languageVersion)) { pos += 6; @@ -10685,6 +10372,7 @@ ${lanes.join("\n")} tokenValue = "#" + String.fromCharCode(cookedChar2) + scanIdentifierParts(); return token = 81 /* PrivateIdentifier */; } + pos--; } if (isIdentifierStart(charAfterHash, languageVersion)) { @@ -10714,6 +10402,7 @@ ${lanes.join("\n")} } } } + function shouldParseJSDoc() { switch (jsDocParsingMode) { case 0 /* ParseAll */: @@ -10745,8 +10434,7 @@ ${lanes.join("\n")} 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 = codePointAt(text, pos), languageVersion2)) pos += charSize(ch); tokenValue = text.substring(tokenStart, pos); if (ch === 92 /* backslash */) { tokenValue += scanIdentifierParts(); @@ -10761,19 +10449,24 @@ ${lanes.join("\n")} if (text.charCodeAt(pos + 2) === 61 /* equals */) { return pos += 3, token = 73 /* GreaterThanGreaterThanGreaterThanEqualsToken */; } + return pos += 2, token = 50 /* GreaterThanGreaterThanGreaterThanToken */; } + if (text.charCodeAt(pos + 1) === 61 /* equals */) { return pos += 2, token = 72 /* GreaterThanGreaterThanEqualsToken */; } + pos++; return token = 49 /* GreaterThanGreaterThanToken */; } + if (text.charCodeAt(pos) === 61 /* equals */) { pos++; return token = 34 /* GreaterThanEqualsToken */; } } + return token; } function reScanAsteriskEqualsToken() { @@ -10781,6 +10474,7 @@ ${lanes.join("\n")} pos = tokenStart + 1; return token = 64 /* EqualsToken */; } + function reScanSlashToken() { if (token === 44 /* SlashToken */ || token === 69 /* SlashEqualsToken */) { let p = tokenStart + 1; @@ -10819,6 +10513,7 @@ ${lanes.join("\n")} tokenValue = text.substring(tokenStart, pos); token = 14 /* RegularExpressionLiteral */; } + return token; } function appendIfCommentDirective(commentDirectives2, text2, commentDirectiveRegEx, lineStart) { @@ -10826,13 +10521,13 @@ ${lanes.join("\n")} if (type === void 0) { return commentDirectives2; } - return append( - commentDirectives2, - { - range: { pos: lineStart, end: pos }, - type - } - ); + return append(commentDirectives2, { + range: { + pos: lineStart, + end: pos + }, + type + }); } function getDirectiveFromComment(text2, commentDirectiveRegEx) { const match = commentDirectiveRegEx.exec(text2); @@ -10845,6 +10540,7 @@ ${lanes.join("\n")} case "ts-ignore": return 1 /* Ignore */; } + return void 0; } function reScanTemplateToken(isTaggedTemplate) { @@ -10853,10 +10549,8 @@ ${lanes.join("\n")} } function reScanTemplateHeadOrNoSubstitutionTemplate() { pos = tokenStart; - return token = scanTemplateAndSetTokenValue( - /*shouldEmitInvalidEscapeError*/ - true - ); + return token = scanTemplateAndSetTokenValue( /*shouldEmitInvalidEscapeError*/ + true); } function reScanJsxToken(allowMultilineJsxText = true) { pos = tokenStart = fullStartPos; @@ -10867,6 +10561,7 @@ ${lanes.join("\n")} pos = tokenStart + 1; return token = 30 /* LessThanToken */; } + return token; } function reScanHashToken() { @@ -10874,6 +10569,7 @@ ${lanes.join("\n")} pos = tokenStart + 1; return token = 63 /* HashToken */; } + return token; } function reScanQuestionToken() { @@ -10881,24 +10577,29 @@ ${lanes.join("\n")} pos = tokenStart + 1; return token = 58 /* QuestionToken */; } + function scanJsxToken(allowMultilineJsxText = true) { fullStartPos = tokenStart = pos; if (pos >= end) { return token = 1 /* EndOfFileToken */; } + let char = text.charCodeAt(pos); if (char === 60 /* lessThan */) { if (text.charCodeAt(pos + 1) === 47 /* slash */) { pos += 2; return token = 31 /* LessThanSlashToken */; } + pos++; return token = 30 /* LessThanToken */; } + if (char === 123 /* openBrace */) { pos++; return token = 19 /* OpenBraceToken */; } + let firstNonWhitespace = 0; while (pos < end) { char = text.charCodeAt(pos); @@ -10910,6 +10611,7 @@ ${lanes.join("\n")} pos = scanConflictMarkerTrivia(text, pos, error2); return token = 7 /* ConflictMarkerTrivia */; } + break; } if (char === 62 /* greaterThan */) { @@ -10930,6 +10632,7 @@ ${lanes.join("\n")} tokenValue = text.substring(fullStartPos, pos); return firstNonWhitespace === -1 ? 13 /* JsxTextAllWhiteSpaces */ : 12 /* JsxText */; } + function scanJsxIdentifier() { if (tokenIsIdentifierOrKeyword(token)) { while (pos < end) { @@ -10954,10 +10657,8 @@ ${lanes.join("\n")} switch (text.charCodeAt(pos)) { case 34 /* doubleQuote */: case 39 /* singleQuote */: - tokenValue = scanString( - /*jsxAttributeString*/ - true - ); + tokenValue = scanString( /*jsxAttributeString*/ + true); return token = 11 /* StringLiteral */; default: return scan(); @@ -10973,7 +10674,8 @@ ${lanes.join("\n")} 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 = text.charCodeAt(pos); pos < end && !isLineBreak(ch) && ch !== 96 /* backtick */; ch = codePointAt(text, ++pos)) { if (!inBackticks) { if (ch === 123 /* openBrace */) { break; @@ -10988,12 +10690,14 @@ ${lanes.join("\n")} tokenValue = text.substring(tokenStart, pos); return token = 82 /* JSDocCommentTextToken */; } + function scanJsDocToken() { fullStartPos = tokenStart = pos; tokenFlags = 0 /* None */; if (pos >= end) { return token = 1 /* EndOfFileToken */; } + const ch = codePointAt(text, pos); pos += charSize(ch); switch (ch) { @@ -11057,10 +10761,10 @@ ${lanes.join("\n")} pos++; return token = 0 /* Unknown */; } + 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 = codePointAt(text, pos), languageVersion) || text.charCodeAt(pos) === 45 /* minus */) pos += charSize(char); tokenValue = text.substring(tokenStart, pos); if (char === 92 /* backslash */) { tokenValue += scanIdentifierParts(); @@ -11070,6 +10774,7 @@ ${lanes.join("\n")} return token = 0 /* Unknown */; } } + function speculationHelper(callback, isLookahead) { const savePos = pos; const saveStartPos = fullStartPos; @@ -11110,18 +10815,12 @@ ${lanes.join("\n")} return result; } function lookAhead(callback) { - return speculationHelper( - callback, - /*isLookahead*/ - true - ); + return speculationHelper(callback, /*isLookahead*/ + true); } function tryScan(callback) { - return speculationHelper( - callback, - /*isLookahead*/ - false - ); + return speculationHelper(callback, /*isLookahead*/ + false); } function getText() { return text; @@ -11158,6 +10857,7 @@ ${lanes.join("\n")} tokenValue = void 0; tokenFlags = 0 /* None */; } + function setInJSDocType(inType) { inJSDocType += inType ? 1 : -1; } @@ -11187,6 +10887,7 @@ ${lanes.join("\n")} var init_scanner = __esm({ "src/compiler/scanner.ts"() { "use strict"; + init_ts2(); textToKeywordObj = { abstract: 128 /* AbstractKeyword */, @@ -11273,6 +10974,7 @@ ${lanes.join("\n")} await: 135 /* AwaitKeyword */, of: 165 /* OfKeyword */ }; + textToKeyword = new Map(Object.entries(textToKeywordObj)); textToToken = new Map(Object.entries({ ...textToKeywordObj, @@ -11338,6 +11040,7 @@ ${lanes.join("\n")} "#": 63 /* HashToken */, "`": 62 /* BacktickToken */ })); + unicodeES3IdentifierStart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 543, 546, 563, 592, 685, 688, 696, 699, 705, 720, 721, 736, 740, 750, 750, 890, 890, 902, 902, 904, 906, 908, 908, 910, 929, 931, 974, 976, 983, 986, 1011, 1024, 1153, 1164, 1220, 1223, 1224, 1227, 1228, 1232, 1269, 1272, 1273, 1329, 1366, 1369, 1369, 1377, 1415, 1488, 1514, 1520, 1522, 1569, 1594, 1600, 1610, 1649, 1747, 1749, 1749, 1765, 1766, 1786, 1788, 1808, 1808, 1810, 1836, 1920, 1957, 2309, 2361, 2365, 2365, 2384, 2384, 2392, 2401, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 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, 2699, 2701, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2749, 2749, 2768, 2768, 2784, 2784, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2870, 2873, 2877, 2877, 2908, 2909, 2911, 2913, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 2997, 2999, 3001, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3168, 3169, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3294, 3294, 3296, 3297, 3333, 3340, 3342, 3344, 3346, 3368, 3370, 3385, 3424, 3425, 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, 3805, 3840, 3840, 3904, 3911, 3913, 3946, 3976, 3979, 4096, 4129, 4131, 4135, 4137, 4138, 4176, 4181, 4256, 4293, 4304, 4342, 4352, 4441, 4447, 4514, 4520, 4601, 4608, 4614, 4616, 4678, 4680, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4742, 4744, 4744, 4746, 4749, 4752, 4782, 4784, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4814, 4816, 4822, 4824, 4846, 4848, 4878, 4880, 4880, 4882, 4885, 4888, 4894, 4896, 4934, 4936, 4954, 5024, 5108, 5121, 5740, 5743, 5750, 5761, 5786, 5792, 5866, 6016, 6067, 6176, 6263, 6272, 6312, 7680, 7835, 7840, 7929, 7936, 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, 8319, 8319, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8497, 8499, 8505, 8544, 8579, 12293, 12295, 12321, 12329, 12337, 12341, 12344, 12346, 12353, 12436, 12445, 12446, 12449, 12538, 12540, 12542, 12549, 12588, 12593, 12686, 12704, 12727, 13312, 19893, 19968, 40869, 40960, 42124, 44032, 55203, 63744, 64045, 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, 65138, 65140, 65140, 65142, 65276, 65313, 65338, 65345, 65370, 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500]; unicodeES3IdentifierPart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 543, 546, 563, 592, 685, 688, 696, 699, 705, 720, 721, 736, 740, 750, 750, 768, 846, 864, 866, 890, 890, 902, 902, 904, 906, 908, 908, 910, 929, 931, 974, 976, 983, 986, 1011, 1024, 1153, 1155, 1158, 1164, 1220, 1223, 1224, 1227, 1228, 1232, 1269, 1272, 1273, 1329, 1366, 1369, 1369, 1377, 1415, 1425, 1441, 1443, 1465, 1467, 1469, 1471, 1471, 1473, 1474, 1476, 1476, 1488, 1514, 1520, 1522, 1569, 1594, 1600, 1621, 1632, 1641, 1648, 1747, 1749, 1756, 1759, 1768, 1770, 1773, 1776, 1788, 1808, 1836, 1840, 1866, 1920, 1968, 2305, 2307, 2309, 2361, 2364, 2381, 2384, 2388, 2392, 2403, 2406, 2415, 2433, 2435, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2492, 2492, 2494, 2500, 2503, 2504, 2507, 2509, 2519, 2519, 2524, 2525, 2527, 2531, 2534, 2545, 2562, 2562, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2620, 2620, 2622, 2626, 2631, 2632, 2635, 2637, 2649, 2652, 2654, 2654, 2662, 2676, 2689, 2691, 2693, 2699, 2701, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2748, 2757, 2759, 2761, 2763, 2765, 2768, 2768, 2784, 2784, 2790, 2799, 2817, 2819, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2870, 2873, 2876, 2883, 2887, 2888, 2891, 2893, 2902, 2903, 2908, 2909, 2911, 2913, 2918, 2927, 2946, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 2997, 2999, 3001, 3006, 3010, 3014, 3016, 3018, 3021, 3031, 3031, 3047, 3055, 3073, 3075, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3134, 3140, 3142, 3144, 3146, 3149, 3157, 3158, 3168, 3169, 3174, 3183, 3202, 3203, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3262, 3268, 3270, 3272, 3274, 3277, 3285, 3286, 3294, 3294, 3296, 3297, 3302, 3311, 3330, 3331, 3333, 3340, 3342, 3344, 3346, 3368, 3370, 3385, 3390, 3395, 3398, 3400, 3402, 3405, 3415, 3415, 3424, 3425, 3430, 3439, 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, 3805, 3840, 3840, 3864, 3865, 3872, 3881, 3893, 3893, 3895, 3895, 3897, 3897, 3902, 3911, 3913, 3946, 3953, 3972, 3974, 3979, 3984, 3991, 3993, 4028, 4038, 4038, 4096, 4129, 4131, 4135, 4137, 4138, 4140, 4146, 4150, 4153, 4160, 4169, 4176, 4185, 4256, 4293, 4304, 4342, 4352, 4441, 4447, 4514, 4520, 4601, 4608, 4614, 4616, 4678, 4680, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4742, 4744, 4744, 4746, 4749, 4752, 4782, 4784, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4814, 4816, 4822, 4824, 4846, 4848, 4878, 4880, 4880, 4882, 4885, 4888, 4894, 4896, 4934, 4936, 4954, 4969, 4977, 5024, 5108, 5121, 5740, 5743, 5750, 5761, 5786, 5792, 5866, 6016, 6099, 6112, 6121, 6160, 6169, 6176, 6263, 6272, 6313, 7680, 7835, 7840, 7929, 7936, 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, 8319, 8319, 8400, 8412, 8417, 8417, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8497, 8499, 8505, 8544, 8579, 12293, 12295, 12321, 12335, 12337, 12341, 12344, 12346, 12353, 12436, 12441, 12442, 12445, 12446, 12449, 12542, 12549, 12588, 12593, 12686, 12704, 12727, 13312, 19893, 19968, 40869, 40960, 42124, 44032, 55203, 63744, 64045, 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, 65056, 65059, 65075, 65076, 65101, 65103, 65136, 65138, 65140, 65140, 65142, 65276, 65296, 65305, 65313, 65338, 65343, 65343, 65345, 65370, 65381, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500]; 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]; @@ -11350,7 +11053,7 @@ ${lanes.join("\n")} tokenStrings = makeReverseMap(textToToken); mergeConflictMarkerLength = "<<<<<<<".length; shebangTriviaRegex = /^#!.*/; - utf16EncodeAsStringWorker = String.fromCodePoint ? (codePoint) => String.fromCodePoint(codePoint) : utf16EncodeAsStringFallback; + utf16EncodeAsStringWorker = String.fromCodePoint ? codePoint => String.fromCodePoint(codePoint) : utf16EncodeAsStringFallback; } }); @@ -11433,7 +11136,10 @@ ${lanes.join("\n")} if (length2 < 0) { throw new Error("length < 0"); } - return { start, length: length2 }; + return { + start, + length: length2 + }; } function createTextSpanFromBounds(start, end) { return createTextSpan(start, end - start); @@ -11448,7 +11154,10 @@ ${lanes.join("\n")} if (newLength < 0) { throw new Error("newLength < 0"); } - return { span, newLength }; + return { + span, + newLength + }; } function collapseTextChangeRangesAcrossMultipleVersions(changes) { if (changes.length === 0) { @@ -11473,11 +11182,8 @@ ${lanes.join("\n")} oldEndN = Math.max(oldEnd1, oldEnd1 + (oldEnd2 - newEnd1)); newEndN = Math.max(newEnd2, newEnd2 + (newEnd1 - oldEnd2)); } - return createTextChangeRange( - createTextSpanFromBounds(oldStartN, oldEndN), - /*newLength*/ - newEndN - oldStartN - ); + return createTextChangeRange(createTextSpanFromBounds(oldStartN, oldEndN), /*newLength*/ + newEndN - oldStartN); } function getTypeParameterOwner(d) { if (d && d.kind === 168 /* TypeParameter */) { @@ -11491,6 +11197,7 @@ ${lanes.join("\n")} function isParameterPropertyDeclaration(node, parent2) { return isParameter(node) && hasSyntacticModifier(node, 31 /* ParameterPropertyModifier */) && parent2.kind === 176 /* Constructor */; } + function isEmptyBindingPattern(node) { if (isBindingPattern(node)) { return every(node.elements, isEmptyBindingElement); @@ -11551,12 +11258,8 @@ ${lanes.join("\n")} const language = matchResult[1]; const territory = matchResult[3]; if (contains(supportedLocaleDirectories, lowerCaseLocale) && !trySetLanguageAndTerritory(language, territory, errors)) { - trySetLanguageAndTerritory( - language, - /*territory*/ - void 0, - errors - ); + trySetLanguageAndTerritory(language, /*territory*/ + void 0, errors); } setUILocale(locale); function trySetLanguageAndTerritory(language2, territory2, errors2) { @@ -11677,15 +11380,17 @@ ${lanes.join("\n")} } } break; - case 217 /* ParenthesizedExpression */: { - return getDeclarationIdentifier(hostNode.expression); - } - case 256 /* LabeledStatement */: { - if (isDeclaration(hostNode.statement) || isExpression(hostNode.statement)) { - return getDeclarationIdentifier(hostNode.statement); + case 217 /* ParenthesizedExpression */: + { + return getDeclarationIdentifier(hostNode.expression); + } + case 256 /* LabeledStatement */: + { + if (isDeclaration(hostNode.statement) || isExpression(hostNode.statement)) { + return getDeclarationIdentifier(hostNode.statement); + } + break; } - break; - } } } function getDeclarationIdentifier(node) { @@ -11696,7 +11401,7 @@ ${lanes.join("\n")} if (isNamedDeclaration(statement) && isIdentifier(statement.name) && idText(statement.name) === idText(name)) { return true; } - if (isVariableStatement(statement) && some(statement.declarationList.declarations, (d) => nodeHasName(d, name))) { + if (isVariableStatement(statement) && some(statement.declarationList.declarations, d => nodeHasName(d, name))) { return true; } return false; @@ -11712,38 +11417,45 @@ ${lanes.join("\n")} case 80 /* Identifier */: return declaration; case 355 /* JSDocPropertyTag */: - case 348 /* JSDocParameterTag */: { - const { name } = declaration; - if (name.kind === 166 /* QualifiedName */) { - return name.right; + case 348 /* JSDocParameterTag */: + { + const { + name + } = declaration; + if (name.kind === 166 /* QualifiedName */) { + return name.right; + } + break; } - break; - } case 213 /* CallExpression */: - case 226 /* BinaryExpression */: { - const expr2 = declaration; - switch (getAssignmentDeclarationKind(expr2)) { - case 1 /* ExportsProperty */: - case 4 /* ThisProperty */: - case 5 /* Property */: - case 3 /* PrototypeProperty */: - return getElementOrPropertyAccessArgumentExpressionOrName(expr2.left); - case 7 /* ObjectDefinePropertyValue */: - case 8 /* ObjectDefinePropertyExports */: - case 9 /* ObjectDefinePrototypeProperty */: - return expr2.arguments[1]; - default: - return void 0; + case 226 /* BinaryExpression */: + { + const expr2 = declaration; + switch (getAssignmentDeclarationKind(expr2)) { + case 1 /* ExportsProperty */: + case 4 /* ThisProperty */: + case 5 /* Property */: + case 3 /* PrototypeProperty */: + return getElementOrPropertyAccessArgumentExpressionOrName(expr2.left); + case 7 /* ObjectDefinePropertyValue */: + case 8 /* ObjectDefinePropertyExports */: + case 9 /* ObjectDefinePrototypeProperty */: + return expr2.arguments[1]; + default: + return void 0; + } } - } case 353 /* JSDocTypedefTag */: return getNameOfJSDocTypedef(declaration); case 347 /* JSDocEnumTag */: return nameForNamelessJSDocTypedef(declaration); - case 277 /* ExportAssignment */: { - const { expression } = declaration; - return isIdentifier(expression) ? expression : void 0; - } + case 277 /* ExportAssignment */: + { + const { + expression + } = declaration; + return isIdentifier(expression) ? expression : void 0; + } case 212 /* ElementAccessExpression */: const expr = declaration; if (isBindableStaticElementAccessExpression(expr)) { @@ -11753,8 +11465,7 @@ ${lanes.join("\n")} 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) { @@ -11786,7 +11497,7 @@ ${lanes.join("\n")} if (param.name) { if (isIdentifier(param.name)) { const name = param.name.escapedText; - return getJSDocTagsWorker(param.parent, noCache).filter((tag) => isJSDocParameterTag(tag) && isIdentifier(tag.name) && tag.name.escapedText === name); + return getJSDocTagsWorker(param.parent, noCache).filter(tag => isJSDocParameterTag(tag) && isIdentifier(tag.name) && tag.name.escapedText === name); } else { const i = param.parent.parameters.indexOf(param); Debug.assert(i > -1, "Parameters should always be in their parents' parameter list"); @@ -11799,36 +11510,24 @@ ${lanes.join("\n")} return emptyArray; } function getJSDocParameterTags(param) { - return getJSDocParameterTagsWorker( - param, - /*noCache*/ - false - ); + return getJSDocParameterTagsWorker(param, /*noCache*/ + false); } function getJSDocParameterTagsNoCache(param) { - return getJSDocParameterTagsWorker( - param, - /*noCache*/ - true - ); + return getJSDocParameterTagsWorker(param, /*noCache*/ + true); } function getJSDocTypeParameterTagsWorker(param, noCache) { const name = param.name.escapedText; - return getJSDocTagsWorker(param.parent, noCache).filter((tag) => isJSDocTemplateTag(tag) && tag.typeParameters.some((tp) => tp.name.escapedText === name)); + return getJSDocTagsWorker(param.parent, noCache).filter(tag => isJSDocTemplateTag(tag) && tag.typeParameters.some(tp => tp.name.escapedText === name)); } function getJSDocTypeParameterTags(param) { - return getJSDocTypeParameterTagsWorker( - param, - /*noCache*/ - false - ); + return getJSDocTypeParameterTagsWorker(param, /*noCache*/ + false); } function getJSDocTypeParameterTagsNoCache(param) { - return getJSDocTypeParameterTagsWorker( - param, - /*noCache*/ - true - ); + return getJSDocTypeParameterTagsWorker(param, /*noCache*/ + true); } function hasJSDocParameterTags(node) { return !!getFirstJSDocTag(node, isJSDocParameterTag); @@ -11846,64 +11545,40 @@ ${lanes.join("\n")} return getFirstJSDocTag(node, isJSDocPublicTag); } function getJSDocPublicTagNoCache(node) { - return getFirstJSDocTag( - node, - isJSDocPublicTag, - /*noCache*/ - true - ); + return getFirstJSDocTag(node, isJSDocPublicTag, /*noCache*/ + true); } function getJSDocPrivateTag(node) { return getFirstJSDocTag(node, isJSDocPrivateTag); } function getJSDocPrivateTagNoCache(node) { - return getFirstJSDocTag( - node, - isJSDocPrivateTag, - /*noCache*/ - true - ); + return getFirstJSDocTag(node, isJSDocPrivateTag, /*noCache*/ + true); } function getJSDocProtectedTag(node) { return getFirstJSDocTag(node, isJSDocProtectedTag); } function getJSDocProtectedTagNoCache(node) { - return getFirstJSDocTag( - node, - isJSDocProtectedTag, - /*noCache*/ - true - ); + return getFirstJSDocTag(node, isJSDocProtectedTag, /*noCache*/ + true); } function getJSDocReadonlyTag(node) { return getFirstJSDocTag(node, isJSDocReadonlyTag); } function getJSDocReadonlyTagNoCache(node) { - return getFirstJSDocTag( - node, - isJSDocReadonlyTag, - /*noCache*/ - true - ); + return getFirstJSDocTag(node, isJSDocReadonlyTag, /*noCache*/ + true); } function getJSDocOverrideTagNoCache(node) { - return getFirstJSDocTag( - node, - isJSDocOverrideTag, - /*noCache*/ - true - ); + return getFirstJSDocTag(node, isJSDocOverrideTag, /*noCache*/ + true); } function getJSDocDeprecatedTag(node) { return getFirstJSDocTag(node, isJSDocDeprecatedTag); } function getJSDocDeprecatedTagNoCache(node) { - return getFirstJSDocTag( - node, - isJSDocDeprecatedTag, - /*noCache*/ - true - ); + return getFirstJSDocTag(node, isJSDocDeprecatedTag, /*noCache*/ + true); } function getJSDocEnumTag(node) { return getFirstJSDocTag(node, isJSDocEnumTag); @@ -11930,7 +11605,7 @@ ${lanes.join("\n")} function getJSDocType(node) { let tag = getFirstJSDocTag(node, isJSDocTypeTag); if (!tag && isParameter(node)) { - tag = find(getJSDocParameterTags(node), (tag2) => !!tag2.typeExpression); + tag = find(getJSDocParameterTags(node), tag2 => !!tag2.typeExpression); } return tag && tag.typeExpression && tag.typeExpression.type; } @@ -11953,33 +11628,27 @@ ${lanes.join("\n")} } 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); Debug.assert(comments.length < 2 || comments[0] !== comments[1]); - tags = flatMap(comments, (j) => isJSDoc(j) ? j.tags : j); + tags = flatMap(comments, j => isJSDoc(j) ? j.tags : j); if (!noCache) { - node.jsDoc ?? (node.jsDoc = []); + var _node$jsDoc; + (_node$jsDoc = node.jsDoc) !== null && _node$jsDoc !== void 0 ? _node$jsDoc : node.jsDoc = []; node.jsDoc.jsDocCache = tags; } } return tags; } function getJSDocTags(node) { - return getJSDocTagsWorker( - node, - /*noCache*/ - false - ); + return getJSDocTagsWorker(node, /*noCache*/ + false); } function getJSDocTagsNoCache(node) { - return getJSDocTagsWorker( - node, - /*noCache*/ - true - ); + return getJSDocTagsWorker(node, /*noCache*/ + true); } function getFirstJSDocTag(node, predicate, noCache) { return find(getJSDocTagsWorker(node, noCache), predicate); @@ -11988,10 +11657,10 @@ ${lanes.join("\n")} return getJSDocTags(node).filter(predicate); } function getAllJSDocTagsOfKind(node, kind) { - return getJSDocTags(node).filter((doc) => doc.kind === kind); + return getJSDocTags(node).filter(doc => doc.kind === kind); } function getTextOfJSDocComment(comment) { - return typeof comment === "string" ? comment : comment == null ? void 0 : comment.map((c) => c.kind === 328 /* JSDocText */ ? c.text : formatJSDocLink(c)).join(""); + return typeof comment === "string" ? comment : comment == null ? void 0 : comment.map(c => c.kind === 328 /* JSDocText */ ? c.text : formatJSDocLink(c)).join(""); } function formatJSDocLink(link) { const kind = link.kind === 331 /* JSDocLink */ ? "link" : link.kind === 332 /* JSDocLinkCode */ ? "linkcode" : "linkplain"; @@ -12004,14 +11673,14 @@ ${lanes.join("\n")} if (isJSDocOverloadTag(node.parent)) { const jsDoc = getJSDocRoot(node.parent); if (jsDoc && length(jsDoc.tags)) { - return flatMap(jsDoc.tags, (tag) => isJSDocTemplateTag(tag) ? tag.typeParameters : void 0); + return flatMap(jsDoc.tags, tag => isJSDocTemplateTag(tag) ? tag.typeParameters : void 0); } } return emptyArray; } if (isJSDocTypeAlias(node)) { Debug.assert(node.parent.kind === 327 /* JSDoc */); - return flatMap(node.parent.tags, (tag) => isJSDocTemplateTag(tag) ? tag.typeParameters : void 0); + return flatMap(node.parent.tags, tag => isJSDocTemplateTag(tag) ? tag.typeParameters : void 0); } if (node.typeParameters) { return node.typeParameters; @@ -12037,22 +11706,28 @@ ${lanes.join("\n")} function isMemberName(node) { return node.kind === 80 /* Identifier */ || node.kind === 81 /* PrivateIdentifier */; } + function isGetOrSetAccessorDeclaration(node) { return node.kind === 178 /* SetAccessor */ || node.kind === 177 /* GetAccessor */; } + function isPropertyAccessChain(node) { return isPropertyAccessExpression(node) && !!(node.flags & 64 /* OptionalChain */); } + function isElementAccessChain(node) { return isElementAccessExpression(node) && !!(node.flags & 64 /* OptionalChain */); } + function isCallChain(node) { return isCallExpression(node) && !!(node.flags & 64 /* OptionalChain */); } + function isOptionalChain(node) { const kind = node.kind; return !!(node.flags & 64 /* OptionalChain */) && (kind === 211 /* PropertyAccessExpression */ || kind === 212 /* ElementAccessExpression */ || kind === 213 /* CallExpression */ || kind === 235 /* NonNullExpression */); } + function isOptionalChainRoot(node) { return isOptionalChain(node) && !isNonNullExpression(node) && !!node.questionDotToken; } @@ -12065,21 +11740,26 @@ ${lanes.join("\n")} function isNullishCoalesce(node) { return node.kind === 226 /* BinaryExpression */ && node.operatorToken.kind === 61 /* QuestionQuestionToken */; } + function isConstTypeReference(node) { return isTypeReferenceNode(node) && isIdentifier(node.typeName) && node.typeName.escapedText === "const" && !node.typeArguments; } function skipPartiallyEmittedExpressions(node) { return skipOuterExpressions(node, 8 /* PartiallyEmittedExpressions */); } + function isNonNullChain(node) { return isNonNullExpression(node) && !!(node.flags & 64 /* OptionalChain */); } + function isBreakOrContinueStatement(node) { return node.kind === 252 /* BreakStatement */ || node.kind === 251 /* ContinueStatement */; } + function isNamedExportBindings(node) { return node.kind === 280 /* NamespaceExport */ || node.kind === 279 /* NamedExports */; } + function isUnparsedTextLike(node) { switch (node.kind) { case 309 /* UnparsedText */: @@ -12092,18 +11772,22 @@ ${lanes.join("\n")} function isUnparsedNode(node) { return isUnparsedTextLike(node) || node.kind === 307 /* UnparsedPrologue */ || node.kind === 311 /* UnparsedSyntheticReference */; } + function isJSDocPropertyLikeTag(node) { return node.kind === 355 /* JSDocPropertyTag */ || node.kind === 348 /* JSDocParameterTag */; } + function isNode(node) { return isNodeKind(node.kind); } function isNodeKind(kind) { return kind >= 166 /* FirstNode */; } + function isTokenKind(kind) { return kind >= 0 /* FirstToken */ && kind <= 165 /* LastToken */; } + function isToken(n) { return isTokenKind(n.kind); } @@ -12113,6 +11797,7 @@ ${lanes.join("\n")} function isLiteralKind(kind) { return 9 /* FirstLiteralToken */ <= kind && kind <= 15 /* LastLiteralToken */; } + function isLiteralExpression(node) { return isLiteralKind(node.kind); } @@ -12130,6 +11815,7 @@ ${lanes.join("\n")} function isTemplateLiteralKind(kind) { return 15 /* FirstTemplateToken */ <= kind && kind <= 18 /* LastTemplateToken */; } + function isTemplateLiteralToken(node) { return isTemplateLiteralKind(node.kind); } @@ -12137,6 +11823,7 @@ ${lanes.join("\n")} const kind = node.kind; return kind === 17 /* TemplateMiddle */ || kind === 18 /* TemplateTail */; } + function isImportOrExportSpecifier(node) { return isImportSpecifier(node) || isExportSpecifier(node); } @@ -12184,6 +11871,7 @@ ${lanes.join("\n")} const flags = node.emitNode.autoGenerate.flags; return !!(flags & 32 /* FileLevel */) && !!(flags & 16 /* Optimistic */) && !!(flags & 8 /* ReservedInNestedScopes */); } + function isPrivateIdentifierClassElementDeclaration(node) { return (isPropertyDeclaration(node) || isMethodOrAccessor(node)) && isPrivateIdentifier(node.name); } @@ -12214,9 +11902,11 @@ ${lanes.join("\n")} function isParameterPropertyModifier(kind) { return !!(modifierToFlag(kind) & 31 /* ParameterPropertyModifier */); } + function isClassMemberModifier(idToken) { return isParameterPropertyModifier(idToken) || idToken === 126 /* StaticKeyword */ || idToken === 164 /* OverrideKeyword */ || idToken === 129 /* AccessorKeyword */; } + function isModifier(node) { return isModifierKind(node.kind); } @@ -12224,14 +11914,17 @@ ${lanes.join("\n")} const kind = node.kind; return kind === 166 /* QualifiedName */ || kind === 80 /* Identifier */; } + function isPropertyName(node) { const kind = node.kind; return kind === 80 /* Identifier */ || kind === 81 /* PrivateIdentifier */ || kind === 11 /* StringLiteral */ || kind === 9 /* NumericLiteral */ || kind === 167 /* ComputedPropertyName */; } + function isBindingName(node) { const kind = node.kind; return kind === 80 /* Identifier */ || kind === 206 /* ObjectBindingPattern */ || kind === 207 /* ArrayBindingPattern */; } + function isFunctionLike(node) { return !!node && isFunctionLikeKind(node.kind); } @@ -12244,6 +11937,7 @@ ${lanes.join("\n")} function isBooleanLiteral(node) { return node.kind === 112 /* TrueKeyword */ || node.kind === 97 /* FalseKeyword */; } + function isFunctionLikeDeclarationKind(kind) { switch (kind) { case 262 /* FunctionDeclaration */: @@ -12280,22 +11974,22 @@ ${lanes.join("\n")} const kind = node.kind; return kind === 176 /* Constructor */ || kind === 172 /* PropertyDeclaration */ || kind === 174 /* MethodDeclaration */ || kind === 177 /* GetAccessor */ || kind === 178 /* SetAccessor */ || kind === 181 /* IndexSignature */ || kind === 175 /* ClassStaticBlockDeclaration */ || kind === 240 /* SemicolonClassElement */; } + function isClassLike(node) { return node && (node.kind === 263 /* ClassDeclaration */ || node.kind === 231 /* ClassExpression */); } + function isAccessor(node) { return node && (node.kind === 177 /* GetAccessor */ || node.kind === 178 /* SetAccessor */); } + function isAutoAccessorPropertyDeclaration(node) { return isPropertyDeclaration(node) && hasAccessorModifier(node); } function isClassInstanceProperty(node) { if (isInJSFile(node) && isExpandoPropertyDeclaration(node)) { - return (!isBindableStaticAccessExpression(node) || !isPrototypeAccess(node.expression)) && !isBindableStaticNameExpression( - node, - /*excludeThisKeyword*/ - true - ); + return (!isBindableStaticAccessExpression(node) || !isPrototypeAccess(node.expression)) && !isBindableStaticNameExpression(node, /*excludeThisKeyword*/ + true); } return node.parent && isClassLike(node.parent) && isPropertyDeclaration(node) && !hasAccessorModifier(node); } @@ -12327,6 +12021,7 @@ ${lanes.join("\n")} const kind = node.kind; return kind === 180 /* ConstructSignature */ || kind === 179 /* CallSignature */ || kind === 171 /* PropertySignature */ || kind === 173 /* MethodSignature */ || kind === 181 /* IndexSignature */ || kind === 177 /* GetAccessor */ || kind === 178 /* SetAccessor */; } + function isClassOrTypeElement(node) { return isTypeElement(node) || isClassElement(node); } @@ -12334,6 +12029,7 @@ ${lanes.join("\n")} const kind = node.kind; return kind === 303 /* PropertyAssignment */ || kind === 304 /* ShorthandPropertyAssignment */ || kind === 305 /* SpreadAssignment */ || kind === 174 /* MethodDeclaration */ || kind === 177 /* GetAccessor */ || kind === 178 /* SetAccessor */; } + function isTypeNode(node) { return isTypeNodeKind(node.kind); } @@ -12350,16 +12046,19 @@ ${lanes.join("\n")} const kind = node.kind; return kind === 207 /* ArrayBindingPattern */ || kind === 206 /* ObjectBindingPattern */; } + return false; } function isAssignmentPattern(node) { const kind = node.kind; return kind === 209 /* ArrayLiteralExpression */ || kind === 210 /* ObjectLiteralExpression */; } + function isArrayBindingElement(node) { const kind = node.kind; return kind === 208 /* BindingElement */ || kind === 232 /* OmittedExpression */; } + function isDeclarationBindingElement(bindingElement) { switch (bindingElement.kind) { case 260 /* VariableDeclaration */: @@ -12413,20 +12112,19 @@ ${lanes.join("\n")} case 212 /* ElementAccessExpression */: return true; } - return isAssignmentExpression( - node, - /*excludeCompoundAssignment*/ - true - ); + return isAssignmentExpression(node, /*excludeCompoundAssignment*/ + true); } 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); } @@ -12446,10 +12144,12 @@ ${lanes.join("\n")} function isCallOrNewExpression(node) { return node.kind === 213 /* CallExpression */ || node.kind === 214 /* NewExpression */; } + function isTemplateLiteral(node) { const kind = node.kind; return kind === 228 /* TemplateExpression */ || kind === 15 /* NoSubstitutionTemplateLiteral */; } + function isLeftHandSideExpression(node) { return isLeftHandSideExpressionKind(skipPartiallyEmittedExpressions(node).kind); } @@ -12553,6 +12253,7 @@ ${lanes.join("\n")} const kind = node.kind; return kind === 216 /* TypeAssertionExpression */ || kind === 234 /* AsExpression */; } + function isNotEmittedOrPartiallyEmittedNode(node) { return isNotEmittedStatement(node) || isPartiallyEmittedExpression(node); } @@ -12581,9 +12282,11 @@ ${lanes.join("\n")} function isExternalModuleIndicator(result) { return isAnyImportOrReExport(result) || isExportAssignment(result) || hasSyntacticModifier(result, 32 /* Export */); } + function isForInOrOfStatement(node) { return node.kind === 249 /* ForInStatement */ || node.kind === 250 /* ForOfStatement */; } + function isConciseBody(node) { return isBlock(node) || isExpression(node); } @@ -12597,21 +12300,26 @@ ${lanes.join("\n")} const kind = node.kind; return kind === 268 /* ModuleBlock */ || kind === 267 /* ModuleDeclaration */ || kind === 80 /* Identifier */; } + function isNamespaceBody(node) { const kind = node.kind; return kind === 268 /* ModuleBlock */ || kind === 267 /* ModuleDeclaration */; } + function isJSDocNamespaceBody(node) { const kind = node.kind; return kind === 80 /* Identifier */ || kind === 267 /* ModuleDeclaration */; } + function isNamedImportBindings(node) { const kind = node.kind; return kind === 275 /* NamedImports */ || kind === 274 /* NamespaceImport */; } + function isModuleOrEnumDeclaration(node) { return node.kind === 267 /* ModuleDeclaration */ || node.kind === 266 /* EnumDeclaration */; } + function canHaveSymbol(node) { switch (node.kind) { case 219 /* ArrowFunction */: @@ -12723,12 +12431,15 @@ ${lanes.join("\n")} 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 === 353 /* JSDocTypedefTag */ || kind === 345 /* JSDocCallbackTag */ || kind === 355 /* JSDocPropertyTag */; } + 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 */; } + function isStatementKindButNotDeclarationKind(kind) { return kind === 252 /* BreakStatement */ || kind === 251 /* ContinueStatement */ || kind === 259 /* DebuggerStatement */ || kind === 246 /* DoStatement */ || kind === 244 /* ExpressionStatement */ || kind === 242 /* EmptyStatement */ || kind === 249 /* ForInStatement */ || kind === 250 /* ForOfStatement */ || kind === 248 /* ForStatement */ || kind === 245 /* IfStatement */ || kind === 256 /* LabeledStatement */ || kind === 253 /* ReturnStatement */ || kind === 255 /* SwitchStatement */ || kind === 257 /* ThrowStatement */ || kind === 258 /* TryStatement */ || kind === 243 /* VariableStatement */ || kind === 247 /* WhileStatement */ || kind === 254 /* WithStatement */ || kind === 359 /* NotEmittedStatement */; } + function isDeclaration(node) { if (node.kind === 168 /* TypeParameter */) { return node.parent && node.parent.kind !== 352 /* JSDocTemplateTag */ || isInJSFile(node); @@ -12746,8 +12457,7 @@ ${lanes.join("\n")} 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; @@ -12759,53 +12469,66 @@ ${lanes.join("\n")} const kind = node.kind; return isStatementKindButNotDeclarationKind(kind) || isDeclarationStatementKind(kind) || kind === 241 /* Block */; } + function isModuleReference(node) { const kind = node.kind; return kind === 283 /* ExternalModuleReference */ || kind === 166 /* QualifiedName */ || kind === 80 /* Identifier */; } + function isJsxTagNameExpression(node) { const kind = node.kind; return kind === 110 /* ThisKeyword */ || kind === 80 /* Identifier */ || kind === 211 /* PropertyAccessExpression */ || kind === 295 /* JsxNamespacedName */; } + function isJsxChild(node) { const kind = node.kind; return kind === 284 /* JsxElement */ || kind === 294 /* JsxExpression */ || kind === 285 /* JsxSelfClosingElement */ || kind === 12 /* JsxText */ || kind === 288 /* JsxFragment */; } + function isJsxAttributeLike(node) { const kind = node.kind; return kind === 291 /* JsxAttribute */ || kind === 293 /* JsxSpreadAttribute */; } + function isStringLiteralOrJsxExpression(node) { const kind = node.kind; return kind === 11 /* StringLiteral */ || kind === 294 /* JsxExpression */; } + function isJsxOpeningLikeElement(node) { const kind = node.kind; return kind === 286 /* JsxOpeningElement */ || kind === 285 /* JsxSelfClosingElement */; } + function isCaseOrDefaultClause(node) { const kind = node.kind; return kind === 296 /* CaseClause */ || kind === 297 /* DefaultClause */; } + function isJSDocNode(node) { return node.kind >= 316 /* FirstJSDocNode */ && node.kind <= 357 /* LastJSDocNode */; } + function isJSDocCommentContainingNode(node) { return node.kind === 327 /* JSDoc */ || node.kind === 326 /* JSDocNamepathType */ || node.kind === 328 /* JSDocText */ || isJSDocLinkLike(node) || isJSDocTag(node) || isJSDocTypeLiteral(node) || isJSDocSignature(node); } function isJSDocTag(node) { return node.kind >= 334 /* FirstJSDocTagNode */ && node.kind <= 357 /* LastJSDocTagNode */; } + function isSetAccessor(node) { return node.kind === 178 /* SetAccessor */; } + function isGetAccessor(node) { return node.kind === 177 /* GetAccessor */; } + function hasJSDocNodes(node) { - if (!canHaveJSDoc(node)) - return false; - const { jsDoc } = node; + if (!canHaveJSDoc(node)) return false; + const { + jsDoc + } = node; return !!jsDoc && jsDoc.length > 0; } function hasType(node) { @@ -12833,6 +12556,7 @@ ${lanes.join("\n")} function isTypeReferenceType(node) { return node.kind === 183 /* TypeReference */ || node.kind === 233 /* ExpressionWithTypeArguments */; } + function guessIndentation(lines) { let indentation = MAX_SMI_X86; for (const line of lines) { @@ -12857,9 +12581,11 @@ ${lanes.join("\n")} function isStringLiteralLike(node) { return node.kind === 11 /* StringLiteral */ || node.kind === 15 /* NoSubstitutionTemplateLiteral */; } + function isJSDocLinkLike(node) { return node.kind === 331 /* JSDocLink */ || node.kind === 332 /* JSDocLinkCode */ || node.kind === 333 /* JSDocLinkPlain */; } + function hasRestParameter(s) { const last2 = lastOrUndefined(s.parameters); return !!last2 && isRestParameter(last2); @@ -12868,10 +12594,12 @@ ${lanes.join("\n")} const type = isJSDocParameterTag(node) ? node.typeExpression && node.typeExpression.type : node.type; return node.dotDotDotToken !== void 0 || !!type && type.kind === 325 /* JSDocVariadicType */; } + var unchangedTextChangeRange, supportedLocaleDirectories, MAX_SMI_X86; var init_utilitiesPublic = __esm({ "src/compiler/utilitiesPublic.ts"() { "use strict"; + init_ts2(); unchangedTextChangeRange = createTextChangeRange(createTextSpan(0, 0), 0); supportedLocaleDirectories = ["cs", "de", "es", "fr", "it", "ja", "ko", "pl", "pt-br", "ru", "tr", "zh-cn", "zh-tw"]; @@ -12892,10 +12620,10 @@ ${lanes.join("\n")} return void 0; } function getDeclarationsOfKind(symbol, kind) { - return filter(symbol.declarations || emptyArray, (d) => d.kind === kind); + return filter(symbol.declarations || emptyArray, d => d.kind === kind); } function createSymbolTable(symbols) { - const result = /* @__PURE__ */ new Map(); + const result = /* @__PURE__ */new Map(); if (symbols) { for (const symbol of symbols) { result.set(symbol.escapedName, symbol); @@ -12908,7 +12636,7 @@ ${lanes.join("\n")} } function createSingleLineStringWriter() { var str = ""; - const writeText = (text) => str += text; + const writeText = text => str += text; return { getText: () => str, write: writeText, @@ -12949,17 +12677,14 @@ ${lanes.join("\n")} return optionsHaveChanges(oldOptions, newOptions, optionsAffectingProgramStructure); } function optionsHaveChanges(oldOptions, newOptions, optionDeclarations2) { - return oldOptions !== newOptions && optionDeclarations2.some((o) => !isJsonEqual(getCompilerOptionValue(oldOptions, o), getCompilerOptionValue(newOptions, o))); + return oldOptions !== newOptions && optionDeclarations2.some(o => !isJsonEqual(getCompilerOptionValue(oldOptions, o), getCompilerOptionValue(newOptions, o))); } 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; } } @@ -13010,39 +12735,25 @@ ${lanes.join("\n")} function createModuleNotFoundChain(sourceFile, host, moduleReference, mode, packageName) { var _a; const node10Result = (_a = host.getResolvedModule(sourceFile, moduleReference, mode)) == null ? void 0 : _a.node10Result; - const result = node10Result ? chainDiagnosticMessages( - /*details*/ - void 0, - Diagnostics.There_are_types_at_0_but_this_result_could_not_be_resolved_when_respecting_package_json_exports_The_1_library_may_need_to_update_its_package_json_or_typings, - node10Result, - node10Result.includes(nodeModulesPathPart + "@types/") ? `@types/${mangleScopedPackageName(packageName)}` : packageName - ) : host.typesPackageExists(packageName) ? chainDiagnosticMessages( - /*details*/ - void 0, - Diagnostics.If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_1, - packageName, - mangleScopedPackageName(packageName) - ) : host.packageBundlesTypes(packageName) ? chainDiagnosticMessages( - /*details*/ - void 0, - Diagnostics.If_the_0_package_actually_exposes_this_module_try_adding_a_new_declaration_d_ts_file_containing_declare_module_1, - packageName, - moduleReference - ) : chainDiagnosticMessages( - /*details*/ - void 0, - Diagnostics.Try_npm_i_save_dev_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, + const result = node10Result ? chainDiagnosticMessages( /*details*/ + void 0, Diagnostics.There_are_types_at_0_but_this_result_could_not_be_resolved_when_respecting_package_json_exports_The_1_library_may_need_to_update_its_package_json_or_typings, node10Result, node10Result.includes(nodeModulesPathPart + "@types/") ? `@types/${mangleScopedPackageName(packageName)}` : packageName) : host.typesPackageExists(packageName) ? chainDiagnosticMessages( /*details*/ + void 0, Diagnostics.If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_1, packageName, mangleScopedPackageName(packageName)) : host.packageBundlesTypes(packageName) ? chainDiagnosticMessages( /*details*/ + void 0, Diagnostics.If_the_0_package_actually_exposes_this_module_try_adding_a_new_declaration_d_ts_file_containing_declare_module_1, packageName, moduleReference) : chainDiagnosticMessages( /*details*/ + void 0, Diagnostics.Try_npm_i_save_dev_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, moduleReference, mangleScopedPackageName(packageName)); + if (result) result.repopulateInfo = () => ({ moduleReference, - mangleScopedPackageName(packageName) - ); - if (result) - result.repopulateInfo = () => ({ moduleReference, mode, packageName: packageName === moduleReference ? void 0 : packageName }); + mode, + packageName: packageName === moduleReference ? void 0 : packageName + }); return result; } function packageIdIsEqual(a, b) { return a === b || !!a && !!b && a.name === b.name && a.subModuleName === b.subModuleName && a.version === b.version; } - function packageIdToPackageName({ name, subModuleName }) { + function packageIdToPackageName({ + name, + subModuleName + }) { return subModuleName ? `${name}/${subModuleName}` : name; } function packageIdToString(packageId) { @@ -13076,9 +12787,11 @@ ${lanes.join("\n")} if (thisNodeOrAnySubNodesHasError) { node.flags |= 1048576 /* ThisNodeOrAnySubNodesHasError */; } + node.flags |= 2097152 /* HasAggregatedChildData */; } } + function getSourceFileOfNode(node) { while (node && node.kind !== 312 /* SourceFile */) { node = node.parent; @@ -13137,42 +12850,30 @@ ${lanes.join("\n")} } return node.pos === node.end && node.pos >= 0 && node.kind !== 1 /* EndOfFileToken */; } + 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])) { @@ -13183,8 +12884,7 @@ ${lanes.join("\n")} 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])) { @@ -13197,6 +12897,7 @@ ${lanes.join("\n")} function isAnyPrologueDirective(node) { return isPrologueDirective(node) || !!(getEmitFlags(node) & 2097152 /* CustomPrologue */); } + function insertStatementsAfterStandardPrologue(to, from) { return insertStatementsAfterPrologue(to, from, isPrologueDirective); } @@ -13219,15 +12920,14 @@ ${lanes.join("\n")} function isPinnedComment(text, start) { return text.charCodeAt(start + 1) === 42 /* asterisk */ && text.charCodeAt(start + 2) === 33 /* exclamation */; } + function createCommentDirectivesMap(sourceFile, commentDirectives) { - const directivesByLine = new Map( - commentDirectives.map((commentDirective) => [ - `${getLineAndCharacterOfPosition(sourceFile, commentDirective.range.end).line}`, - commentDirective - ]) - ); - const usedLines = /* @__PURE__ */ new Map(); - return { getUnusedExpectations, markUsed }; + const directivesByLine = new Map(commentDirectives.map(commentDirective => [`${getLineAndCharacterOfPosition(sourceFile, commentDirective.range.end).line}`, commentDirective])); + const usedLines = /* @__PURE__ */new Map(); + return { + getUnusedExpectations, + markUsed + }; function getUnusedExpectations() { return arrayFrom(directivesByLine.entries()).filter(([line, directive]) => directive.type === 0 /* ExpectError */ && !usedLines.get(line)).map(([_, directive]) => directive); } @@ -13244,14 +12944,9 @@ ${lanes.join("\n")} return node.pos; } if (isJSDocNode(node) || node.kind === 12 /* JsxText */) { - return skipTrivia( - (sourceFile || getSourceFileOfNode(node)).text, - node.pos, - /*stopAfterLineBreak*/ - false, - /*stopAtComments*/ - true - ); + return skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos, /*stopAfterLineBreak*/ + false, /*stopAtComments*/ + true); } if (includeJsDoc && hasJSDocNodes(node)) { return getTokenPosOfNode(node.jsDoc[0], sourceFile); @@ -13259,15 +12954,9 @@ ${lanes.join("\n")} if (node.kind === 358 /* SyntaxList */ && node._children.length > 0) { return getTokenPosOfNode(node._children[0], sourceFile, includeJsDoc); } - return skipTrivia( - (sourceFile || getSourceFileOfNode(node)).text, - node.pos, - /*stopAfterLineBreak*/ - false, - /*stopAtComments*/ - false, - isInJSDoc(node) - ); + return skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos, /*stopAfterLineBreak*/ + false, /*stopAtComments*/ + false, isInJSDoc(node)); } function getNonDecoratorTokenPosOfNode(node, sourceFile) { const lastDecorator = !nodeIsMissing(node) && canHaveModifiers(node) ? findLast(node.modifiers, isDecorator) : void 0; @@ -13291,7 +12980,7 @@ ${lanes.join("\n")} } let text = sourceText.substring(includeTrivia ? node.pos : skipTrivia(sourceText, node.pos), node.end); if (isJSDocTypeExpressionOrChild(node)) { - text = text.split(/\r\n|\n|\r/).map((line) => line.replace(/^\s*\*/, "").trimStart()).join("\n"); + text = text.split(/\r\n|\n|\r/).map(line => line.replace(/^\s*\*/, "").trimStart()).join("\n"); } return text; } @@ -13317,32 +13006,35 @@ ${lanes.join("\n")} return getSourceTextOfNodeFromSourceFile(sourceFile, node); } switch (node.kind) { - case 11 /* StringLiteral */: { - const escapeText = flags & 2 /* JsxAttributeEscape */ ? escapeJsxAttributeString : flags & 1 /* NeverAsciiEscape */ || getEmitFlags(node) & 16777216 /* NoAsciiEscaping */ ? escapeString : escapeNonAsciiString; - if (node.singleQuote) { - return "'" + escapeText(node.text, 39 /* singleQuote */) + "'"; - } else { - return '"' + escapeText(node.text, 34 /* doubleQuote */) + '"'; + case 11 /* StringLiteral */: + { + const escapeText = flags & 2 /* JsxAttributeEscape */ ? escapeJsxAttributeString : flags & 1 /* NeverAsciiEscape */ || getEmitFlags(node) & 16777216 /* NoAsciiEscaping */ ? escapeString : escapeNonAsciiString; + if (node.singleQuote) { + return "'" + escapeText(node.text, 39 /* singleQuote */) + "'"; + } else { + return '"' + escapeText(node.text, 34 /* doubleQuote */) + '"'; + } } - } case 15 /* NoSubstitutionTemplateLiteral */: case 16 /* TemplateHead */: case 17 /* TemplateMiddle */: - case 18 /* TemplateTail */: { - const escapeText = flags & 1 /* NeverAsciiEscape */ || getEmitFlags(node) & 16777216 /* NoAsciiEscaping */ ? escapeString : escapeNonAsciiString; - const rawText = node.rawText ?? escapeTemplateSubstitution(escapeText(node.text, 96 /* backtick */)); - switch (node.kind) { - case 15 /* NoSubstitutionTemplateLiteral */: - return "`" + rawText + "`"; - case 16 /* TemplateHead */: - return "`" + rawText + "${"; - case 17 /* TemplateMiddle */: - return "}" + rawText + "${"; - case 18 /* TemplateTail */: - return "}" + rawText + "`"; + case 18 /* TemplateTail */: + { + var _node$rawText; + const escapeText = flags & 1 /* NeverAsciiEscape */ || getEmitFlags(node) & 16777216 /* NoAsciiEscaping */ ? escapeString : escapeNonAsciiString; + const rawText = (_node$rawText = node.rawText) !== null && _node$rawText !== void 0 ? _node$rawText : escapeTemplateSubstitution(escapeText(node.text, 96 /* backtick */)); + switch (node.kind) { + case 15 /* NoSubstitutionTemplateLiteral */: + return "`" + rawText + "`"; + case 16 /* TemplateHead */: + return "`" + rawText + "${"; + case 17 /* TemplateMiddle */: + return "}" + rawText + "${"; + case 18 /* TemplateTail */: + return "}" + rawText + "`"; + } + break; } - break; - } case 9 /* NumericLiteral */: case 10 /* BigIntLiteral */: return node.text; @@ -13366,6 +13058,7 @@ ${lanes.join("\n")} return !!(flags & 8 /* AllowNumericSeparator */); } } + return !isBigIntLiteral(node); } function getTextOfConstantValue(value) { @@ -13381,12 +13074,14 @@ ${lanes.join("\n")} const node = getRootDeclaration(declaration); return node.kind === 260 /* VariableDeclaration */ && node.parent.kind === 299 /* CatchClause */; } + function isAmbientModule(node) { return isModuleDeclaration(node) && (node.name.kind === 11 /* StringLiteral */ || isGlobalScopeAugmentation(node)); } function isModuleWithStringLiteralName(node) { return isModuleDeclaration(node) && node.name.kind === 11 /* StringLiteral */; } + function isNonGlobalAmbientModule(node) { return isModuleDeclaration(node) && isStringLiteral(node.name); } @@ -13405,6 +13100,7 @@ ${lanes.join("\n")} function isGlobalScopeAugmentation(module2) { return !!(module2.flags & 2048 /* GlobalAugmentation */); } + function isExternalModuleAugmentation(node) { return isAmbientModule(node) && isModuleAugmentationExternal(node); } @@ -13419,11 +13115,12 @@ ${lanes.join("\n")} } function getNonAugmentationDeclaration(symbol) { var _a; - return (_a = symbol.declarations) == null ? void 0 : _a.find((d) => !isExternalModuleAugmentation(d) && !(isModuleDeclaration(d) && isGlobalScopeAugmentation(d))); + return (_a = symbol.declarations) == null ? void 0 : _a.find(d => !isExternalModuleAugmentation(d) && !(isModuleDeclaration(d) && isGlobalScopeAugmentation(d))); } function isCommonJSContainingModuleKind(kind) { return kind === 1 /* CommonJS */ || kind === 100 /* Node16 */ || kind === 199 /* NodeNext */; } + function isEffectiveExternalModule(node, compilerOptions) { return isExternalModule(node) || isCommonJSContainingModuleKind(getEmitModuleKind(compilerOptions)) && !!node.commonJsModuleIndicator; } @@ -13457,6 +13154,7 @@ ${lanes.join("\n")} function isAmbientPropertyDeclaration(node) { return !!(node.flags & 33554432 /* Ambient */) || hasSyntacticModifier(node, 128 /* Ambient */); } + function isBlockScope(node, parentNode) { switch (node.kind) { case 312 /* SourceFile */: @@ -13556,10 +13254,11 @@ ${lanes.join("\n")} return isAnyImportSyntax(node) || isExportDeclaration(node); } function getEnclosingContainer(node) { - return findAncestor(node.parent, (n) => !!(getContainerFlags(n) & 1 /* IsContainer */)); + return findAncestor(node.parent, n => !!(getContainerFlags(n) & 1 /* IsContainer */)); } + function getEnclosingBlockScopeContainer(node) { - return findAncestor(node.parent, (current) => isBlockScope(current, current.parent)); + return findAncestor(node.parent, current => isBlockScope(current, current.parent)); } function forEachEnclosingBlockScopeContainer(node, cb) { let container = getEnclosingBlockScopeContainer(node); @@ -13588,8 +13287,7 @@ ${lanes.join("\n")} 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); @@ -13691,39 +13389,29 @@ ${lanes.join("\n")} }; } function getSpanOfTokenAtPosition(sourceFile, pos) { - const scanner2 = createScanner( - sourceFile.languageVersion, - /*skipTrivia*/ - true, - sourceFile.languageVariant, - sourceFile.text, - /*onError*/ - void 0, - pos - ); + const scanner2 = createScanner(sourceFile.languageVersion, /*skipTrivia*/ + true, sourceFile.languageVariant, sourceFile.text, /*onError*/ + void 0, pos); scanner2.scan(); const start = scanner2.getTokenStart(); return createTextSpanFromBounds(start, scanner2.getTokenEnd()); } function scanTokenAtPosition(sourceFile, pos) { - const scanner2 = createScanner( - sourceFile.languageVersion, - /*skipTrivia*/ - true, - sourceFile.languageVariant, - sourceFile.text, - /*onError*/ - void 0, - pos - ); + const scanner2 = createScanner(sourceFile.languageVersion, /*skipTrivia*/ + true, sourceFile.languageVariant, sourceFile.text, /*onError*/ + void 0, pos); scanner2.scan(); return scanner2.getToken(); } function getErrorSpanForArrowFunction(sourceFile, node) { const pos = skipTrivia(sourceFile.text, node.pos); if (node.body && node.body.kind === 241 /* Block */) { - const { line: startLine } = getLineAndCharacterOfPosition(sourceFile, node.body.pos); - const { line: endLine } = getLineAndCharacterOfPosition(sourceFile, node.body.end); + const { + line: startLine + } = getLineAndCharacterOfPosition(sourceFile, node.body.pos); + const { + line: endLine + } = getLineAndCharacterOfPosition(sourceFile, node.body.end); if (startLine < endLine) { return createTextSpan(pos, getEndLinePosition(startLine, sourceFile) - pos + 1); } @@ -13733,18 +13421,15 @@ ${lanes.join("\n")} function getErrorSpanForNode(sourceFile, node) { let errorNode = node; switch (node.kind) { - case 312 /* SourceFile */: { - const pos2 = skipTrivia( - sourceFile.text, - 0, - /*stopAfterLineBreak*/ - false - ); - if (pos2 === sourceFile.text.length) { - return createTextSpan(0, 0); + case 312 /* SourceFile */: + { + const pos2 = skipTrivia(sourceFile.text, 0, /*stopAfterLineBreak*/ + false); + if (pos2 === sourceFile.text.length) { + return createTextSpan(0, 0); + } + return getSpanOfTokenAtPosition(sourceFile, pos2); } - return getSpanOfTokenAtPosition(sourceFile, pos2); - } case 260 /* VariableDeclaration */: case 208 /* BindingElement */: case 263 /* ClassDeclaration */: @@ -13767,24 +13452,28 @@ ${lanes.join("\n")} case 219 /* ArrowFunction */: return getErrorSpanForArrowFunction(sourceFile, node); case 296 /* CaseClause */: - case 297 /* DefaultClause */: { - const start = skipTrivia(sourceFile.text, node.pos); - const end = node.statements.length > 0 ? node.statements[0].pos : node.end; - return createTextSpanFromBounds(start, end); - } + case 297 /* DefaultClause */: + { + const start = skipTrivia(sourceFile.text, node.pos); + const end = node.statements.length > 0 ? node.statements[0].pos : node.end; + return createTextSpanFromBounds(start, end); + } case 253 /* ReturnStatement */: - case 229 /* YieldExpression */: { - const pos2 = skipTrivia(sourceFile.text, node.pos); - return getSpanOfTokenAtPosition(sourceFile, pos2); - } - case 238 /* SatisfiesExpression */: { - const pos2 = skipTrivia(sourceFile.text, node.expression.end); - return getSpanOfTokenAtPosition(sourceFile, pos2); - } - case 357 /* JSDocSatisfiesTag */: { - const pos2 = skipTrivia(sourceFile.text, node.tagName.pos); - return getSpanOfTokenAtPosition(sourceFile, pos2); - } + case 229 /* YieldExpression */: + { + const pos2 = skipTrivia(sourceFile.text, node.pos); + return getSpanOfTokenAtPosition(sourceFile, pos2); + } + case 238 /* SatisfiesExpression */: + { + const pos2 = skipTrivia(sourceFile.text, node.expression.end); + return getSpanOfTokenAtPosition(sourceFile, pos2); + } + case 357 /* JSDocSatisfiesTag */: + { + const pos2 = skipTrivia(sourceFile.text, node.tagName.pos); + return getSpanOfTokenAtPosition(sourceFile, pos2); + } } if (errorNode === void 0) { return getSpanOfTokenAtPosition(sourceFile, node.pos); @@ -13807,30 +13496,38 @@ ${lanes.join("\n")} function isJsonSourceFile(file) { return file.scriptKind === 6 /* JSON */; } + function isEnumConst(node) { return !!(getCombinedModifierFlags(node) & 4096 /* Const */); } + function isDeclarationReadonly(declaration) { return !!(getCombinedModifierFlags(declaration) & 8 /* Readonly */ && !isParameterPropertyDeclaration(declaration, declaration.parent)); } function isVarAwaitUsing(node) { return (getCombinedNodeFlags(node) & 7 /* BlockScoped */) === 6 /* AwaitUsing */; } + function isVarUsing(node) { return (getCombinedNodeFlags(node) & 7 /* BlockScoped */) === 4 /* Using */; } + function isVarConst(node) { return (getCombinedNodeFlags(node) & 7 /* BlockScoped */) === 2 /* Const */; } + function isLet(node) { return (getCombinedNodeFlags(node) & 7 /* BlockScoped */) === 1 /* Let */; } + function isSuperCall(n) { return n.kind === 213 /* CallExpression */ && n.expression.kind === 108 /* SuperKeyword */; } + function isImportCall(n) { return n.kind === 213 /* CallExpression */ && n.expression.kind === 102 /* ImportKeyword */; } + function isImportMeta(n) { return isMetaProperty(n) && n.keywordToken === 102 /* ImportKeyword */ && n.name.escapedText === "meta"; } @@ -13840,9 +13537,11 @@ ${lanes.join("\n")} function isPrologueDirective(node) { return node.kind === 244 /* ExpressionStatement */ && node.expression.kind === 11 /* StringLiteral */; } + function isCustomPrologue(node) { return !!(getEmitFlags(node) & 2097152 /* CustomPrologue */); } + function isHoistedFunction(node) { return isCustomPrologue(node) && isFunctionDeclaration(node); } @@ -13857,8 +13556,9 @@ ${lanes.join("\n")} } 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 => text.charCodeAt(comment.pos + 1) === 42 /* asterisk */ && text.charCodeAt(comment.pos + 2) === 42 /* asterisk */ && text.charCodeAt(comment.pos + 3) !== 47 /* slash */); } + function isPartOfTypeNode(node) { if (182 /* FirstTypeNode */ <= node.kind && node.kind <= 205 /* LastTypeNode */) { return true; @@ -13891,50 +13591,53 @@ ${lanes.join("\n")} Debug.assert(node.kind === 80 /* Identifier */ || node.kind === 166 /* QualifiedName */ || node.kind === 211 /* PropertyAccessExpression */, "'node' was expected to be a qualified name, identifier or property access in 'isPartOfTypeNode'."); case 166 /* QualifiedName */: case 211 /* PropertyAccessExpression */: - case 110 /* ThisKeyword */: { - const { parent: parent2 } = node; - if (parent2.kind === 186 /* TypeQuery */) { - return false; + case 110 /* ThisKeyword */: + { + const { + parent: parent2 + } = node; + if (parent2.kind === 186 /* TypeQuery */) { + return false; + } + if (parent2.kind === 205 /* ImportType */) { + return !parent2.isTypeOf; + } + if (182 /* FirstTypeNode */ <= parent2.kind && parent2.kind <= 205 /* LastTypeNode */) { + return true; + } + switch (parent2.kind) { + case 233 /* ExpressionWithTypeArguments */: + return isHeritageClause(parent2.parent) && !isExpressionWithTypeArgumentsInClassExtendsClause(parent2); + case 168 /* TypeParameter */: + return node === parent2.constraint; + case 352 /* JSDocTemplateTag */: + return node === parent2.constraint; + case 172 /* PropertyDeclaration */: + case 171 /* PropertySignature */: + case 169 /* Parameter */: + case 260 /* VariableDeclaration */: + return node === parent2.type; + case 262 /* FunctionDeclaration */: + case 218 /* FunctionExpression */: + case 219 /* ArrowFunction */: + case 176 /* Constructor */: + case 174 /* MethodDeclaration */: + case 173 /* MethodSignature */: + case 177 /* GetAccessor */: + case 178 /* SetAccessor */: + return node === parent2.type; + case 179 /* CallSignature */: + case 180 /* ConstructSignature */: + case 181 /* IndexSignature */: + return node === parent2.type; + case 216 /* TypeAssertionExpression */: + return node === parent2.type; + case 213 /* CallExpression */: + case 214 /* NewExpression */: + case 215 /* TaggedTemplateExpression */: + return contains(parent2.typeArguments, node); + } } - if (parent2.kind === 205 /* ImportType */) { - return !parent2.isTypeOf; - } - if (182 /* FirstTypeNode */ <= parent2.kind && parent2.kind <= 205 /* LastTypeNode */) { - return true; - } - switch (parent2.kind) { - case 233 /* ExpressionWithTypeArguments */: - return isHeritageClause(parent2.parent) && !isExpressionWithTypeArgumentsInClassExtendsClause(parent2); - case 168 /* TypeParameter */: - return node === parent2.constraint; - case 352 /* JSDocTemplateTag */: - return node === parent2.constraint; - case 172 /* PropertyDeclaration */: - case 171 /* PropertySignature */: - case 169 /* Parameter */: - case 260 /* VariableDeclaration */: - return node === parent2.type; - case 262 /* FunctionDeclaration */: - case 218 /* FunctionExpression */: - case 219 /* ArrowFunction */: - case 176 /* Constructor */: - case 174 /* MethodDeclaration */: - case 173 /* MethodSignature */: - case 177 /* GetAccessor */: - case 178 /* SetAccessor */: - return node === parent2.type; - case 179 /* CallSignature */: - case 180 /* ConstructSignature */: - case 181 /* IndexSignature */: - return node === parent2.type; - case 216 /* TypeAssertionExpression */: - return node === parent2.type; - case 213 /* CallExpression */: - case 214 /* NewExpression */: - case 215 /* TaggedTemplateExpression */: - return contains(parent2.typeArguments, node); - } - } } return false; } @@ -14042,16 +13745,16 @@ ${lanes.join("\n")} 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) { return (isVariableDeclaration(node) ? isVarConst(node) && isIdentifier(node.name) && isVariableDeclarationInVariableStatement(node) : isPropertyDeclaration(node) ? hasEffectiveReadonlyModifier(node) && hasStaticModifier(node) : isPropertySignature(node) && hasEffectiveReadonlyModifier(node)) || isCommonJsExportPropertyAssignment(node); } @@ -14085,25 +13788,28 @@ ${lanes.join("\n")} function isObjectLiteralMethod(node) { return node && node.kind === 174 /* MethodDeclaration */ && node.parent.kind === 210 /* ObjectLiteralExpression */; } + function isObjectLiteralOrClassExpressionMethodOrAccessor(node) { return (node.kind === 174 /* MethodDeclaration */ || node.kind === 177 /* GetAccessor */ || node.kind === 178 /* SetAccessor */) && (node.parent.kind === 210 /* ObjectLiteralExpression */ || node.parent.kind === 231 /* ClassExpression */); } + function isIdentifierTypePredicate(predicate) { return predicate && predicate.kind === 1 /* Identifier */; } + function isThisTypePredicate(predicate) { return predicate && predicate.kind === 0 /* This */; } + function forEachPropertyAssignment(objectLiteral, key, callback, key2) { - return forEach(objectLiteral == null ? void 0 : objectLiteral.properties, (property) => { - if (!isPropertyAssignment(property)) - return void 0; + return forEach(objectLiteral == null ? void 0 : objectLiteral.properties, property => { + if (!isPropertyAssignment(property)) return void 0; const propName = tryGetTextOfPropertyName(property.name); return key === propName || key2 && key2 === propName ? callback(property) : void 0; }); } function getPropertyArrayElementValue(objectLiteral, propKey, elementValue) { - return forEachPropertyAssignment(objectLiteral, propKey, (property) => isArrayLiteralExpression(property.initializer) ? find(property.initializer.elements, (element) => isStringLiteral(element) && element.text === elementValue) : void 0); + return forEachPropertyAssignment(objectLiteral, propKey, property => isArrayLiteralExpression(property.initializer) ? find(property.initializer.elements, element => isStringLiteral(element) && element.text === elementValue) : void 0); } function getTsConfigObjectLiteralExpression(tsConfigSourceFile) { if (tsConfigSourceFile && tsConfigSourceFile.statements.length) { @@ -14112,7 +13818,7 @@ ${lanes.join("\n")} } } function getTsConfigPropArrayElementValue(tsConfigSourceFile, propKey, elementValue) { - return forEachTsConfigPropArray(tsConfigSourceFile, propKey, (property) => isArrayLiteralExpression(property.initializer) ? find(property.initializer.elements, (element) => isStringLiteral(element) && element.text === elementValue) : void 0); + return forEachTsConfigPropArray(tsConfigSourceFile, propKey, property => isArrayLiteralExpression(property.initializer) ? find(property.initializer.elements, element => isStringLiteral(element) && element.text === elementValue) : void 0); } function forEachTsConfigPropArray(tsConfigSourceFile, propKey, callback) { return forEachPropertyAssignment(getTsConfigObjectLiteralExpression(tsConfigSourceFile), propKey, callback); @@ -14127,7 +13833,7 @@ ${lanes.join("\n")} return findAncestor(node.parent, isClassLike); } function getContainingClassStaticBlock(node) { - return findAncestor(node.parent, (n) => { + return findAncestor(node.parent, n => { if (isClassLike(n) || isFunctionLike(n)) { return "quit"; } @@ -14138,8 +13844,8 @@ ${lanes.join("\n")} return findAncestor(node.parent, isFunctionLikeOrClassStaticBlockDeclaration); } function getContainingClassExcludingClassDecorators(node) { - const decorator = findAncestor(node.parent, (n) => isClassLike(n) ? "quit" : isDecorator(n)); - return decorator && isClassLike(decorator.parent) ? getContainingClass(decorator.parent) : getContainingClass(decorator ?? node); + const decorator = findAncestor(node.parent, n => isClassLike(n) ? "quit" : isDecorator(n)); + return decorator && isClassLike(decorator.parent) ? getContainingClass(decorator.parent) : getContainingClass(decorator !== null && decorator !== void 0 ? decorator : node); } function getThisContainer(node, includeArrowFunctions, includeClassComputedPropertyName) { Debug.assert(node.kind !== 312 /* SourceFile */); @@ -14211,23 +13917,15 @@ ${lanes.join("\n")} if (isIdentifier(node) && (isClassDeclaration(node.parent) || isFunctionDeclaration(node.parent)) && node.parent.name === node) { node = node.parent; } - const container = getThisContainer( - node, - /*includeArrowFunctions*/ - true, - /*includeClassComputedPropertyName*/ - false - ); + const container = getThisContainer(node, /*includeArrowFunctions*/ + true, /*includeClassComputedPropertyName*/ + false); return isSourceFile(container); } function getNewTargetContainer(node) { - const container = getThisContainer( - node, - /*includeArrowFunctions*/ - false, - /*includeClassComputedPropertyName*/ - false - ); + const container = getThisContainer(node, /*includeArrowFunctions*/ + false, /*includeClassComputedPropertyName*/ + false); if (container) { switch (container.kind) { case 176 /* Constructor */: @@ -14293,17 +13991,21 @@ ${lanes.join("\n")} const kind = node.kind; return (kind === 211 /* PropertyAccessExpression */ || kind === 212 /* ElementAccessExpression */) && node.expression.kind === 108 /* SuperKeyword */; } + function isThisProperty(node) { const kind = node.kind; return (kind === 211 /* PropertyAccessExpression */ || kind === 212 /* ElementAccessExpression */) && node.expression.kind === 110 /* ThisKeyword */; } + function isThisInitializedDeclaration(node) { var _a; return !!node && isVariableDeclaration(node) && ((_a = node.initializer) == null ? void 0 : _a.kind) === 110 /* ThisKeyword */; } + function isThisInitializedObjectBindingExpression(node) { return !!node && (isShorthandPropertyAssignment(node) || isPropertyAssignment(node)) && isBinaryExpression(node.parent.parent) && node.parent.parent.operatorToken.kind === 64 /* EqualsToken */ && node.parent.parent.right.kind === 110 /* ThisKeyword */; } + function getEntityNameFromTypeNode(node) { switch (node.kind) { case 183 /* TypeReference */: @@ -14345,10 +14047,10 @@ ${lanes.join("\n")} 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; } function nodeIsDecorated(useLegacyDecorators, node, parent2, grandparent) { @@ -14360,27 +14062,30 @@ ${lanes.join("\n")} function childIsDecorated(useLegacyDecorators, node, parent2) { switch (node.kind) { case 263 /* ClassDeclaration */: - return some(node.members, (m) => nodeOrChildIsDecorated(useLegacyDecorators, m, node, parent2)); + return some(node.members, m => nodeOrChildIsDecorated(useLegacyDecorators, m, node, parent2)); case 231 /* ClassExpression */: - return !useLegacyDecorators && some(node.members, (m) => nodeOrChildIsDecorated(useLegacyDecorators, m, node, parent2)); + return !useLegacyDecorators && some(node.members, m => nodeOrChildIsDecorated(useLegacyDecorators, m, node, parent2)); case 174 /* MethodDeclaration */: case 178 /* SetAccessor */: case 176 /* Constructor */: - return some(node.parameters, (p) => nodeIsDecorated(useLegacyDecorators, p, node, parent2)); + return some(node.parameters, p => nodeIsDecorated(useLegacyDecorators, p, node, parent2)); default: return false; } } 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); } function classElementOrClassElementParameterIsDecorated(useLegacyDecorators, node, parent2) { let parameters; if (isAccessor(node)) { - const { firstAccessor, secondAccessor, setAccessor } = getAllAccessorDeclarations(parent2.members, node); + const { + firstAccessor, + secondAccessor, + setAccessor + } = getAllAccessorDeclarations(parent2.members, node); const firstAccessorWithDecorators = hasDecorators(firstAccessor) ? firstAccessor : secondAccessor && hasDecorators(secondAccessor) ? secondAccessor : void 0; if (!firstAccessorWithDecorators || node !== firstAccessorWithDecorators) { return false; @@ -14394,10 +14099,8 @@ ${lanes.join("\n")} } 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; @@ -14415,7 +14118,9 @@ ${lanes.join("\n")} return node.text === ""; } function isJSXTagName(node) { - const { parent: parent2 } = node; + const { + parent: parent2 + } = node; if (parent2.kind === 286 /* JsxOpeningElement */ || parent2.kind === 285 /* JsxSelfClosingElement */ || parent2.kind === 287 /* JsxClosingElement */) { return parent2.tagName === node; } @@ -14489,7 +14194,9 @@ ${lanes.join("\n")} } } function isInExpressionContext(node) { - const { parent: parent2 } = node; + const { + parent: parent2 + } = node; switch (parent2.kind) { case 260 /* VariableDeclaration */: case 169 /* Parameter */: @@ -14544,12 +14251,14 @@ ${lanes.join("\n")} } return node.kind === 186 /* TypeQuery */; } + function isNamespaceReexportDeclaration(node) { return isNamespaceExport(node) && !!node.parent.moduleSpecifier; } function isExternalModuleImportEqualsDeclaration(node) { return node.kind === 271 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 283 /* ExternalModuleReference */; } + function getExternalModuleImportEqualsDeclarationExpression(node) { Debug.assert(isExternalModuleImportEqualsDeclaration(node)); return node.moduleReference.expression; @@ -14560,6 +14269,7 @@ ${lanes.join("\n")} function isInternalModuleImportEqualsDeclaration(node) { return node.kind === 271 /* ImportEqualsDeclaration */ && node.moduleReference.kind !== 283 /* ExternalModuleReference */; } + function isSourceFileJS(file) { return isInJSFile(file); } @@ -14569,23 +14279,30 @@ ${lanes.join("\n")} function isInJSFile(node) { return !!node && !!(node.flags & 524288 /* JavaScriptFile */); } + function isInJsonFile(node) { return !!node && !!(node.flags & 134217728 /* JsonFile */); } + function isSourceFileNotJson(file) { return !isJsonSourceFile(file); } function isInJSDoc(node) { return !!node && !!(node.flags & 16777216 /* JSDoc */); } + function isJSDocIndexSignature(node) { return isTypeReferenceNode(node) && isIdentifier(node.typeName) && node.typeName.escapedText === "Object" && node.typeArguments && node.typeArguments.length === 2 && (node.typeArguments[0].kind === 154 /* StringKeyword */ || node.typeArguments[0].kind === 150 /* NumberKeyword */); } + function isRequireCall(callExpression, requireStringLiteralLikeArgument) { if (callExpression.kind !== 213 /* CallExpression */) { return false; } - const { expression, arguments: args } = callExpression; + const { + expression, + arguments: args + } = callExpression; if (expression.kind !== 80 /* Identifier */ || expression.escapedText !== "require") { return false; } @@ -14596,38 +14313,31 @@ ${lanes.join("\n")} return !requireStringLiteralLikeArgument || isStringLiteralLike(arg); } function isVariableDeclarationInitializedToRequire(node) { - return isVariableDeclarationInitializedWithRequireHelper( - node, - /*allowAccessedRequire*/ - false - ); + return isVariableDeclarationInitializedWithRequireHelper(node, /*allowAccessedRequire*/ + false); } function isVariableDeclarationInitializedToBareOrAccessedRequire(node) { - return isVariableDeclarationInitializedWithRequireHelper( - node, - /*allowAccessedRequire*/ - true - ); + return isVariableDeclarationInitializedWithRequireHelper(node, /*allowAccessedRequire*/ + true); } function isBindingElementOfBareOrAccessedRequire(node) { return isBindingElement(node) && isVariableDeclarationInitializedToBareOrAccessedRequire(node.parent.parent); } function isVariableDeclarationInitializedWithRequireHelper(node, allowAccessedRequire) { - return isVariableDeclaration(node) && !!node.initializer && isRequireCall( - allowAccessedRequire ? getLeftmostAccessExpression(node.initializer) : node.initializer, - /*requireStringLiteralLikeArgument*/ - true - ); + return isVariableDeclaration(node) && !!node.initializer && isRequireCall(allowAccessedRequire ? getLeftmostAccessExpression(node.initializer) : node.initializer, /*requireStringLiteralLikeArgument*/ + true); } function isRequireVariableStatement(node) { - return isVariableStatement(node) && node.declarationList.declarations.length > 0 && every(node.declarationList.declarations, (decl) => isVariableDeclarationInitializedToRequire(decl)); + return isVariableStatement(node) && node.declarationList.declarations.length > 0 && every(node.declarationList.declarations, decl => isVariableDeclarationInitializedToRequire(decl)); } function isSingleOrDoubleQuote(charCode) { return charCode === 39 /* singleQuote */ || charCode === 34 /* doubleQuote */; } + function isStringDoubleQuoted(str, sourceFile) { return getSourceTextOfNodeFromSourceFile(sourceFile, str).charCodeAt(0) === 34 /* doubleQuote */; } + function isAssignmentDeclaration(decl) { return isBinaryExpression(decl) || isAccessExpression(decl) || isIdentifier(decl) || isCallExpression(decl); } @@ -14642,7 +14352,7 @@ ${lanes.join("\n")} return init && getExpandoInitializer(init, isPrototypeAccess(node.name)); } function hasExpandoValueProperty(node, isPrototypeAssignment) { - return forEach(node.properties, (p) => isPropertyAssignment(p) && isIdentifier(p.name) && p.name.escapedText === "value" && p.initializer && getExpandoInitializer(p.initializer, isPrototypeAssignment)); + return forEach(node.properties, p => isPropertyAssignment(p) && isIdentifier(p.name) && p.name.escapedText === "value" && p.initializer && getExpandoInitializer(p.initializer, isPrototypeAssignment)); } function getAssignedExpandoInitializer(node) { if (node && node.parent && isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 64 /* EqualsToken */) { @@ -14701,11 +14411,8 @@ ${lanes.join("\n")} return false; } function getRightMostAssignedExpression(node) { - while (isAssignmentExpression( - node, - /*excludeCompoundAssignment*/ - true - )) { + while (isAssignmentExpression(node, /*excludeCompoundAssignment*/ + true)) { node = node.right; } return node; @@ -14723,12 +14430,10 @@ ${lanes.join("\n")} const special = getAssignmentDeclarationKindWorker(expr); return special === 5 /* Property */ || isInJSFile(expr) ? special : 0 /* None */; } + function isBindableObjectDefinePropertyCall(expr) { - return length(expr.arguments) === 3 && isPropertyAccessExpression(expr.expression) && isIdentifier(expr.expression.expression) && idText(expr.expression.expression) === "Object" && idText(expr.expression.name) === "defineProperty" && isStringOrNumericLiteralLike(expr.arguments[1]) && isBindableStaticNameExpression( - expr.arguments[0], - /*excludeThisKeyword*/ - true - ); + return length(expr.arguments) === 3 && isPropertyAccessExpression(expr.expression) && isIdentifier(expr.expression.expression) && idText(expr.expression.expression) === "Object" && idText(expr.expression.name) === "defineProperty" && isStringOrNumericLiteralLike(expr.arguments[1]) && isBindableStaticNameExpression(expr.arguments[0], /*excludeThisKeyword*/ + true); } function isLiteralLikeAccess(node) { return isPropertyAccessExpression(node) || isLiteralLikeElementAccess(node); @@ -14737,18 +14442,12 @@ ${lanes.join("\n")} return isElementAccessExpression(node) && isStringOrNumericLiteralLike(node.argumentExpression); } function isBindableStaticAccessExpression(node, excludeThisKeyword) { - return isPropertyAccessExpression(node) && (!excludeThisKeyword && node.expression.kind === 110 /* ThisKeyword */ || isIdentifier(node.name) && isBindableStaticNameExpression( - node.expression, - /*excludeThisKeyword*/ - true - )) || isBindableStaticElementAccessExpression(node, excludeThisKeyword); + return isPropertyAccessExpression(node) && (!excludeThisKeyword && node.expression.kind === 110 /* ThisKeyword */ || isIdentifier(node.name) && isBindableStaticNameExpression(node.expression, /*excludeThisKeyword*/ + true)) || isBindableStaticElementAccessExpression(node, excludeThisKeyword); } function isBindableStaticElementAccessExpression(node, excludeThisKeyword) { - return isLiteralLikeElementAccess(node) && (!excludeThisKeyword && node.expression.kind === 110 /* ThisKeyword */ || isEntityNameExpression(node.expression) || isBindableStaticAccessExpression( - node.expression, - /*excludeThisKeyword*/ - true - )); + return isLiteralLikeElementAccess(node) && (!excludeThisKeyword && node.expression.kind === 110 /* ThisKeyword */ || isEntityNameExpression(node.expression) || isBindableStaticAccessExpression(node.expression, /*excludeThisKeyword*/ + true)); } function isBindableStaticNameExpression(node, excludeThisKeyword) { return isEntityNameExpression(node) || isBindableStaticAccessExpression(node, excludeThisKeyword); @@ -14764,25 +14463,28 @@ ${lanes.join("\n")} if (!isBindableObjectDefinePropertyCall(expr)) { return 0 /* None */; } + const entityName = expr.arguments[0]; if (isExportsIdentifier(entityName) || isModuleExportsAccessExpression(entityName)) { return 8 /* ObjectDefinePropertyExports */; } + if (isBindableStaticAccessExpression(entityName) && getElementOrPropertyAccessName(entityName) === "prototype") { return 9 /* ObjectDefinePrototypeProperty */; } + return 7 /* ObjectDefinePropertyValue */; } + if (expr.operatorToken.kind !== 64 /* EqualsToken */ || !isAccessExpression(expr.left) || isVoidZero(getRightMostAssignedExpression(expr))) { return 0 /* None */; } - if (isBindableStaticNameExpression( - expr.left.expression, - /*excludeThisKeyword*/ - true - ) && getElementOrPropertyAccessName(expr.left) === "prototype" && isObjectLiteralExpression(getInitializerOfBinaryExpression(expr))) { + + if (isBindableStaticNameExpression(expr.left.expression, /*excludeThisKeyword*/ + true) && getElementOrPropertyAccessName(expr.left) === "prototype" && isObjectLiteralExpression(getInitializerOfBinaryExpression(expr))) { return 6 /* Prototype */; } + return getAssignmentDeclarationPropertyAccessKind(expr.left); } function isVoidZero(node) { @@ -14815,33 +14517,32 @@ ${lanes.join("\n")} return 4 /* ThisProperty */; } else if (isModuleExportsAccessExpression(lhs)) { return 2 /* ModuleExports */; - } else if (isBindableStaticNameExpression( - lhs.expression, - /*excludeThisKeyword*/ - true - )) { + } else if (isBindableStaticNameExpression(lhs.expression, /*excludeThisKeyword*/ + true)) { if (isPrototypeAccess(lhs.expression)) { return 3 /* PrototypeProperty */; } + let nextToLast = lhs; while (!isIdentifier(nextToLast.expression)) { nextToLast = nextToLast.expression; } const id = nextToLast.expression; - if ((id.escapedText === "exports" || id.escapedText === "module" && getElementOrPropertyAccessName(nextToLast) === "exports") && // ExportsProperty does not support binding with computed names + if ((id.escapedText === "exports" || id.escapedText === "module" && getElementOrPropertyAccessName(nextToLast) === "exports") && + // ExportsProperty does not support binding with computed names isBindableStaticAccessExpression(lhs)) { return 1 /* ExportsProperty */; } - if (isBindableStaticNameExpression( - lhs, - /*excludeThisKeyword*/ - true - ) || isElementAccessExpression(lhs) && isDynamicName(lhs)) { + + if (isBindableStaticNameExpression(lhs, /*excludeThisKeyword*/ + true) || isElementAccessExpression(lhs) && isDynamicName(lhs)) { return 5 /* Property */; } } + return 0 /* None */; } + function getInitializerOfBinaryExpression(expr) { while (isBinaryExpression(expr.right)) { expr = expr.right; @@ -14851,12 +14552,15 @@ ${lanes.join("\n")} function isPrototypePropertyAssignment(node) { return isBinaryExpression(node) && getAssignmentDeclarationKind(node) === 3 /* PrototypeProperty */; } + function isSpecialPropertyDeclaration(expr) { return isInJSFile(expr) && expr.parent && expr.parent.kind === 244 /* ExpressionStatement */ && (!isElementAccessExpression(expr) || isLiteralLikeElementAccess(expr)) && !!getJSDocTypeTag(expr.parent); } function setValueDeclaration(symbol, node) { - const { valueDeclaration } = symbol; - if (!valueDeclaration || !(node.flags & 33554432 /* Ambient */ && !isInJSFile(node) && !(valueDeclaration.flags & 33554432 /* Ambient */)) && (isAssignmentDeclaration(valueDeclaration) && !isAssignmentDeclaration(node)) || valueDeclaration.kind !== node.kind && isEffectiveModuleDeclaration(valueDeclaration)) { + const { + valueDeclaration + } = symbol; + if (!valueDeclaration || !(node.flags & 33554432 /* Ambient */ && !isInJSFile(node) && !(valueDeclaration.flags & 33554432 /* Ambient */)) && isAssignmentDeclaration(valueDeclaration) && !isAssignmentDeclaration(node) || valueDeclaration.kind !== node.kind && isEffectiveModuleDeclaration(valueDeclaration)) { symbol.valueDeclaration = node; } } @@ -14872,11 +14576,8 @@ ${lanes.join("\n")} switch (node.kind) { case 260 /* VariableDeclaration */: case 208 /* BindingElement */: - return (_a = findAncestor(node.initializer, (node2) => isRequireCall( - node2, - /*requireStringLiteralLikeArgument*/ - true - ))) == null ? void 0 : _a.arguments[0]; + return (_a = findAncestor(node.initializer, node2 => isRequireCall(node2, /*requireStringLiteralLikeArgument*/ + true))) == null ? void 0 : _a.arguments[0]; case 272 /* ImportDeclaration */: case 278 /* ExportDeclaration */: return tryCast(node.moduleSpecifier, isStringLiteralLike); @@ -14907,11 +14608,8 @@ ${lanes.join("\n")} case 283 /* ExternalModuleReference */: return node.parent.parent; case 213 /* CallExpression */: - return isImportCall(node.parent) || isRequireCall( - node.parent, - /*requireStringLiteralLikeArgument*/ - false - ) ? node.parent : void 0; + return isImportCall(node.parent) || isRequireCall(node.parent, /*requireStringLiteralLikeArgument*/ + false) ? node.parent : void 0; case 201 /* LiteralType */: Debug.assert(isStringLiteral(node)); return tryCast(node.parent.parent, isImportTypeNode); @@ -14954,13 +14652,11 @@ ${lanes.join("\n")} 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) { @@ -14986,6 +14682,7 @@ ${lanes.join("\n")} function isJSDocTypeAlias(node) { return node.kind === 353 /* JSDocTypedefTag */ || node.kind === 345 /* JSDocCallbackTag */ || node.kind === 347 /* JSDocEnumTag */; } + function isTypeAlias(node) { return isJSDocTypeAlias(node) || isTypeAliasDeclaration(node); } @@ -15132,7 +14829,7 @@ ${lanes.join("\n")} } function filterOwnedJSDocTags(hostNode, jsDoc) { if (isJSDoc(jsDoc)) { - const ownedTags = filter(jsDoc.tags, (tag) => ownsJSDocTag(hostNode, tag)); + const ownedTags = filter(jsDoc.tags, tag => ownsJSDocTag(hostNode, tag)); return jsDoc.tags === ownedTags ? [jsDoc] : ownedTags; } return ownsJSDocTag(hostNode, jsDoc) ? [jsDoc] : void 0; @@ -15162,7 +14859,7 @@ ${lanes.join("\n")} if (!decl) { return void 0; } - const parameter = find(decl.parameters, (p) => p.name.kind === 80 /* Identifier */ && p.name.escapedText === name); + const parameter = find(decl.parameters, p => p.name.kind === 80 /* Identifier */ && p.name.escapedText === name); return parameter && parameter.symbol; } function getEffectiveContainerForJSDocTemplateTag(node) { @@ -15202,8 +14899,10 @@ ${lanes.join("\n")} } function getTypeParameterFromJsDoc(node) { const name = node.name.escapedText; - const { typeParameters } = node.parent.parent.parent; - return typeParameters && find(typeParameters, (p) => p.name.escapedText === name); + const { + typeParameters + } = node.parent.parent.parent; + return typeParameters && find(typeParameters, p => p.name.escapedText === name); } function hasTypeArguments(node) { return !!node.typeArguments; @@ -15257,6 +14956,7 @@ ${lanes.join("\n")} if (!target) { return 0 /* None */; } + switch (target.kind) { case 226 /* BinaryExpression */: const binaryOperator = target.operatorToken.kind; @@ -15269,6 +14969,7 @@ ${lanes.join("\n")} return 1 /* Definite */; } } + function isAssignmentTarget(node) { return !!getAssignmentTarget(node); } @@ -15278,11 +14979,8 @@ ${lanes.join("\n")} } function isInCompoundLikeAssignment(node) { const target = getAssignmentTarget(node); - return !!target && isAssignmentExpression( - target, - /*excludeCompoundAssignment*/ - true - ) && isCompoundLikeAssignment(target); + return !!target && isAssignmentExpression(target, /*excludeCompoundAssignment*/ + true) && isCompoundLikeAssignment(target); } function isNodeWithPossibleHoistedDeclaration(node) { switch (node.kind) { @@ -15318,9 +15016,11 @@ ${lanes.join("\n")} function walkUpParenthesizedTypes(node) { return walkUp(node, 196 /* ParenthesizedType */); } + function walkUpParenthesizedExpressions(node) { return walkUp(node, 217 /* ParenthesizedExpression */); } + function walkUpParenthesizedTypesAndGetParentAndChild(node) { let child; while (node && node.kind === 196 /* ParenthesizedType */) { @@ -15330,8 +15030,7 @@ ${lanes.join("\n")} return [child, node]; } function skipTypeParentheses(node) { - while (isParenthesizedTypeNode(node)) - node = node.type; + while (isParenthesizedTypeNode(node)) node = node.type; return node; } function skipParentheses(node, excludeJSDocTypeAssertions) { @@ -15345,10 +15044,10 @@ ${lanes.join("\n")} node = walkUpParenthesizedExpressions(node.parent); return node && node.kind === 220 /* DeleteExpression */; } + function isNodeDescendantOf(node, ancestor) { while (node) { - if (node === ancestor) - return true; + if (node === ancestor) return true; node = node.parent; } return false; @@ -15362,8 +15061,7 @@ ${lanes.join("\n")} 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; @@ -15462,7 +15160,7 @@ ${lanes.join("\n")} } function getEffectiveImplementsTypeNodes(node) { if (isInJSFile(node)) { - return getJSDocImplementsTags(node).map((n) => n.class); + return getJSDocImplementsTags(node).map(n => n.class); } else { const heritageClause = getHeritageClause(node.heritageClauses, 119 /* ImplementsKeyword */); return heritageClause == null ? void 0 : heritageClause.types; @@ -15497,21 +15195,25 @@ ${lanes.join("\n")} function isKeyword(token) { return 83 /* FirstKeyword */ <= token && token <= 165 /* LastKeyword */; } + function isPunctuation(token) { return 19 /* FirstPunctuation */ <= token && token <= 79 /* LastPunctuation */; } + function isKeywordOrPunctuation(token) { return isKeyword(token) || isPunctuation(token); } function isContextualKeyword(token) { return 128 /* FirstContextualKeyword */ <= token && token <= 165 /* LastContextualKeyword */; } + function isNonContextualKeyword(token) { return isKeyword(token) && !isContextualKeyword(token); } function isFutureReservedKeyword(token) { return 119 /* FirstFutureReservedWord */ <= token && token <= 127 /* LastFutureReservedWord */; } + function isStringANonContextualKeyword(name) { const token = stringToToken(name); return token !== void 0 && isNonContextualKeyword(token); @@ -15527,10 +15229,12 @@ ${lanes.join("\n")} function isTrivia(token) { return 2 /* FirstTriviaToken */ <= token && token <= 7 /* LastTriviaToken */; } + function getFunctionFlags(node) { if (!node) { return 4 /* Invalid */; } + let flags = 0 /* Normal */; switch (node.kind) { case 262 /* FunctionDeclaration */: @@ -15539,15 +15243,18 @@ ${lanes.join("\n")} if (node.asteriskToken) { flags |= 1 /* Generator */; } + case 219 /* ArrowFunction */: if (hasSyntacticModifier(node, 1024 /* Async */)) { flags |= 2 /* Async */; } + break; } if (!node.body) { flags |= 4 /* Invalid */; } + return flags; } function isAsyncFunction(node) { @@ -15558,6 +15265,7 @@ ${lanes.join("\n")} case 174 /* MethodDeclaration */: return node.body !== void 0 && node.asteriskToken === void 0 && hasSyntacticModifier(node, 1024 /* Async */); } + return false; } function isStringOrNumericLiteralLike(node) { @@ -15687,8 +15395,7 @@ ${lanes.join("\n")} 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); @@ -15712,6 +15419,7 @@ ${lanes.join("\n")} const root = getRootDeclaration(node); return root.kind === 169 /* Parameter */; } + function getRootDeclaration(node) { while (node.kind === 208 /* BindingElement */) { node = node.parent.parent; @@ -15722,6 +15430,7 @@ ${lanes.join("\n")} const kind = node.kind; return kind === 176 /* Constructor */ || kind === 218 /* FunctionExpression */ || kind === 262 /* FunctionDeclaration */ || kind === 219 /* ArrowFunction */ || kind === 174 /* MethodDeclaration */ || kind === 177 /* GetAccessor */ || kind === 178 /* SetAccessor */ || kind === 267 /* ModuleDeclaration */ || kind === 312 /* SourceFile */; } + function nodeIsSynthesized(range) { return positionIsSynthesized(range.pos) || positionIsSynthesized(range.end); } @@ -15767,8 +15476,10 @@ ${lanes.join("\n")} return 1 /* Right */; } } + return 0 /* Left */; } + function getExpressionPrecedence(expression) { const operator = getOperator(expression); const hasArguments = expression.kind === 214 /* NewExpression */ && expression.arguments !== void 0; @@ -15867,6 +15578,7 @@ ${lanes.join("\n")} return -1 /* Invalid */; } } + function getBinaryOperatorPrecedence(kind) { switch (kind) { case 61 /* QuestionQuestionToken */: @@ -15909,10 +15621,11 @@ ${lanes.join("\n")} case 43 /* AsteriskAsteriskToken */: return 15 /* Exponentiation */; } + return -1; } function getSemanticJsxChildren(children) { - return filter(children, (i) => { + return filter(children, i => { switch (i.kind) { case 294 /* JsxExpression */: return !!i.expression; @@ -15926,7 +15639,7 @@ ${lanes.join("\n")} function createDiagnosticCollection() { let nonFileDiagnostics = []; const filesWithDiagnostics = []; - const fileDiagnostics = /* @__PURE__ */ new Map(); + const fileDiagnostics = /* @__PURE__ */new Map(); let hasReadNonFileDiagnostics = false; return { add, @@ -15976,7 +15689,7 @@ ${lanes.join("\n")} if (fileName) { return fileDiagnostics.get(fileName) || []; } - const fileDiags = flatMapToMutable(filesWithDiagnostics, (f) => fileDiagnostics.get(f)); + const fileDiags = flatMapToMutable(filesWithDiagnostics, f => fileDiagnostics.get(f)); if (!nonFileDiagnostics.length) { return fileDiags; } @@ -15990,8 +15703,9 @@ ${lanes.join("\n")} function containsInvalidEscapeFlag(node) { return !!((node.templateFlags || 0) & 2048 /* ContainsInvalidEscape */); } + function hasInvalidEscape(template) { - return template && !!(isNoSubstitutionTemplateLiteral(template) ? containsInvalidEscapeFlag(template) : containsInvalidEscapeFlag(template.head) || some(template.templateSpans, (span) => containsInvalidEscapeFlag(span.literal))); + return template && !!(isNoSubstitutionTemplateLiteral(template) ? containsInvalidEscapeFlag(template) : containsInvalidEscapeFlag(template.head) || some(template.templateSpans, span => containsInvalidEscapeFlag(span.literal))); } function encodeUtf16EscapeSequence(charCode) { const hexCharCode = charCode.toString(16).toUpperCase(); @@ -16014,7 +15728,7 @@ ${lanes.join("\n")} } function escapeNonAsciiString(s, quoteChar) { s = escapeString(s, quoteChar); - return nonAsciiCharacters.test(s) ? s.replace(nonAsciiCharacters, (c) => encodeUtf16EscapeSequence(c.charCodeAt(0))) : s; + return nonAsciiCharacters.test(s) ? s.replace(nonAsciiCharacters, c => encodeUtf16EscapeSequence(c.charCodeAt(0))) : s; } function encodeJsxCharacterEntity(charCode) { const hexCharCode = charCode.toString(16).toUpperCase(); @@ -16040,6 +15754,7 @@ ${lanes.join("\n")} function isQuoteOrBacktick(charCode) { return charCode === 39 /* singleQuote */ || charCode === 34 /* doubleQuote */ || charCode === 96 /* backtick */; } + function isIntrinsicJsxName(name) { const ch = name.charCodeAt(0); return ch >= 97 /* a */ && ch <= 122 /* z */ || name.includes("-"); @@ -16082,13 +15797,11 @@ ${lanes.join("\n")} } } 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() { @@ -16248,17 +15961,11 @@ ${lanes.join("\n")} return getResolvedExternalModuleName(host, file); } function getExternalModuleNameFromPath(host, fileName, referencePath) { - const getCanonicalFileName = (f) => host.getCanonicalFileName(f); + const getCanonicalFileName = f => host.getCanonicalFileName(f); const dir = toPath(referencePath ? getDirectoryPath(referencePath) : host.getCommonSourceDirectory(), host.getCurrentDirectory(), getCanonicalFileName); const filePath = getNormalizedAbsolutePath(fileName, host.getCurrentDirectory()); - const relativePath = getRelativePathToDirectoryOrUrl( - dir, - filePath, - dir, - getCanonicalFileName, - /*isAbsolutePathAnUrl*/ - false - ); + const relativePath = getRelativePathToDirectoryOrUrl(dir, filePath, dir, getCanonicalFileName, /*isAbsolutePathAnUrl*/ + false); const extensionless = removeFileExtension(relativePath); return referencePath ? ensurePathIsNonModuleName(extensionless) : extensionless; } @@ -16273,7 +15980,7 @@ ${lanes.join("\n")} return emitOutputFilePathWithoutExtension + extension; } function getDeclarationEmitOutputFilePath(fileName, host) { - return getDeclarationEmitOutputFilePathWorker(fileName, host.getCompilerOptions(), host.getCurrentDirectory(), host.getCommonSourceDirectory(), (f) => host.getCanonicalFileName(f)); + return getDeclarationEmitOutputFilePathWorker(fileName, host.getCompilerOptions(), host.getCurrentDirectory(), host.getCommonSourceDirectory(), f => host.getCanonicalFileName(f)); } function getDeclarationEmitOutputFilePathWorker(fileName, options, currentDirectory, commonSourceDirectory, getCanonicalFileName) { const outputDir = options.declarationDir || options.outDir; @@ -16282,70 +15989,55 @@ ${lanes.join("\n")} return removeFileExtension(path) + declarationExtension; } function getDeclarationEmitExtensionForPath(path) { - return fileExtensionIsOneOf(path, [".mjs" /* Mjs */, ".mts" /* Mts */]) ? ".d.mts" /* Dmts */ : fileExtensionIsOneOf(path, [".cjs" /* Cjs */, ".cts" /* Cts */]) ? ".d.cts" /* Dcts */ : fileExtensionIsOneOf(path, [".json" /* Json */]) ? `.d.json.ts` : ( - // Drive-by redefinition of json declaration file output name so if it's ever enabled, it behaves well - ".d.ts" /* Dts */ - ); + return fileExtensionIsOneOf(path, [".mjs" /* Mjs */, ".mts" /* Mts */]) ? ".d.mts" /* Dmts */ : fileExtensionIsOneOf(path, [".cjs" /* Cjs */, ".cts" /* Cts */]) ? ".d.cts" /* Dcts */ : fileExtensionIsOneOf(path, [".json" /* Json */]) ? `.d.json.ts` : + // Drive-by redefinition of json declaration file output name so if it's ever enabled, it behaves well + ".d.ts" /* Dts */; } + function getPossibleOriginalInputExtensionForExtension(path) { return fileExtensionIsOneOf(path, [".d.mts" /* Dmts */, ".mjs" /* Mjs */, ".mts" /* Mts */]) ? [".mts" /* Mts */, ".mjs" /* Mjs */] : fileExtensionIsOneOf(path, [".d.cts" /* Dcts */, ".cjs" /* Cjs */, ".cts" /* Cts */]) ? [".cts" /* Cts */, ".cjs" /* Cjs */] : fileExtensionIsOneOf(path, [`.d.json.ts`]) ? [".json" /* Json */] : [".tsx" /* Tsx */, ".ts" /* Ts */, ".jsx" /* Jsx */, ".js" /* Js */]; } + function outFile(options) { return options.outFile || options.out; } function getPathsBasePath(options, host) { + var _options$baseUrl; var _a; - 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'."); + if (!options.paths) return void 0; + return (_options$baseUrl = options.baseUrl) !== null && _options$baseUrl !== void 0 ? _options$baseUrl : Debug.checkDefined(options.pathsBasePath || ((_a = host.getCurrentDirectory) == null ? void 0 : _a.call(host)), "Encountered 'paths' without a 'baseUrl', config file, or host 'getCurrentDirectory'."); } function getSourceFilesToEmit(host, targetSourceFile, forceDtsEmit) { const options = host.getCompilerOptions(); if (outFile(options)) { const moduleKind = getEmitModuleKind(options); const moduleEmitEnabled = options.emitDeclarationOnly || moduleKind === 2 /* AMD */ || moduleKind === 4 /* System */; - return filter( - host.getSourceFiles(), - (sourceFile) => (moduleEmitEnabled || !isExternalModule(sourceFile)) && sourceFileMayBeEmitted(sourceFile, host, forceDtsEmit) - ); + return filter(host.getSourceFiles(), sourceFile => (moduleEmitEnabled || !isExternalModule(sourceFile)) && sourceFileMayBeEmitted(sourceFile, host, forceDtsEmit)); } else { const sourceFiles = targetSourceFile === void 0 ? host.getSourceFiles() : [targetSourceFile]; - return filter( - sourceFiles, - (sourceFile) => sourceFileMayBeEmitted(sourceFile, host, forceDtsEmit) - ); + return filter(sourceFiles, sourceFile => sourceFileMayBeEmitted(sourceFile, host, 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 (outFile(options)) - 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 (outFile(options)) 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; } function getSourceFilePathInNewDir(fileName, host, newDirPath) { - return getSourceFilePathInNewDirWorker(fileName, newDirPath, host.getCurrentDirectory(), host.getCommonSourceDirectory(), (f) => host.getCanonicalFileName(f)); + return getSourceFilePathInNewDirWorker(fileName, newDirPath, host.getCurrentDirectory(), host.getCommonSourceDirectory(), f => host.getCanonicalFileName(f)); } function getSourceFilePathInNewDirWorker(fileName, newDirPath, currentDirectory, commonSourceDirectory, getCanonicalFileName) { let sourceFilePath = getNormalizedAbsolutePath(fileName, currentDirectory); @@ -16354,16 +16046,9 @@ ${lanes.join("\n")} return combinePaths(newDirPath, sourceFilePath); } function writeFile(host, diagnostics, fileName, text, writeByteOrderMark, sourceFiles, data) { - host.writeFile( - fileName, - text, - writeByteOrderMark, - (hostErrorMessage) => { - diagnostics.add(createCompilerDiagnostic(Diagnostics.Could_not_write_file_0_Colon_1, fileName, hostErrorMessage)); - }, - sourceFiles, - data - ); + host.writeFile(fileName, text, writeByteOrderMark, hostErrorMessage => { + diagnostics.add(createCompilerDiagnostic(Diagnostics.Could_not_write_file_0_Colon_1, fileName, hostErrorMessage)); + }, sourceFiles, data); } function ensureDirectoriesExist(directoryPath, createDirectory, directoryExists) { if (directoryPath.length > getRootLength(directoryPath) && !directoryExists(directoryPath)) { @@ -16388,7 +16073,7 @@ ${lanes.join("\n")} return computeLineOfPosition(lineMap, pos); } function getFirstConstructorWithBody(node) { - return find(node.members, (member) => isConstructorDeclaration(member) && nodeIsPresent(member.body)); + return find(node.members, member => isConstructorDeclaration(member) && nodeIsPresent(member.body)); } function getSetAccessorValueParameter(accessor) { if (accessor && accessor.parameters.length > 0) { @@ -16415,10 +16100,7 @@ ${lanes.join("\n")} return !!node && node.kind === 80 /* Identifier */ && identifierIsThisKeyword(node); } function isInTypeQuery(node) { - return !!findAncestor( - node, - (n) => n.kind === 186 /* TypeQuery */ ? true : n.kind === 80 /* Identifier */ || n.kind === 166 /* QualifiedName */ ? false : "quit" - ); + return !!findAncestor(node, n => n.kind === 186 /* TypeQuery */ ? true : n.kind === 80 /* Identifier */ || n.kind === 166 /* QualifiedName */ ? false : "quit"); } function isThisInTypeQuery(node) { if (!isThisIdentifier(node)) { @@ -16429,6 +16111,7 @@ ${lanes.join("\n")} } return node.parent.kind === 186 /* TypeQuery */; } + function identifierIsThisKeyword(id) { return id.escapedText === "this"; } @@ -16447,7 +16130,7 @@ ${lanes.join("\n")} Debug.fail("Accessor has wrong kind"); } } else { - forEach(declarations, (member) => { + forEach(declarations, member => { if (isAccessor(member) && isStatic(member) === isStatic(accessor)) { const memberName = getPropertyNameForPropertyNameNode(member.name); const accessorName = getPropertyNameForPropertyNameNode(accessor.name); @@ -16475,11 +16158,9 @@ ${lanes.join("\n")} }; } function getEffectiveTypeAnnotationNode(node) { - if (!isInJSFile(node) && isFunctionDeclaration(node)) - return void 0; + if (!isInJSFile(node) && isFunctionDeclaration(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) { @@ -16489,7 +16170,7 @@ ${lanes.join("\n")} return isJSDocSignature(node) ? node.type && node.type.typeExpression && node.type.typeExpression.type : node.type || (isInJSFile(node) ? getJSDocReturnType(node) : void 0); } function getJSDocTypeParameterDeclarations(node) { - return flatMap(getJSDocTags(node), (tag) => isNonTypeAliasTemplate(tag) ? tag.typeParameters : void 0); + return flatMap(getJSDocTags(node), tag => isNonTypeAliasTemplate(tag) ? tag.typeParameters : void 0); } function isNonTypeAliasTemplate(tag) { return isJSDocTemplateTag(tag) && !(tag.parent.kind === 327 /* JSDoc */ && (tag.parent.tags.some(isJSDocTypeAlias) || tag.parent.tags.some(isJSDocOverloadTag))); @@ -16563,19 +16244,13 @@ ${lanes.join("\n")} const nodeLine = getLineOfLocalPositionFromLineMap(lineMap, skipTrivia(text, node.pos)); if (nodeLine >= lastCommentLine + 2) { emitNewLineBeforeLeadingComments(lineMap, writer, node, leadingComments); - emitComments( - text, - lineMap, - writer, - detachedComments, - /*leadingSeparator*/ - false, - /*trailingSeparator*/ - true, - newLine, - writeComment - ); - currentDetachedCommentInfo = { nodePos: node.pos, detachedCommentEndPos: last(detachedComments).end }; + emitComments(text, lineMap, writer, detachedComments, /*leadingSeparator*/ + false, /*trailingSeparator*/ + true, newLine, writeComment); + currentDetachedCommentInfo = { + nodePos: node.pos, + detachedCommentEndPos: last(detachedComments).end + }; } } } @@ -16642,9 +16317,11 @@ ${lanes.join("\n")} function hasEffectiveModifiers(node) { return getEffectiveModifierFlags(node) !== 0 /* None */; } + function hasSyntacticModifiers(node) { return getSyntacticModifierFlags(node) !== 0 /* None */; } + function hasEffectiveModifier(node, flags) { return !!getSelectedEffectiveModifierFlags(node, flags); } @@ -16657,24 +16334,31 @@ ${lanes.join("\n")} function hasStaticModifier(node) { return hasSyntacticModifier(node, 256 /* Static */); } + function hasOverrideModifier(node) { return hasEffectiveModifier(node, 16 /* Override */); } + function hasAbstractModifier(node) { return hasSyntacticModifier(node, 64 /* Abstract */); } + function hasAmbientModifier(node) { return hasSyntacticModifier(node, 128 /* Ambient */); } + function hasAccessorModifier(node) { return hasSyntacticModifier(node, 512 /* Accessor */); } + function hasEffectiveReadonlyModifier(node) { return hasEffectiveModifier(node, 8 /* Readonly */); } + function hasDecorators(node) { return hasSyntacticModifier(node, 32768 /* Decorator */); } + function getSelectedEffectiveModifierFlags(node, flags) { return getEffectiveModifierFlags(node) & flags; } @@ -16685,63 +16369,53 @@ ${lanes.join("\n")} if (node.kind >= 0 /* FirstToken */ && node.kind <= 165 /* LastToken */) { return 0 /* None */; } + if (!(node.modifierFlagsCache & 536870912 /* HasComputedFlags */)) { node.modifierFlagsCache = getSyntacticModifierFlagsNoCache(node) | 536870912 /* HasComputedFlags */; } + if (alwaysIncludeJSDoc || includeJSDoc && isInJSFile(node)) { if (!(node.modifierFlagsCache & 268435456 /* HasComputedJSDocModifiers */) && node.parent) { node.modifierFlagsCache |= getRawJSDocModifierFlagsNoCache(node) | 268435456 /* HasComputedJSDocModifiers */; } + return selectEffectiveModifierFlags(node.modifierFlagsCache); } return selectSyntacticModifierFlags(node.modifierFlagsCache); } function getEffectiveModifierFlags(node) { - return getModifierFlagsWorker( - node, - /*includeJSDoc*/ - true - ); + return getModifierFlagsWorker(node, /*includeJSDoc*/ + true); } function getEffectiveModifierFlagsAlwaysIncludeJSDoc(node) { - return getModifierFlagsWorker( - node, - /*includeJSDoc*/ - true, - /*alwaysIncludeJSDoc*/ - true - ); + return getModifierFlagsWorker(node, /*includeJSDoc*/ + true, /*alwaysIncludeJSDoc*/ + true); } function getSyntacticModifierFlags(node) { - return getModifierFlagsWorker( - node, - /*includeJSDoc*/ - false - ); + return getModifierFlagsWorker(node, /*includeJSDoc*/ + false); } 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 (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 (getJSDocDeprecatedTagNoCache(node)) flags |= 65536 /* Deprecated */; } + return flags; } function selectSyntacticModifierFlags(flags) { return flags & 65535 /* SyntacticModifiers */; } + function selectEffectiveModifierFlags(flags) { return flags & 131071 /* NonCacheOnlyModifiers */ | (flags & 260046848 /* JSDocCacheOnlyModifiers */) >>> 23; } @@ -16756,6 +16430,7 @@ ${lanes.join("\n")} if (node.flags & 8 /* NestedNamespace */ || node.kind === 80 /* Identifier */ && node.flags & 4096 /* IdentifierIsInJSDocNamespace */) { flags |= 32 /* Export */; } + return flags; } function modifiersToFlags(modifiers) { @@ -16802,29 +16477,36 @@ ${lanes.join("\n")} case 170 /* Decorator */: return 32768 /* Decorator */; } + return 0 /* None */; } + function isBinaryLogicalOperator(token) { return token === 57 /* BarBarToken */ || token === 56 /* AmpersandAmpersandToken */; } + function isLogicalOperator(token) { return isBinaryLogicalOperator(token) || token === 54 /* ExclamationToken */; } + function isLogicalOrCoalescingAssignmentOperator(token) { return token === 76 /* BarBarEqualsToken */ || token === 77 /* AmpersandAmpersandEqualsToken */ || token === 78 /* QuestionQuestionEqualsToken */; } + function isLogicalOrCoalescingAssignmentExpression(expr) { return isBinaryExpression(expr) && isLogicalOrCoalescingAssignmentOperator(expr.operatorToken.kind); } function isLogicalOrCoalescingBinaryOperator(token) { return isBinaryLogicalOperator(token) || token === 61 /* QuestionQuestionToken */; } + function isLogicalOrCoalescingBinaryExpression(expr) { return isBinaryExpression(expr) && isLogicalOrCoalescingBinaryOperator(expr.operatorToken.kind); } function isAssignmentOperator(token) { return token >= 64 /* FirstAssignment */ && token <= 79 /* LastAssignment */; } + function tryGetClassExtendingExpressionWithTypeArguments(node) { const cls = tryGetClassImplementingOrExtendingExpressionWithTypeArguments(node); return cls && !cls.isImplements ? cls.class : void 0; @@ -16832,12 +16514,19 @@ ${lanes.join("\n")} function tryGetClassImplementingOrExtendingExpressionWithTypeArguments(node) { if (isExpressionWithTypeArguments(node)) { if (isHeritageClause(node.parent) && isClassLike(node.parent.parent)) { - return { class: node.parent.parent, isImplements: node.parent.token === 119 /* ImplementsKeyword */ }; + return { + class: node.parent.parent, + isImplements: node.parent.token === 119 /* ImplementsKeyword */ + }; } + if (isJSDocAugmentsTag(node.parent)) { const host = getEffectiveJSDocHost(node.parent); if (host && isClassLike(host)) { - return { class: host, isImplements: false }; + return { + class: host, + isImplements: false + }; } } } @@ -16850,14 +16539,12 @@ ${lanes.join("\n")} return isAssignmentExpression(node.parent) && node.parent.left === node; } function isDestructuringAssignment(node) { - if (isAssignmentExpression( - node, - /*excludeCompoundAssignment*/ - true - )) { + if (isAssignmentExpression(node, /*excludeCompoundAssignment*/ + true)) { const kind = node.left.kind; return kind === 210 /* ObjectLiteralExpression */ || kind === 209 /* ArrayLiteralExpression */; } + return false; } function isExpressionWithTypeArgumentsInClassExtendsClause(node) { @@ -16921,6 +16608,7 @@ ${lanes.join("\n")} function isInstanceOfExpression(node) { return isBinaryExpression(node) && node.operatorToken.kind === 104 /* InstanceOfKeyword */; } + function isRightSideOfInstanceofExpression(node) { return isInstanceOfExpression(node.parent) && node === node.parent.right; } @@ -16931,19 +16619,18 @@ ${lanes.join("\n")} 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; } function isExportDefaultSymbol(symbol) { return symbol && length(symbol.declarations) > 0 && hasSyntacticModifier(symbol.declarations[0], 2048 /* Default */); } + function tryExtractTSExtension(fileName) { - return find(supportedTSExtensionsForExtractExtension, (extension) => fileExtensionIs(fileName, extension)); + return find(supportedTSExtensionsForExtractExtension, extension => fileExtensionIs(fileName, extension)); } function getExpandedCharCodes(input) { const output = []; @@ -17054,8 +16741,7 @@ ${lanes.join("\n")} } 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; } @@ -17076,7 +16762,10 @@ ${lanes.join("\n")} } function createRange(pos, end = pos) { Debug.assert(end >= pos || end === -1); - return { pos, end }; + return { + pos, + end + }; } function moveRangeEnd(range, end) { return createRange(range.pos, end); @@ -17105,40 +16794,20 @@ ${lanes.join("\n")} return rangeStartIsOnSameLineAsRangeEnd(range, range, sourceFile); } function rangeStartPositionsAreOnSameLine(range1, range2, sourceFile) { - return positionsAreOnSameLine( - getStartPositionOfRange( - range1, - sourceFile, - /*includeComments*/ - false - ), - getStartPositionOfRange( - range2, - sourceFile, - /*includeComments*/ - false - ), - sourceFile - ); + return positionsAreOnSameLine(getStartPositionOfRange(range1, sourceFile, /*includeComments*/ + false), getStartPositionOfRange(range2, sourceFile, /*includeComments*/ + false), sourceFile); } function rangeEndPositionsAreOnSameLine(range1, range2, sourceFile) { return positionsAreOnSameLine(range1.end, range2.end, sourceFile); } function rangeStartIsOnSameLineAsRangeEnd(range1, range2, sourceFile) { - return positionsAreOnSameLine(getStartPositionOfRange( - range1, - sourceFile, - /*includeComments*/ - false - ), range2.end, sourceFile); + return positionsAreOnSameLine(getStartPositionOfRange(range1, sourceFile, /*includeComments*/ + false), range2.end, sourceFile); } function rangeEndIsOnSameLineAsRangeStart(range1, range2, sourceFile) { - return positionsAreOnSameLine(range1.end, getStartPositionOfRange( - range2, - sourceFile, - /*includeComments*/ - false - ), sourceFile); + return positionsAreOnSameLine(range1.end, getStartPositionOfRange(range2, sourceFile, /*includeComments*/ + false), sourceFile); } function getLinesBetweenRangeEndAndRangeStart(range1, range2, sourceFile, includeSecondRangeComments) { const range2Start = getStartPositionOfRange(range2, sourceFile, includeSecondRangeComments); @@ -17154,33 +16823,18 @@ ${lanes.join("\n")} return getLinesBetweenPositions(sourceFile, pos1, pos2) === 0; } function getStartPositionOfRange(range, sourceFile, includeComments) { - return positionIsSynthesized(range.pos) ? -1 : skipTrivia( - sourceFile.text, - range.pos, - /*stopAfterLineBreak*/ - false, - includeComments - ); + return positionIsSynthesized(range.pos) ? -1 : skipTrivia(sourceFile.text, range.pos, /*stopAfterLineBreak*/ + false, includeComments); } function getLinesBetweenPositionAndPrecedingNonWhitespaceCharacter(pos, stopPos, sourceFile, includeComments) { - const startPos = skipTrivia( - sourceFile.text, - pos, - /*stopAfterLineBreak*/ - false, - includeComments - ); + const startPos = skipTrivia(sourceFile.text, pos, /*stopAfterLineBreak*/ + false, includeComments); const prevPos = getPreviousNonWhitespacePosition(startPos, stopPos, sourceFile); - return getLinesBetweenPositions(sourceFile, prevPos ?? stopPos, startPos); + return getLinesBetweenPositions(sourceFile, prevPos !== null && prevPos !== void 0 ? prevPos : stopPos, startPos); } function getLinesBetweenPositionAndNextNonWhitespaceCharacter(pos, stopPos, sourceFile, includeComments) { - const nextPos = skipTrivia( - sourceFile.text, - pos, - /*stopAfterLineBreak*/ - false, - includeComments - ); + const nextPos = skipTrivia(sourceFile.text, pos, /*stopAfterLineBreak*/ + false, includeComments); return getLinesBetweenPositions(sourceFile, pos, Math.min(stopPos, nextPos)); } function getPreviousNonWhitespacePosition(pos, stopPos = 0, sourceFile) { @@ -17222,6 +16876,7 @@ ${lanes.join("\n")} const flags = getCombinedModifierFlags(declaration); return s.parent && s.parent.flags & 32 /* Class */ ? flags : flags & ~7 /* AccessibilityModifier */; } + if (getCheckFlags(s) & 6 /* Synthetic */) { const checkFlags = s.links.checkFlags; const accessModifier = checkFlags & 1024 /* ContainsPrivate */ ? 2 /* Private */ : checkFlags & 256 /* ContainsPublic */ ? 1 /* Public */ : 4 /* Protected */; @@ -17231,6 +16886,7 @@ ${lanes.join("\n")} if (s.flags & 4194304 /* Prototype */) { return 1 /* Public */ | 256 /* Static */; } + return 0; } function skipAlias(symbol, checker) { @@ -17242,27 +16898,37 @@ ${lanes.join("\n")} function isWriteOnlyAccess(node) { return accessKind(node) === 1 /* Write */; } + function isWriteAccess(node) { return accessKind(node) !== 0 /* Read */; } + function accessKind(node) { - const { parent: parent2 } = node; + const { + parent: parent2 + } = node; switch (parent2 == null ? void 0 : parent2.kind) { case 217 /* ParenthesizedExpression */: return accessKind(parent2); case 225 /* PostfixUnaryExpression */: case 224 /* PrefixUnaryExpression */: - const { operator } = parent2; + const { + operator + } = parent2; return operator === 46 /* PlusPlusToken */ || operator === 47 /* MinusMinusToken */ ? 2 /* ReadWrite */ : 0 /* Read */; case 226 /* BinaryExpression */: - const { left, operatorToken } = parent2; + const { + left, + operatorToken + } = parent2; return left === node && isAssignmentOperator(operatorToken.kind) ? operatorToken.kind === 64 /* EqualsToken */ ? 1 /* Write */ : 2 /* ReadWrite */ : 0 /* Read */; case 211 /* PropertyAccessExpression */: return parent2.name !== node ? 0 /* Read */ : accessKind(parent2); - case 303 /* PropertyAssignment */: { - const parentAccess = accessKind(parent2.parent); - return node === parent2.name ? reverseAccessKind(parentAccess) : parentAccess; - } + case 303 /* PropertyAssignment */: + { + const parentAccess = accessKind(parent2.parent); + return node === parent2.name ? reverseAccessKind(parentAccess) : parentAccess; + } case 304 /* ShorthandPropertyAssignment */: return node === parent2.objectAssignmentInitializer ? 0 /* Read */ : accessKind(parent2.parent); case 209 /* ArrayLiteralExpression */: @@ -17271,6 +16937,7 @@ ${lanes.join("\n")} return 0 /* Read */; } } + function reverseAccessKind(a) { switch (a) { case 0 /* Read */: @@ -17305,7 +16972,10 @@ ${lanes.join("\n")} map2.clear(); } function mutateMapSkippingNewValues(map2, newMap, options) { - const { onDeleteValue, onExistingValue } = options; + const { + onDeleteValue, + onExistingValue + } = options; map2.forEach((existingValue, key) => { const valueInNewMap = newMap.get(key); if (valueInNewMap === void 0) { @@ -17318,7 +16988,9 @@ ${lanes.join("\n")} } function mutateMap(map2, newMap, options) { mutateMapSkippingNewValues(map2, newMap, options); - const { createNewValue } = options; + const { + createNewValue + } = options; newMap.forEach((valueInNewMap, key) => { if (!map2.has(key)) { map2.set(key, createNewValue(key, valueInNewMap)); @@ -17330,6 +17002,7 @@ ${lanes.join("\n")} const declaration = getClassLikeDeclarationOfSymbol(symbol); return !!declaration && hasSyntacticModifier(declaration, 64 /* Abstract */); } + return false; } function getClassLikeDeclarationOfSymbol(symbol) { @@ -17340,20 +17013,21 @@ ${lanes.join("\n")} return type.flags & 3899393 /* ObjectFlagsType */ ? type.objectFlags : 0; } function forSomeAncestorDirectory(directory, callback) { - return !!forEachAncestorDirectory(directory, (d) => callback(d) ? true : void 0); + return !!forEachAncestorDirectory(directory, d => callback(d) ? true : void 0); } function isUMDExportSymbol(symbol) { return !!symbol && !!symbol.declarations && !!symbol.declarations[0] && isNamespaceExportDeclaration(symbol.declarations[0]); } - function showModuleSpecifier({ moduleSpecifier }) { + function showModuleSpecifier({ + moduleSpecifier + }) { return isStringLiteral(moduleSpecifier) ? moduleSpecifier.text : getTextOfNode(moduleSpecifier); } function getLastChild(node) { let lastChild; - forEachChild(node, (child) => { - if (nodeIsPresent(child)) - lastChild = child; - }, (children) => { + forEachChild(node, child => { + if (nodeIsPresent(child)) lastChild = child; + }, children => { for (let i = children.length - 1; i >= 0; i--) { if (nodeIsPresent(children[i])) { lastChild = children[i]; @@ -17376,9 +17050,11 @@ ${lanes.join("\n")} function isTypeNodeKind(kind) { return kind >= 182 /* FirstTypeNode */ && kind <= 205 /* LastTypeNode */ || kind === 133 /* AnyKeyword */ || kind === 159 /* UnknownKeyword */ || kind === 150 /* NumberKeyword */ || kind === 163 /* BigIntKeyword */ || kind === 151 /* ObjectKeyword */ || kind === 136 /* BooleanKeyword */ || kind === 154 /* StringKeyword */ || kind === 155 /* SymbolKeyword */ || kind === 116 /* VoidKeyword */ || kind === 157 /* UndefinedKeyword */ || kind === 146 /* NeverKeyword */ || kind === 141 /* IntrinsicKeyword */ || kind === 233 /* ExpressionWithTypeArguments */ || kind === 319 /* JSDocAllType */ || kind === 320 /* JSDocUnknownType */ || kind === 321 /* JSDocNullableType */ || kind === 322 /* JSDocNonNullableType */ || kind === 323 /* JSDocOptionalType */ || kind === 324 /* JSDocFunctionType */ || kind === 325 /* JSDocVariadicType */; } + function isAccessExpression(node) { return node.kind === 211 /* PropertyAccessExpression */ || node.kind === 212 /* ElementAccessExpression */; } + function getNameOfAccessExpression(node) { if (node.kind === 211 /* PropertyAccessExpression */) { return node.name; @@ -17398,6 +17074,7 @@ ${lanes.join("\n")} function isNamedImportsOrExports(node) { return node.kind === 275 /* NamedImports */ || node.kind === 279 /* NamedExports */; } + function getLeftmostAccessExpression(expr) { while (isAccessExpression(expr)) { expr = expr.expression; @@ -17528,7 +17205,7 @@ ${lanes.join("\n")} function SourceMapSource(fileName, text, skipTrivia2) { this.fileName = fileName; this.text = text; - this.skipTrivia = skipTrivia2 || ((pos) => pos); + this.skipTrivia = skipTrivia2 || (pos => pos); } function addObjectAllocatorPatcher(fn) { objectAllocatorPatchers.push(fn); @@ -17536,7 +17213,7 @@ ${lanes.join("\n")} } function setObjectAllocator(alloc) { Object.assign(objectAllocator, alloc); - forEach(objectAllocatorPatchers, (fn) => fn(objectAllocator)); + forEach(objectAllocatorPatchers, fn => fn(objectAllocator)); } function formatStringFromArgs(text, args) { return text.replace(/{(\d+)}/g, (_match, index) => "" + Debug.checkDefined(args[+index])); @@ -17687,21 +17364,26 @@ ${lanes.join("\n")} 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 */; } + 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) => { 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); @@ -17710,6 +17392,7 @@ ${lanes.join("\n")} } else if (typeof t2 === "string") { return 1 /* GreaterThan */; } + let res = compareStringsCaseSensitive(t1.messageText, t2.messageText); if (res) { return res; @@ -17717,12 +17400,15 @@ ${lanes.join("\n")} if (!t1.next && !t2.next) { return 0 /* EqualTo */; } + if (!t1.next) { return -1 /* LessThan */; } + if (!t2.next) { 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]); @@ -17735,14 +17421,16 @@ ${lanes.join("\n")} } else if (t1.next.length > t2.next.length) { return 1 /* GreaterThan */; } + return 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) { @@ -17754,11 +17442,11 @@ ${lanes.join("\n")} function getSetExternalModuleIndicator(options) { switch (getEmitModuleDetectionKind(options)) { case 3 /* Force */: - return (file) => { + return file => { file.externalModuleIndicator = isFileProbablyExternalModule(file) || !file.isDeclarationFile || void 0; }; case 1 /* Legacy */: - return (file) => { + return file => { file.externalModuleIndicator = isFileProbablyExternalModule(file); }; case 2 /* Auto */: @@ -17768,19 +17456,23 @@ ${lanes.join("\n")} } checks.push(isFileForcedToBeModuleByFormat); const combined = or(...checks); - const callback = (file) => void (file.externalModuleIndicator = combined(file)); + const callback = file => void (file.externalModuleIndicator = combined(file)); return callback; } } function getEmitScriptTarget(compilerOptions) { - return compilerOptions.target ?? (compilerOptions.module === 100 /* Node16 */ && 9 /* ES2022 */ || compilerOptions.module === 199 /* NodeNext */ && 99 /* ESNext */ || 1 /* ES5 */); + var _compilerOptions$targ; + return (_compilerOptions$targ = compilerOptions.target) !== null && _compilerOptions$targ !== void 0 ? _compilerOptions$targ : compilerOptions.module === 100 /* Node16 */ && 9 /* ES2022 */ || compilerOptions.module === 199 /* NodeNext */ && 99 /* ESNext */ || 1 /* ES5 */; } + function getEmitModuleKind(compilerOptions) { return typeof compilerOptions.module === "number" ? compilerOptions.module : getEmitScriptTarget(compilerOptions) >= 2 /* ES2015 */ ? 5 /* ES2015 */ : 1 /* CommonJS */; } + function emitModuleKindIsNonNodeESM(moduleKind) { return moduleKind >= 5 /* ES2015 */ && moduleKind <= 99 /* ESNext */; } + function getEmitModuleResolutionKind(compilerOptions) { let moduleResolution = compilerOptions.moduleResolution; if (moduleResolution === void 0) { @@ -17804,6 +17496,7 @@ ${lanes.join("\n")} function getEmitModuleDetectionKind(options) { return options.moduleDetection || (getEmitModuleKind(options) === 100 /* Node16 */ || getEmitModuleKind(options) === 199 /* NodeNext */ ? 3 /* Force */ : 2 /* Auto */); } + function hasJsonModuleEmitEnabled(options) { switch (getEmitModuleKind(options)) { case 1 /* CommonJS */: @@ -17851,12 +17544,15 @@ ${lanes.join("\n")} } return getESModuleInterop(compilerOptions) || getEmitModuleKind(compilerOptions) === 4 /* System */ || getEmitModuleResolutionKind(compilerOptions) === 100 /* Bundler */; } + function moduleResolutionSupportsPackageJsonExportsAndImports(moduleResolution) { return moduleResolution >= 3 /* Node16 */ && moduleResolution <= 99 /* NodeNext */ || moduleResolution === 100 /* Bundler */; } + function shouldResolveJsRequire(compilerOptions) { return !!compilerOptions.noDtsResolution || getEmitModuleResolutionKind(compilerOptions) !== 100 /* Bundler */; } + function getResolvePackageJsonExports(compilerOptions) { const moduleResolution = getEmitModuleResolutionKind(compilerOptions); if (!moduleResolutionSupportsPackageJsonExportsAndImports(moduleResolution)) { @@ -17895,6 +17591,7 @@ ${lanes.join("\n")} } return getEmitModuleResolutionKind(compilerOptions) === 100 /* Bundler */; } + function getEmitDeclarations(compilerOptions) { return !!(compilerOptions.declaration || compilerOptions.composite); } @@ -17916,6 +17613,7 @@ ${lanes.join("\n")} function getEmitStandardClassFields(compilerOptions) { return compilerOptions.useDefineForClassFields !== false && getEmitScriptTarget(compilerOptions) >= 9 /* ES2022 */; } + function compilerOptionsAffectSemanticDiagnostics(newOptions, oldOptions) { return optionsHaveChanges(oldOptions, newOptions, semanticDiagnosticsOptionDeclarations); } @@ -17932,6 +17630,7 @@ ${lanes.join("\n")} const jsx = options.jsx; return jsx === 2 /* React */ || jsx === 4 /* ReactJSX */ || jsx === 5 /* ReactJSXDev */; } + function getJSXImplicitImportBase(compilerOptions, file) { const jsxImportSourcePragmas = file == null ? void 0 : file.pragmas.get("jsximportsource"); const jsxImportSourcePragma = isArray(jsxImportSourcePragmas) ? jsxImportSourcePragmas[jsxImportSourcePragmas.length - 1] : jsxImportSourcePragmas; @@ -17962,7 +17661,7 @@ ${lanes.join("\n")} getSymlinkedFiles: () => symlinkedFiles, getSymlinkedDirectories: () => symlinkedDirectories, getSymlinkedDirectoriesByRealpath: () => symlinkedDirectoriesByRealpath, - setSymlinkedFile: (path, real) => (symlinkedFiles || (symlinkedFiles = /* @__PURE__ */ new Map())).set(path, real), + setSymlinkedFile: (path, real) => (symlinkedFiles || (symlinkedFiles = /* @__PURE__ */new Map())).set(path, real), setSymlinkedDirectory: (symlink, real) => { let symlinkPath = toPath(symlink, cwd, getCanonicalFileName); if (!containsIgnoredPath(symlinkPath)) { @@ -17970,32 +17669,31 @@ ${lanes.join("\n")} if (real !== false && !(symlinkedDirectories == null ? void 0 : symlinkedDirectories.has(symlinkPath))) { (symlinkedDirectoriesByRealpath || (symlinkedDirectoriesByRealpath = createMultiMap())).add(real.realPath, symlink); } - (symlinkedDirectories || (symlinkedDirectories = /* @__PURE__ */ new Map())).set(symlinkPath, real); + (symlinkedDirectories || (symlinkedDirectories = /* @__PURE__ */new Map())).set(symlinkPath, real); } }, setSymlinksFromResolutions(forEachResolvedModule, forEachResolvedTypeReferenceDirective, typeReferenceDirectives) { Debug.assert(!hasProcessedResolutions); hasProcessedResolutions = true; - forEachResolvedModule((resolution) => processResolution(this, resolution.resolvedModule)); - forEachResolvedTypeReferenceDirective((resolution) => processResolution(this, resolution.resolvedTypeReferenceDirective)); - typeReferenceDirectives.forEach((resolution) => processResolution(this, resolution.resolvedTypeReferenceDirective)); + forEachResolvedModule(resolution => processResolution(this, resolution.resolvedModule)); + forEachResolvedTypeReferenceDirective(resolution => processResolution(this, resolution.resolvedTypeReferenceDirective)); + typeReferenceDirectives.forEach(resolution => processResolution(this, resolution.resolvedTypeReferenceDirective)); }, hasProcessedResolutions: () => hasProcessedResolutions }; function processResolution(cache, resolution) { - if (!resolution || !resolution.originalPath || !resolution.resolvedFileName) - return; - const { resolvedFileName, originalPath } = resolution; + 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; if (commonResolved && commonOriginal) { - cache.setSymlinkedDirectory( - commonOriginal, - { - real: ensureTrailingDirectorySeparator(commonResolved), - realPath: ensureTrailingDirectorySeparator(toPath(commonResolved, cwd, getCanonicalFileName)) - } - ); + cache.setSymlinkedDirectory(commonOriginal, { + real: ensureTrailingDirectorySeparator(commonResolved), + realPath: ensureTrailingDirectorySeparator(toPath(commonResolved, cwd, getCanonicalFileName)) + }); } } } @@ -18031,7 +17729,7 @@ ${lanes.join("\n")} if (!patterns || !patterns.length) { return void 0; } - const pattern = patterns.map((pattern2) => `(${pattern2})`).join("|"); + const pattern = patterns.map(pattern2 => `(${pattern2})`).join("|"); const terminator = usage === "exclude" ? "($|/)" : "$"; return `^(${pattern})${terminator}`; } @@ -18039,7 +17737,7 @@ ${lanes.join("\n")} if (specs === void 0 || specs.length === 0) { return void 0; } - return flatMap(specs, (spec) => spec && getSubPatternFromSpec(spec, basePath, usage, wildcardMatchers[usage])); + return flatMap(specs, spec => spec && getSubPatternFromSpec(spec, basePath, usage, wildcardMatchers[usage])); } function isImplicitGlob(lastPathComponent) { return !/[.*?]/.test(lastPathComponent); @@ -18048,7 +17746,11 @@ ${lanes.join("\n")} const pattern = spec && getSubPatternFromSpec(spec, basePath, usage, wildcardMatchers[usage]); return pattern && `^(${pattern})${usage === "exclude" ? "($|/)" : "$"}`; } - function getSubPatternFromSpec(spec, basePath, usage, { singleAsteriskRegexFragment, doubleAsteriskRegexFragment, replaceWildcardCharacter: replaceWildcardCharacter2 }) { + function getSubPatternFromSpec(spec, basePath, usage, { + singleAsteriskRegexFragment, + doubleAsteriskRegexFragment, + replaceWildcardCharacter: replaceWildcardCharacter2 + }) { let subpattern = ""; let hasWrittenComponent = false; const components = getNormalizedPathComponents(spec, basePath); @@ -18106,7 +17808,7 @@ ${lanes.join("\n")} currentDirectory = normalizePath(currentDirectory); const absolutePath = combinePaths(currentDirectory, path); return { - includeFilePatterns: map(getRegularExpressionsForWildcards(includes, absolutePath, "files"), (pattern) => `^${pattern}$`), + includeFilePatterns: map(getRegularExpressionsForWildcards(includes, absolutePath, "files"), pattern => `^${pattern}$`), includeFilePattern: getRegularExpressionForWildcard(includes, absolutePath, "files"), includeDirectoryPattern: getRegularExpressionForWildcard(includes, absolutePath, "directories"), excludePattern: getRegularExpressionForWildcard(excludes, absolutePath, "exclude"), @@ -18120,11 +17822,11 @@ ${lanes.join("\n")} path = normalizePath(path); currentDirectory = normalizePath(currentDirectory); const patterns = getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames2, currentDirectory); - const includeFileRegexes = patterns.includeFilePatterns && patterns.includeFilePatterns.map((pattern) => getRegexFromPattern(pattern, useCaseSensitiveFileNames2)); + const includeFileRegexes = patterns.includeFilePatterns && patterns.includeFilePatterns.map(pattern => getRegexFromPattern(pattern, useCaseSensitiveFileNames2)); const includeDirectoryRegex = patterns.includeDirectoryPattern && getRegexFromPattern(patterns.includeDirectoryPattern, useCaseSensitiveFileNames2); const excludeRegex = patterns.excludePattern && getRegexFromPattern(patterns.excludePattern, useCaseSensitiveFileNames2); const results = includeFileRegexes ? includeFileRegexes.map(() => []) : [[]]; - const visited = /* @__PURE__ */ new Map(); + const visited = /* @__PURE__ */new Map(); const toCanonical = createGetCanonicalFileName(useCaseSensitiveFileNames2); for (const basePath of patterns.basePaths) { visitDirectory(basePath, combinePaths(currentDirectory, basePath), depth); @@ -18132,21 +17834,21 @@ ${lanes.join("\n")} 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); + 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 { - const includeIndex = findIndex(includeFileRegexes, (re) => re.test(absoluteName)); + const includeIndex = findIndex(includeFileRegexes, re => re.test(absoluteName)); if (includeIndex !== -1) { results[includeIndex].push(name); } @@ -18177,7 +17879,7 @@ ${lanes.join("\n")} } includeBasePaths.sort(getStringComparer(!useCaseSensitiveFileNames2)); for (const includeBasePath of includeBasePaths) { - if (every(basePaths, (basePath) => !containsPath(basePath, includeBasePath, path, !useCaseSensitiveFileNames2))) { + if (every(basePaths, basePath => !containsPath(basePath, includeBasePath, path, !useCaseSensitiveFileNames2))) { basePaths.push(includeBasePath); } } @@ -18194,6 +17896,7 @@ ${lanes.join("\n")} function ensureScriptKind(fileName, scriptKind) { return scriptKind || getScriptKindFromFileName(fileName) || 3 /* TS */; } + function getScriptKindFromFileName(fileName) { const ext = fileName.substr(fileName.lastIndexOf(".")); switch (ext.toLowerCase()) { @@ -18215,6 +17918,7 @@ ${lanes.join("\n")} return 0 /* Unknown */; } } + function getSupportedExtensions(options, extraFileExtensions) { const needJsExtensions = options && getAllowJSCompilerOption(options); if (!extraFileExtensions || extraFileExtensions.length === 0) { @@ -18222,53 +17926,58 @@ ${lanes.join("\n")} } const builtins = needJsExtensions ? allSupportedExtensions : supportedTSExtensions; const flatBuiltins = flatten(builtins); - const extensions = [ - ...builtins, - ...mapDefined(extraFileExtensions, (x) => x.scriptKind === 7 /* Deferred */ || needJsExtensions && isJSLike(x.scriptKind) && !flatBuiltins.includes(x.extension) ? [x.extension] : void 0) - ]; + const extensions = [...builtins, ...mapDefined(extraFileExtensions, x => x.scriptKind === 7 /* Deferred */ || needJsExtensions && isJSLike(x.scriptKind) && !flatBuiltins.includes(x.extension) ? [x.extension] : void 0)]; 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) { return scriptKind === 1 /* JS */ || scriptKind === 2 /* JSX */; } + function hasJSFileExtension(fileName) { - return some(supportedJSExtensionsFlat, (extension) => fileExtensionIs(fileName, extension)); + return some(supportedJSExtensionsFlat, extension => fileExtensionIs(fileName, extension)); } function hasTSFileExtension(fileName) { - return some(supportedTSExtensionsFlat, (extension) => fileExtensionIs(fileName, extension)); + return some(supportedTSExtensionsFlat, extension => fileExtensionIs(fileName, extension)); } - function usesExtensionsOnImports({ imports }, hasExtension2 = or(hasJSFileExtension, hasTSFileExtension)) { - return firstDefined(imports, ({ text }) => pathIsRelative(text) && !fileExtensionIsOneOf(text, extensionsNotSupportingExtensionlessResolution) ? hasExtension2(text) : void 0) || false; + function usesExtensionsOnImports({ + imports + }, hasExtension2 = or(hasJSFileExtension, hasTSFileExtension)) { + return firstDefined(imports, ({ + text + }) => pathIsRelative(text) && !fileExtensionIsOneOf(text, extensionsNotSupportingExtensionlessResolution) ? hasExtension2(text) : void 0) || false; } function getModuleSpecifierEndingPreference(preference, resolutionMode, compilerOptions, sourceFile) { if (preference === "js" || resolutionMode === 99 /* ESNext */) { if (!shouldAllowImportingTsExtension(compilerOptions)) { return 2 /* JsExtension */; } + return inferPreference() !== 2 /* JsExtension */ ? 3 /* TsExtension */ : 2 /* JsExtension */; } + if (preference === "minimal") { return 0 /* Minimal */; } + if (preference === "index") { return 1 /* Index */; } + if (!shouldAllowImportingTsExtension(compilerOptions)) { return usesExtensionsOnImports(sourceFile) ? 2 /* JsExtension */ : 0 /* Minimal */; } + return inferPreference(); function inferPreference() { let usesJsExtensions = false; - const specifiers = sourceFile.imports.length ? sourceFile.imports.map((i) => i.text) : isSourceFileJS(sourceFile) ? getRequiresAtTopOfFile(sourceFile).map((r) => r.arguments[0].text) : emptyArray; + const specifiers = sourceFile.imports.length ? sourceFile.imports.map(i => i.text) : isSourceFileJS(sourceFile) ? getRequiresAtTopOfFile(sourceFile).map(r => r.arguments[0].text) : emptyArray; for (const specifier of specifiers) { if (pathIsRelative(specifier)) { if (fileExtensionIsOneOf(specifier, extensionsNotSupportingExtensionlessResolution)) { @@ -18277,6 +17986,7 @@ ${lanes.join("\n")} if (hasTSFileExtension(specifier)) { return 3 /* TsExtension */; } + if (hasJSFileExtension(specifier)) { usesJsExtensions = true; } @@ -18285,6 +17995,7 @@ ${lanes.join("\n")} return usesJsExtensions ? 2 /* JsExtension */ : 0 /* Minimal */; } } + function getRequiresAtTopOfFile(sourceFile) { let nonRequireStatementCount = 0; let requires; @@ -18293,12 +18004,9 @@ ${lanes.join("\n")} break; } if (isRequireVariableStatement(statement)) { - requires = concatenate(requires, statement.declarationList.declarations.map((d) => d.initializer)); - } else if (isExpressionStatement(statement) && isRequireCall( - statement.expression, - /*requireStringLiteralLikeArgument*/ - true - )) { + requires = concatenate(requires, statement.declarationList.declarations.map(d => d.initializer)); + } else if (isExpressionStatement(statement) && isRequireCall(statement.expression, /*requireStringLiteralLikeArgument*/ + true)) { requires = append(requires, statement.expression); } else { nonRequireStatementCount++; @@ -18307,8 +18015,7 @@ ${lanes.join("\n")} 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)) { @@ -18322,10 +18029,7 @@ ${lanes.join("\n")} return match ? match.length : 0; } function compareNumberOfDirectorySeparators(path1, path2) { - return compareValues( - numberOfDirectorySeparators(path1), - numberOfDirectorySeparators(path2) - ); + return compareValues(numberOfDirectorySeparators(path1), numberOfDirectorySeparators(path2)); } function removeFileExtension(path) { for (const ext of extensionsToRemove) { @@ -18343,13 +18047,8 @@ ${lanes.join("\n")} return path.substring(0, path.length - extension.length); } function changeExtension(path, newExtension) { - return changeAnyExtension( - path, - newExtension, - extensionsToRemove, - /*ignoreCase*/ - false - ); + return changeAnyExtension(path, newExtension, extensionsToRemove, /*ignoreCase*/ + false); } function tryParsePattern(pattern) { const indexOfStar = pattern.indexOf("*"); @@ -18362,7 +18061,7 @@ ${lanes.join("\n")} }; } function tryParsePatterns(paths) { - return mapDefined(getOwnKeys(paths), (path) => tryParsePattern(path)); + return mapDefined(getOwnKeys(paths), path => tryParsePattern(path)); } function positionIsSynthesized(pos) { return !(pos >= 0); @@ -18373,6 +18072,7 @@ ${lanes.join("\n")} function resolutionExtensionIsTSOrJson(ext) { return extensionIsTS(ext) || ext === ".json" /* Json */; } + function extensionFromPath(path) { const ext = tryGetExtensionFromPath2(path); return ext !== void 0 ? ext : Debug.fail(`File ${path} has unknown extension.`); @@ -18381,7 +18081,7 @@ ${lanes.join("\n")} return tryGetExtensionFromPath2(path) !== void 0; } function tryGetExtensionFromPath2(path) { - return find(extensionsToRemove, (e) => fileExtensionIs(path, e)); + return find(extensionsToRemove, e => fileExtensionIs(path, e)); } function isCheckJsEnabledForFile(sourceFile, compilerOptions) { return sourceFile.checkJsDirective ? sourceFile.checkJsDirective.enabled : compilerOptions.checkJs; @@ -18396,7 +18096,7 @@ ${lanes.join("\n")} patterns.push(patternOrString); } } - return findBestPatternMatch(patterns, (_) => _, candidate); + return findBestPatternMatch(patterns, _ => _, candidate); } function sliceAfter(arr, value) { const index = arr.indexOf(value); @@ -18426,15 +18126,24 @@ ${lanes.join("\n")} max = value; } } - return { min: min2, max }; + return { + min: min2, + max + }; } function rangeOfNode(node) { - return { pos: getTokenPosOfNode(node), end: node.end }; + return { + pos: getTokenPosOfNode(node), + end: node.end + }; } function rangeOfTypeParameters(sourceFile, typeParameters) { const pos = typeParameters.pos - 1; const end = Math.min(sourceFile.text.length, skipTrivia(sourceFile.text, typeParameters.end) + 1); - return { pos, end }; + return { + pos, + end + }; } function skipTypeChecking(sourceFile, options, host) { return options.skipLibCheck && sourceFile.isDeclarationFile || options.skipDefaultLibCheck && sourceFile.hasNoDefaultLib || host.isSourceOfProjectReferenceRedirect(sourceFile.fileName); @@ -18465,7 +18174,8 @@ ${lanes.join("\n")} } return stringValue.slice(nonZeroStart, nIndex) || "0"; } - const startIndex = 2, endIndex = stringValue.length - 1; + const startIndex = 2, + endIndex = stringValue.length - 1; const bitsNeeded = (endIndex - startIndex) * log2Base; const segments = new Uint16Array((bitsNeeded >>> 4) + (bitsNeeded & 15 ? 1 : 0)); for (let i = endIndex - 1, bitOffset = 0; i >= startIndex; i--, bitOffset += log2Base) { @@ -18475,8 +18185,7 @@ ${lanes.join("\n")} 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; @@ -18498,15 +18207,15 @@ ${lanes.join("\n")} } return base10Value; } - function pseudoBigIntToString({ negative, base10Value }) { + function pseudoBigIntToString({ + negative, + base10Value + }) { return (negative && base10Value !== "0" ? "-" : "") + base10Value; } function parseBigInt(text) { - if (!isValidBigIntString( - text, - /*roundTripOnly*/ - false - )) { + if (!isValidBigIntString(text, /*roundTripOnly*/ + false)) { return void 0; } return parseValidBigInt(text); @@ -18514,16 +18223,15 @@ ${lanes.join("\n")} function parseValidBigInt(text) { const negative = text.startsWith("-"); const base10Value = parsePseudoBigInt(`${negative ? text.slice(1) : text}n`); - return { negative, base10Value }; + return { + negative, + base10Value + }; } function isValidBigIntString(s, roundTripOnly) { - if (s === "") - return false; - const scanner2 = createScanner( - 99 /* ESNext */, - /*skipTrivia*/ - false - ); + if (s === "") return false; + const scanner2 = createScanner(99 /* ESNext */, /*skipTrivia*/ + false); let success = true; scanner2.setOnError(() => success = false); scanner2.setText(s + "n"); @@ -18533,7 +18241,10 @@ ${lanes.join("\n")} result = scanner2.scan(); } const flags = scanner2.getTokenFlags(); - return success && result === 10 /* BigIntLiteral */ && scanner2.getTokenEnd() === s.length + 1 && !(flags & 512 /* ContainsSeparator */) && (!roundTripOnly || s === pseudoBigIntToString({ negative, base10Value: parsePseudoBigInt(scanner2.getTokenValue()) })); + return success && result === 10 /* BigIntLiteral */ && scanner2.getTokenEnd() === s.length + 1 && !(flags & 512 /* ContainsSeparator */) && (!roundTripOnly || s === pseudoBigIntToString({ + negative, + base10Value: parsePseudoBigInt(scanner2.getTokenValue()) + })); } function isValidTypeOnlyAliasUseSite(useSite) { return !!(useSite.flags & 33554432 /* Ambient */) || isPartOfTypeQuery(useSite) || isIdentifierInNonEmittingHeritageClause(useSite) || isPartOfPossiblyValidTypeOrAbstractComputedPropertyName(useSite) || !(isExpressionNode(useSite) || isShorthandPropertyNameUseSite(useSite)); @@ -18554,10 +18265,10 @@ ${lanes.join("\n")} const containerKind = node.parent.parent.kind; return containerKind === 264 /* InterfaceDeclaration */ || containerKind === 187 /* TypeLiteral */; } + function isIdentifierInNonEmittingHeritageClause(node) { - if (node.kind !== 80 /* Identifier */) - return false; - const heritageClause = findAncestor(node.parent, (parent2) => { + if (node.kind !== 80 /* Identifier */) return false; + const heritageClause = findAncestor(node.parent, parent2 => { switch (parent2.kind) { case 298 /* HeritageClause */: return true; @@ -18570,17 +18281,16 @@ ${lanes.join("\n")} }); return (heritageClause == null ? void 0 : heritageClause.token) === 119 /* ImplementsKeyword */ || (heritageClause == null ? void 0 : heritageClause.parent.kind) === 264 /* InterfaceDeclaration */; } + function isIdentifierTypeReference(node) { return isTypeReferenceNode(node) && isIdentifier(node.typeName); } 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; } @@ -18619,8 +18329,7 @@ ${lanes.join("\n")} 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) { @@ -18659,14 +18368,12 @@ ${lanes.join("\n")} 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; } @@ -18674,14 +18381,15 @@ ${lanes.join("\n")} } } function containsIgnoredPath(path) { - return some(ignoredPaths, (p) => path.includes(p)); + 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; + const { + parent: parent3 + } = node; return parent3.kind === 195 /* InferType */ ? void 0 : parent3.typeParameters; case 169 /* Parameter */: return node.parent.parameters; @@ -18689,14 +18397,19 @@ ${lanes.join("\n")} return node.parent.templateSpans; case 239 /* TemplateSpan */: return node.parent.templateSpans; - case 170 /* Decorator */: { - const { parent: parent4 } = node; - return canHaveDecorators(parent4) ? parent4.modifiers : void 0; - } + case 170 /* Decorator */: + { + const { + parent: parent4 + } = node; + return canHaveDecorators(parent4) ? parent4.modifiers : void 0; + } case 298 /* HeritageClause */: return node.parent.heritageClauses; } - const { parent: parent2 } = node; + const { + parent: parent2 + } = node; if (isJSDocTag(node)) { return isJSDocTypeLiteral(node.parent) ? void 0 : node.parent.tags; } @@ -18743,7 +18456,7 @@ ${lanes.join("\n")} } function hasContextSensitiveParameters(node) { if (!node.typeParameters) { - if (some(node.parameters, (p) => !getEffectiveTypeAnnotationNode(p))) { + if (some(node.parameters, p => !getEffectiveTypeAnnotationNode(p))) { return true; } if (node.kind !== 219 /* ArrowFunction */) { @@ -18761,6 +18474,7 @@ ${lanes.join("\n")} function isCatchClauseVariableDeclaration(node) { return node.kind === 260 /* VariableDeclaration */ && node.parent.kind === 299 /* CatchClause */; } + function isParameterOrCatchClauseVariable(symbol) { const declaration = symbol.valueDeclaration && getRootDeclaration(symbol.valueDeclaration); return !!declaration && (isParameter(declaration) || isCatchClauseVariableDeclaration(declaration)); @@ -18768,6 +18482,7 @@ ${lanes.join("\n")} function isFunctionExpressionOrArrowFunction(node) { return node.kind === 218 /* FunctionExpression */ || node.kind === 219 /* ArrowFunction */; } + function escapeSnippetText(text) { return text.replace(/\$/gm, () => "\\$"); } @@ -18787,7 +18502,7 @@ ${lanes.join("\n")} let packageRootIndex = 0; let fileNameIndex = 0; let States; - ((States2) => { + (States2 => { States2[States2["BeforeNodeModules"] = 0] = "BeforeNodeModules"; States2[States2["NodeModules"] = 1] = "NodeModules"; States2[States2["Scope"] = 2] = "Scope"; @@ -18806,6 +18521,7 @@ ${lanes.join("\n")} topLevelPackageNameIndex = partEnd; state = 1 /* NodeModules */; } + break; case 1 /* NodeModules */: case 2 /* Scope */: @@ -18815,6 +18531,7 @@ ${lanes.join("\n")} packageRootIndex = partEnd; state = 3 /* PackageContent */; } + break; case 3 /* PackageContent */: if (fullPath.indexOf(nodeModulesPathPart, partStart) === partStart) { @@ -18822,11 +18539,17 @@ ${lanes.join("\n")} } else { state = 3 /* PackageContent */; } + break; } } fileNameIndex = partStart; - return state > 1 /* NodeModules */ ? { topLevelNodeModulesIndex, topLevelPackageNameIndex, packageRootIndex, fileNameIndex } : void 0; + return state > 1 /* NodeModules */ ? { + topLevelNodeModulesIndex, + topLevelPackageNameIndex, + packageRootIndex, + fileNameIndex + } : void 0; } function getParameterTypeNode(parameter) { var _a; @@ -18859,9 +18582,13 @@ ${lanes.join("\n")} if (!isJSDocPropertyLikeTag(node)) { return false; } - const { isBracketed, typeExpression } = node; + const { + isBracketed, + typeExpression + } = node; return isBracketed || !!typeExpression && typeExpression.type.kind === 323 /* JSDocOptionalType */; } + function canUsePropertyAccess(name, languageVersion) { if (name.length === 0) { return false; @@ -18873,10 +18600,16 @@ ${lanes.join("\n")} var _a; return ((_a = getSnippetElement(node)) == null ? void 0 : _a.kind) === 0 /* TabStop */; } + function isJSDocOptionalParameter(node) { - return isInJSFile(node) && // node.type should only be a JSDocOptionalType when node is a parameter of a JSDocFunctionType - (node.type && node.type.kind === 323 /* JSDocOptionalType */ || getJSDocParameterTags(node).some(({ isBracketed, typeExpression }) => isBracketed || !!typeExpression && typeExpression.type.kind === 323 /* JSDocOptionalType */)); + return isInJSFile(node) && ( + // node.type should only be a JSDocOptionalType when node is a parameter of a JSDocFunctionType + node.type && node.type.kind === 323 /* JSDocOptionalType */ || getJSDocParameterTags(node).some(({ + isBracketed, + typeExpression + }) => isBracketed || !!typeExpression && typeExpression.type.kind === 323 /* JSDocOptionalType */)); } + function isOptionalDeclaration(declaration) { switch (declaration.kind) { case 172 /* PropertyDeclaration */: @@ -18915,6 +18648,7 @@ ${lanes.join("\n")} const kind = node.kind; return kind === 80 /* Identifier */ || kind === 295 /* JsxNamespacedName */; } + function getEscapedTextOfJsxNamespacedName(node) { return `${node.namespace.escapedText}:${idText(node.name)}`; } @@ -18927,6 +18661,7 @@ ${lanes.join("\n")} function isTypeUsableAsPropertyName(type) { return !!(type.flags & 8576 /* StringOrNumberLiteralOrUnique */); } + function getPropertyNameFromType(type) { if (type.flags & 8192 /* UniqueESSymbol */) { return type.escapedName; @@ -18949,409 +18684,181 @@ ${lanes.join("\n")} var init_utilities = __esm({ "src/compiler/utilities.ts"() { "use strict"; + init_ts2(); resolvingEmptyArray = []; externalHelpersModuleNameText = "tslib"; defaultMaximumTruncationLength = 160; noTruncationMaximumTruncationLength = 1e6; stringWriter = createSingleLineStringWriter(); - getScriptTargetFeatures = /* @__PURE__ */ memoize( - () => new Map(Object.entries({ - Array: new Map(Object.entries({ - es2015: [ - "find", - "findIndex", - "fill", - "copyWithin", - "entries", - "keys", - "values" - ], - es2016: [ - "includes" - ], - es2019: [ - "flat", - "flatMap" - ], - es2022: [ - "at" - ], - es2023: [ - "findLastIndex", - "findLast" - ] - })), - Iterator: new Map(Object.entries({ - es2015: emptyArray - })), - AsyncIterator: new Map(Object.entries({ - es2015: emptyArray - })), - Atomics: new Map(Object.entries({ - es2017: emptyArray - })), - SharedArrayBuffer: new Map(Object.entries({ - es2017: emptyArray - })), - AsyncIterable: new Map(Object.entries({ - es2018: emptyArray - })), - AsyncIterableIterator: new Map(Object.entries({ - es2018: emptyArray - })), - AsyncGenerator: new Map(Object.entries({ - es2018: emptyArray - })), - AsyncGeneratorFunction: new Map(Object.entries({ - es2018: emptyArray - })), - RegExp: new Map(Object.entries({ - es2015: [ - "flags", - "sticky", - "unicode" - ], - es2018: [ - "dotAll" - ] - })), - Reflect: new Map(Object.entries({ - es2015: [ - "apply", - "construct", - "defineProperty", - "deleteProperty", - "get", - "getOwnPropertyDescriptor", - "getPrototypeOf", - "has", - "isExtensible", - "ownKeys", - "preventExtensions", - "set", - "setPrototypeOf" - ] - })), - ArrayConstructor: new Map(Object.entries({ - es2015: [ - "from", - "of" - ] - })), - ObjectConstructor: new Map(Object.entries({ - es2015: [ - "assign", - "getOwnPropertySymbols", - "keys", - "is", - "setPrototypeOf" - ], - es2017: [ - "values", - "entries", - "getOwnPropertyDescriptors" - ], - es2019: [ - "fromEntries" - ], - es2022: [ - "hasOwn" - ] - })), - NumberConstructor: new Map(Object.entries({ - es2015: [ - "isFinite", - "isInteger", - "isNaN", - "isSafeInteger", - "parseFloat", - "parseInt" - ] - })), - Math: new Map(Object.entries({ - es2015: [ - "clz32", - "imul", - "sign", - "log10", - "log2", - "log1p", - "expm1", - "cosh", - "sinh", - "tanh", - "acosh", - "asinh", - "atanh", - "hypot", - "trunc", - "fround", - "cbrt" - ] - })), - Map: new Map(Object.entries({ - es2015: [ - "entries", - "keys", - "values" - ] - })), - Set: new Map(Object.entries({ - es2015: [ - "entries", - "keys", - "values" - ] - })), - PromiseConstructor: new Map(Object.entries({ - es2015: [ - "all", - "race", - "reject", - "resolve" - ], - es2020: [ - "allSettled" - ], - es2021: [ - "any" - ] - })), - Symbol: new Map(Object.entries({ - es2015: [ - "for", - "keyFor" - ], - es2019: [ - "description" - ] - })), - WeakMap: new Map(Object.entries({ - es2015: [ - "entries", - "keys", - "values" - ] - })), - WeakSet: new Map(Object.entries({ - es2015: [ - "entries", - "keys", - "values" - ] - })), - String: new Map(Object.entries({ - es2015: [ - "codePointAt", - "includes", - "endsWith", - "normalize", - "repeat", - "startsWith", - "anchor", - "big", - "blink", - "bold", - "fixed", - "fontcolor", - "fontsize", - "italics", - "link", - "small", - "strike", - "sub", - "sup" - ], - es2017: [ - "padStart", - "padEnd" - ], - es2019: [ - "trimStart", - "trimEnd", - "trimLeft", - "trimRight" - ], - es2020: [ - "matchAll" - ], - es2021: [ - "replaceAll" - ], - es2022: [ - "at" - ] - })), - StringConstructor: new Map(Object.entries({ - es2015: [ - "fromCodePoint", - "raw" - ] - })), - DateTimeFormat: new Map(Object.entries({ - es2017: [ - "formatToParts" - ] - })), - Promise: new Map(Object.entries({ - es2015: emptyArray, - es2018: [ - "finally" - ] - })), - RegExpMatchArray: new Map(Object.entries({ - es2018: [ - "groups" - ] - })), - RegExpExecArray: new Map(Object.entries({ - es2018: [ - "groups" - ] - })), - Intl: new Map(Object.entries({ - es2018: [ - "PluralRules" - ] - })), - NumberFormat: new Map(Object.entries({ - es2018: [ - "formatToParts" - ] - })), - SymbolConstructor: new Map(Object.entries({ - es2020: [ - "matchAll" - ] - })), - DataView: new Map(Object.entries({ - es2020: [ - "setBigInt64", - "setBigUint64", - "getBigInt64", - "getBigUint64" - ] - })), - BigInt: new Map(Object.entries({ - es2020: emptyArray - })), - RelativeTimeFormat: new Map(Object.entries({ - es2020: [ - "format", - "formatToParts", - "resolvedOptions" - ] - })), - Int8Array: new Map(Object.entries({ - es2022: [ - "at" - ], - es2023: [ - "findLastIndex", - "findLast" - ] - })), - Uint8Array: new Map(Object.entries({ - es2022: [ - "at" - ], - es2023: [ - "findLastIndex", - "findLast" - ] - })), - Uint8ClampedArray: new Map(Object.entries({ - es2022: [ - "at" - ], - es2023: [ - "findLastIndex", - "findLast" - ] - })), - Int16Array: new Map(Object.entries({ - es2022: [ - "at" - ], - es2023: [ - "findLastIndex", - "findLast" - ] - })), - Uint16Array: new Map(Object.entries({ - es2022: [ - "at" - ], - es2023: [ - "findLastIndex", - "findLast" - ] - })), - Int32Array: new Map(Object.entries({ - es2022: [ - "at" - ], - es2023: [ - "findLastIndex", - "findLast" - ] - })), - Uint32Array: new Map(Object.entries({ - es2022: [ - "at" - ], - es2023: [ - "findLastIndex", - "findLast" - ] - })), - Float32Array: new Map(Object.entries({ - es2022: [ - "at" - ], - es2023: [ - "findLastIndex", - "findLast" - ] - })), - Float64Array: new Map(Object.entries({ - es2022: [ - "at" - ], - es2023: [ - "findLastIndex", - "findLast" - ] - })), - BigInt64Array: new Map(Object.entries({ - es2020: emptyArray, - es2022: [ - "at" - ], - es2023: [ - "findLastIndex", - "findLast" - ] - })), - BigUint64Array: new Map(Object.entries({ - es2020: emptyArray, - es2022: [ - "at" - ], - es2023: [ - "findLastIndex", - "findLast" - ] - })), - Error: new Map(Object.entries({ - es2022: [ - "cause" - ] - })) + getScriptTargetFeatures = /* @__PURE__ */memoize(() => new Map(Object.entries({ + Array: new Map(Object.entries({ + es2015: ["find", "findIndex", "fill", "copyWithin", "entries", "keys", "values"], + es2016: ["includes"], + es2019: ["flat", "flatMap"], + es2022: ["at"], + es2023: ["findLastIndex", "findLast"] + })), + Iterator: new Map(Object.entries({ + es2015: emptyArray + })), + AsyncIterator: new Map(Object.entries({ + es2015: emptyArray + })), + Atomics: new Map(Object.entries({ + es2017: emptyArray + })), + SharedArrayBuffer: new Map(Object.entries({ + es2017: emptyArray + })), + AsyncIterable: new Map(Object.entries({ + es2018: emptyArray + })), + AsyncIterableIterator: new Map(Object.entries({ + es2018: emptyArray + })), + AsyncGenerator: new Map(Object.entries({ + es2018: emptyArray + })), + AsyncGeneratorFunction: new Map(Object.entries({ + es2018: emptyArray + })), + RegExp: new Map(Object.entries({ + es2015: ["flags", "sticky", "unicode"], + es2018: ["dotAll"] + })), + Reflect: new Map(Object.entries({ + es2015: ["apply", "construct", "defineProperty", "deleteProperty", "get", "getOwnPropertyDescriptor", "getPrototypeOf", "has", "isExtensible", "ownKeys", "preventExtensions", "set", "setPrototypeOf"] + })), + ArrayConstructor: new Map(Object.entries({ + es2015: ["from", "of"] + })), + ObjectConstructor: new Map(Object.entries({ + es2015: ["assign", "getOwnPropertySymbols", "keys", "is", "setPrototypeOf"], + es2017: ["values", "entries", "getOwnPropertyDescriptors"], + es2019: ["fromEntries"], + es2022: ["hasOwn"] + })), + NumberConstructor: new Map(Object.entries({ + es2015: ["isFinite", "isInteger", "isNaN", "isSafeInteger", "parseFloat", "parseInt"] + })), + Math: new Map(Object.entries({ + es2015: ["clz32", "imul", "sign", "log10", "log2", "log1p", "expm1", "cosh", "sinh", "tanh", "acosh", "asinh", "atanh", "hypot", "trunc", "fround", "cbrt"] + })), + Map: new Map(Object.entries({ + es2015: ["entries", "keys", "values"] + })), + Set: new Map(Object.entries({ + es2015: ["entries", "keys", "values"] + })), + PromiseConstructor: new Map(Object.entries({ + es2015: ["all", "race", "reject", "resolve"], + es2020: ["allSettled"], + es2021: ["any"] + })), + Symbol: new Map(Object.entries({ + es2015: ["for", "keyFor"], + es2019: ["description"] + })), + WeakMap: new Map(Object.entries({ + es2015: ["entries", "keys", "values"] + })), + WeakSet: new Map(Object.entries({ + es2015: ["entries", "keys", "values"] + })), + String: new Map(Object.entries({ + es2015: ["codePointAt", "includes", "endsWith", "normalize", "repeat", "startsWith", "anchor", "big", "blink", "bold", "fixed", "fontcolor", "fontsize", "italics", "link", "small", "strike", "sub", "sup"], + es2017: ["padStart", "padEnd"], + es2019: ["trimStart", "trimEnd", "trimLeft", "trimRight"], + es2020: ["matchAll"], + es2021: ["replaceAll"], + es2022: ["at"] + })), + StringConstructor: new Map(Object.entries({ + es2015: ["fromCodePoint", "raw"] + })), + DateTimeFormat: new Map(Object.entries({ + es2017: ["formatToParts"] + })), + Promise: new Map(Object.entries({ + es2015: emptyArray, + es2018: ["finally"] + })), + RegExpMatchArray: new Map(Object.entries({ + es2018: ["groups"] + })), + RegExpExecArray: new Map(Object.entries({ + es2018: ["groups"] + })), + Intl: new Map(Object.entries({ + es2018: ["PluralRules"] + })), + NumberFormat: new Map(Object.entries({ + es2018: ["formatToParts"] + })), + SymbolConstructor: new Map(Object.entries({ + es2020: ["matchAll"] + })), + DataView: new Map(Object.entries({ + es2020: ["setBigInt64", "setBigUint64", "getBigInt64", "getBigUint64"] + })), + BigInt: new Map(Object.entries({ + es2020: emptyArray + })), + RelativeTimeFormat: new Map(Object.entries({ + es2020: ["format", "formatToParts", "resolvedOptions"] + })), + Int8Array: new Map(Object.entries({ + es2022: ["at"], + es2023: ["findLastIndex", "findLast"] + })), + Uint8Array: new Map(Object.entries({ + es2022: ["at"], + es2023: ["findLastIndex", "findLast"] + })), + Uint8ClampedArray: new Map(Object.entries({ + es2022: ["at"], + es2023: ["findLastIndex", "findLast"] + })), + Int16Array: new Map(Object.entries({ + es2022: ["at"], + es2023: ["findLastIndex", "findLast"] + })), + Uint16Array: new Map(Object.entries({ + es2022: ["at"], + es2023: ["findLastIndex", "findLast"] + })), + Int32Array: new Map(Object.entries({ + es2022: ["at"], + es2023: ["findLastIndex", "findLast"] + })), + Uint32Array: new Map(Object.entries({ + es2022: ["at"], + es2023: ["findLastIndex", "findLast"] + })), + Float32Array: new Map(Object.entries({ + es2022: ["at"], + es2023: ["findLastIndex", "findLast"] + })), + Float64Array: new Map(Object.entries({ + es2022: ["at"], + es2023: ["findLastIndex", "findLast"] + })), + BigInt64Array: new Map(Object.entries({ + es2020: emptyArray, + es2022: ["at"], + es2023: ["findLastIndex", "findLast"] + })), + BigUint64Array: new Map(Object.entries({ + es2020: emptyArray, + es2022: ["at"], + es2023: ["findLastIndex", "findLast"] + })), + Error: new Map(Object.entries({ + es2022: ["cause"] })) - ); - GetLiteralTextFlags = /* @__PURE__ */ ((GetLiteralTextFlags2) => { + }))); + GetLiteralTextFlags = /* @__PURE__ */(GetLiteralTextFlags2 => { GetLiteralTextFlags2[GetLiteralTextFlags2["None"] = 0] = "None"; GetLiteralTextFlags2[GetLiteralTextFlags2["NeverAsciiEscape"] = 1] = "NeverAsciiEscape"; GetLiteralTextFlags2[GetLiteralTextFlags2["JsxAttributeEscape"] = 2] = "JsxAttributeEscape"; @@ -19365,13 +18872,13 @@ ${lanes.join("\n")} fullTripleSlashAMDReferencePathRegEx = /^(\/\/\/\s*/; fullTripleSlashAMDModuleRegEx = /^\/\/\/\s*/; defaultLibReferenceRegEx = /^(\/\/\/\s*/; - AssignmentKind = /* @__PURE__ */ ((AssignmentKind2) => { + AssignmentKind = /* @__PURE__ */(AssignmentKind2 => { AssignmentKind2[AssignmentKind2["None"] = 0] = "None"; AssignmentKind2[AssignmentKind2["Definite"] = 1] = "Definite"; AssignmentKind2[AssignmentKind2["Compound"] = 2] = "Compound"; return AssignmentKind2; })(AssignmentKind || {}); - FunctionFlags = /* @__PURE__ */ ((FunctionFlags2) => { + FunctionFlags = /* @__PURE__ */(FunctionFlags2 => { FunctionFlags2[FunctionFlags2["Normal"] = 0] = "Normal"; FunctionFlags2[FunctionFlags2["Generator"] = 1] = "Generator"; FunctionFlags2[FunctionFlags2["Async"] = 2] = "Async"; @@ -19379,12 +18886,12 @@ ${lanes.join("\n")} FunctionFlags2[FunctionFlags2["AsyncGenerator"] = 3] = "AsyncGenerator"; return FunctionFlags2; })(FunctionFlags || {}); - Associativity = /* @__PURE__ */ ((Associativity2) => { + Associativity = /* @__PURE__ */(Associativity2 => { Associativity2[Associativity2["Left"] = 0] = "Left"; Associativity2[Associativity2["Right"] = 1] = "Right"; return Associativity2; })(Associativity || {}); - OperatorPrecedence = /* @__PURE__ */ ((OperatorPrecedence2) => { + OperatorPrecedence = /* @__PURE__ */(OperatorPrecedence2 => { OperatorPrecedence2[OperatorPrecedence2["Comma"] = 0] = "Comma"; OperatorPrecedence2[OperatorPrecedence2["Spread"] = 1] = "Spread"; OperatorPrecedence2[OperatorPrecedence2["Yield"] = 2] = "Yield"; @@ -19436,6 +18943,7 @@ ${lanes.join("\n")} "\r\n": "\\r\\n" // special case for CRLFs in backticks })); + nonAsciiCharacters = /[^\u0000-\u007F]/g; jsxDoubleQuoteEscapedCharsRegExp = /["\u0000-\u001f\u2028\u2029\u0085]/g; jsxSingleQuoteEscapedCharsRegExp = /['\u0000-\u001f\u2028\u2029\u0085]/g; @@ -19476,7 +18984,7 @@ ${lanes.join("\n")} * files or directories, does not match subdirectories that start with a . character */ doubleAsteriskRegexFragment: `(/${implicitExcludePathRegexPattern}[^/.][^/]*)*?`, - replaceWildcardCharacter: (match) => replaceWildcardCharacter(match, filesMatcher.singleAsteriskRegexFragment) + replaceWildcardCharacter: match => replaceWildcardCharacter(match, filesMatcher.singleAsteriskRegexFragment) }; directoriesMatcher = { singleAsteriskRegexFragment: "[^/]*", @@ -19485,12 +18993,12 @@ ${lanes.join("\n")} * files or directories, does not match subdirectories that start with a . character */ doubleAsteriskRegexFragment: `(/${implicitExcludePathRegexPattern}[^/.][^/]*)*?`, - replaceWildcardCharacter: (match) => replaceWildcardCharacter(match, directoriesMatcher.singleAsteriskRegexFragment) + replaceWildcardCharacter: match => replaceWildcardCharacter(match, directoriesMatcher.singleAsteriskRegexFragment) }; excludeMatcher = { singleAsteriskRegexFragment: "[^/]*", doubleAsteriskRegexFragment: "(/.+?)?", - replaceWildcardCharacter: (match) => replaceWildcardCharacter(match, excludeMatcher.singleAsteriskRegexFragment) + replaceWildcardCharacter: match => replaceWildcardCharacter(match, excludeMatcher.singleAsteriskRegexFragment) }; wildcardMatchers = { files: filesMatcher, @@ -19508,7 +19016,7 @@ ${lanes.join("\n")} supportedDeclarationExtensions = [".d.ts" /* Dts */, ".d.cts" /* Dcts */, ".d.mts" /* Dmts */]; supportedTSImplementationExtensions = [".ts" /* Ts */, ".cts" /* Cts */, ".mts" /* Mts */, ".tsx" /* Tsx */]; extensionsNotSupportingExtensionlessResolution = [".mts" /* Mts */, ".d.mts" /* Dmts */, ".mjs" /* Mjs */, ".cts" /* Cts */, ".d.cts" /* Dcts */, ".cjs" /* Cjs */]; - ModuleSpecifierEnding = /* @__PURE__ */ ((ModuleSpecifierEnding2) => { + ModuleSpecifierEnding = /* @__PURE__ */(ModuleSpecifierEnding2 => { ModuleSpecifierEnding2[ModuleSpecifierEnding2["Minimal"] = 0] = "Minimal"; ModuleSpecifierEnding2[ModuleSpecifierEnding2["Index"] = 1] = "Index"; ModuleSpecifierEnding2[ModuleSpecifierEnding2["JsExtension"] = 2] = "JsExtension"; @@ -19538,54 +19046,35 @@ ${lanes.join("\n")} createBaseNode }; function createBaseSourceFileNode(kind) { - return new (SourceFileConstructor2 || (SourceFileConstructor2 = objectAllocator.getSourceFileConstructor()))( - kind, - /*pos*/ - -1, - /*end*/ - -1 - ); + return new (SourceFileConstructor2 || (SourceFileConstructor2 = objectAllocator.getSourceFileConstructor()))(kind, /*pos*/ + -1, /*end*/ + -1); } function createBaseIdentifierNode(kind) { - return new (IdentifierConstructor2 || (IdentifierConstructor2 = objectAllocator.getIdentifierConstructor()))( - kind, - /*pos*/ - -1, - /*end*/ - -1 - ); + return new (IdentifierConstructor2 || (IdentifierConstructor2 = objectAllocator.getIdentifierConstructor()))(kind, /*pos*/ + -1, /*end*/ + -1); } function createBasePrivateIdentifierNode(kind) { - return new (PrivateIdentifierConstructor2 || (PrivateIdentifierConstructor2 = objectAllocator.getPrivateIdentifierConstructor()))( - kind, - /*pos*/ - -1, - /*end*/ - -1 - ); + return new (PrivateIdentifierConstructor2 || (PrivateIdentifierConstructor2 = objectAllocator.getPrivateIdentifierConstructor()))(kind, /*pos*/ + -1, /*end*/ + -1); } function createBaseTokenNode(kind) { - return new (TokenConstructor2 || (TokenConstructor2 = objectAllocator.getTokenConstructor()))( - kind, - /*pos*/ - -1, - /*end*/ - -1 - ); + return new (TokenConstructor2 || (TokenConstructor2 = objectAllocator.getTokenConstructor()))(kind, /*pos*/ + -1, /*end*/ + -1); } function createBaseNode(kind) { - return new (NodeConstructor2 || (NodeConstructor2 = objectAllocator.getNodeConstructor()))( - kind, - /*pos*/ - -1, - /*end*/ - -1 - ); + return new (NodeConstructor2 || (NodeConstructor2 = objectAllocator.getNodeConstructor()))(kind, /*pos*/ + -1, /*end*/ + -1); } } var init_baseNodeFactory = __esm({ "src/compiler/factory/baseNodeFactory.ts"() { "use strict"; + init_ts2(); } }); @@ -19627,24 +19116,20 @@ ${lanes.join("\n")} parenthesizeLeadingTypeArgument }; function getParenthesizeLeftSideOfBinaryForOperator(operatorKind) { - binaryLeftOperandParenthesizerCache || (binaryLeftOperandParenthesizerCache = /* @__PURE__ */ new Map()); + binaryLeftOperandParenthesizerCache || (binaryLeftOperandParenthesizerCache = /* @__PURE__ */new Map()); let parenthesizerRule = binaryLeftOperandParenthesizerCache.get(operatorKind); if (!parenthesizerRule) { - parenthesizerRule = (node) => parenthesizeLeftSideOfBinary(operatorKind, node); + parenthesizerRule = node => parenthesizeLeftSideOfBinary(operatorKind, node); binaryLeftOperandParenthesizerCache.set(operatorKind, parenthesizerRule); } return parenthesizerRule; } function getParenthesizeRightSideOfBinaryForOperator(operatorKind) { - binaryRightOperandParenthesizerCache || (binaryRightOperandParenthesizerCache = /* @__PURE__ */ new Map()); + binaryRightOperandParenthesizerCache || (binaryRightOperandParenthesizerCache = /* @__PURE__ */new Map()); let parenthesizerRule = binaryRightOperandParenthesizerCache.get(operatorKind); if (!parenthesizerRule) { - parenthesizerRule = (node) => parenthesizeRightSideOfBinary( - operatorKind, - /*leftSide*/ - void 0, - node - ); + parenthesizerRule = node => parenthesizeRightSideOfBinary(operatorKind, /*leftSide*/ + void 0, node); binaryRightOperandParenthesizerCache.set(operatorKind, parenthesizerRule); } return parenthesizerRule; @@ -19685,9 +19170,11 @@ ${lanes.join("\n")} } } } + function operatorHasAssociativeProperty(binaryOperator) { return binaryOperator === 42 /* AsteriskToken */ || binaryOperator === 52 /* BarToken */ || binaryOperator === 51 /* AmpersandToken */ || binaryOperator === 53 /* CaretToken */ || binaryOperator === 28 /* CommaToken */; } + function getLiteralKindOfBinaryPlusOperand(node) { node = skipPartiallyEmittedExpressions(node); if (isLiteralKind(node.kind)) { @@ -19704,6 +19191,7 @@ ${lanes.join("\n")} } return 0 /* Unknown */; } + function parenthesizeBinaryOperand(binaryOperator, operand, isLeftSideOfBinary, leftOperand) { const skipped = skipPartiallyEmittedExpressions(operand); if (skipped.kind === 217 /* ParenthesizedExpression */) { @@ -19712,21 +19200,12 @@ ${lanes.join("\n")} return binaryOperandNeedsParentheses(binaryOperator, operand, isLeftSideOfBinary, leftOperand) ? factory2.createParenthesizedExpression(operand) : operand; } function parenthesizeLeftSideOfBinary(binaryOperator, leftSide) { - return parenthesizeBinaryOperand( - binaryOperator, - leftSide, - /*isLeftSideOfBinary*/ - true - ); + return parenthesizeBinaryOperand(binaryOperator, leftSide, /*isLeftSideOfBinary*/ + true); } function parenthesizeRightSideOfBinary(binaryOperator, leftSide, rightSide) { - return parenthesizeBinaryOperand( - binaryOperator, - rightSide, - /*isLeftSideOfBinary*/ - false, - leftSide - ); + return parenthesizeBinaryOperand(binaryOperator, rightSide, /*isLeftSideOfBinary*/ + false, leftSide); } function parenthesizeExpressionOfComputedPropertyName(expression) { return isCommaSequence(expression) ? factory2.createParenthesizedExpression(expression) : expression; @@ -19748,11 +19227,8 @@ ${lanes.join("\n")} const check = skipPartiallyEmittedExpressions(expression); let needsParens = isCommaSequence(check); if (!needsParens) { - switch (getLeftmostExpression( - check, - /*stopAtCallExpressions*/ - false - ).kind) { + switch (getLeftmostExpression(check, /*stopAtCallExpressions*/ + false).kind) { case 231 /* ClassExpression */: case 218 /* FunctionExpression */: needsParens = true; @@ -19761,11 +19237,8 @@ ${lanes.join("\n")} return needsParens ? factory2.createParenthesizedExpression(expression) : expression; } function parenthesizeExpressionOfNew(expression) { - const leftmostExpr = getLeftmostExpression( - expression, - /*stopAtCallExpressions*/ - true - ); + const leftmostExpr = getLeftmostExpression(expression, /*stopAtCallExpressions*/ + true); switch (leftmostExpr.kind) { case 213 /* CallExpression */: return factory2.createParenthesizedExpression(expression); @@ -19803,31 +19276,21 @@ ${lanes.join("\n")} const callee = emittedExpression.expression; const kind = skipPartiallyEmittedExpressions(callee).kind; if (kind === 218 /* FunctionExpression */ || kind === 219 /* ArrowFunction */) { - const updated = factory2.updateCallExpression( - emittedExpression, - setTextRange(factory2.createParenthesizedExpression(callee), callee), - emittedExpression.typeArguments, - emittedExpression.arguments - ); + const updated = factory2.updateCallExpression(emittedExpression, setTextRange(factory2.createParenthesizedExpression(callee), callee), emittedExpression.typeArguments, emittedExpression.arguments); return factory2.restoreOuterExpressions(expression, updated, 8 /* PartiallyEmittedExpressions */); } } - const leftmostExpressionKind = getLeftmostExpression( - emittedExpression, - /*stopAtCallExpressions*/ - false - ).kind; + + const leftmostExpressionKind = getLeftmostExpression(emittedExpression, /*stopAtCallExpressions*/ + false).kind; if (leftmostExpressionKind === 210 /* ObjectLiteralExpression */ || leftmostExpressionKind === 218 /* FunctionExpression */) { return setTextRange(factory2.createParenthesizedExpression(expression), expression); } return expression; } function parenthesizeConciseBodyOfArrowFunction(body) { - if (!isBlock(body) && (isCommaSequence(body) || getLeftmostExpression( - body, - /*stopAtCallExpressions*/ - false - ).kind === 210 /* ObjectLiteralExpression */)) { + if (!isBlock(body) && (isCommaSequence(body) || getLeftmostExpression(body, /*stopAtCallExpressions*/ + false).kind === 210 /* ObjectLiteralExpression */)) { return setTextRange(factory2.createParenthesizedExpression(body), body); } return body; @@ -19897,30 +19360,21 @@ ${lanes.join("\n")} 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) { @@ -19939,37 +19393,38 @@ ${lanes.join("\n")} var init_parenthesizerRules = __esm({ "src/compiler/factory/parenthesizerRules.ts"() { "use strict"; + init_ts2(); nullParenthesizerRules = { - getParenthesizeLeftSideOfBinaryForOperator: (_) => identity, - getParenthesizeRightSideOfBinaryForOperator: (_) => identity, + getParenthesizeLeftSideOfBinaryForOperator: _ => identity, + getParenthesizeRightSideOfBinaryForOperator: _ => identity, parenthesizeLeftSideOfBinary: (_binaryOperator, leftSide) => leftSide, parenthesizeRightSideOfBinary: (_binaryOperator, _leftSide, rightSide) => rightSide, parenthesizeExpressionOfComputedPropertyName: identity, parenthesizeConditionOfConditionalExpression: identity, parenthesizeBranchOfConditionalExpression: identity, parenthesizeExpressionOfExportDefault: identity, - parenthesizeExpressionOfNew: (expression) => cast(expression, isLeftHandSideExpression), - parenthesizeLeftSideOfAccess: (expression) => cast(expression, isLeftHandSideExpression), - parenthesizeOperandOfPostfixUnary: (operand) => cast(operand, isLeftHandSideExpression), - parenthesizeOperandOfPrefixUnary: (operand) => cast(operand, isUnaryExpression), - parenthesizeExpressionsOfCommaDelimitedList: (nodes) => cast(nodes, isNodeArray), + parenthesizeExpressionOfNew: expression => cast(expression, isLeftHandSideExpression), + parenthesizeLeftSideOfAccess: expression => cast(expression, isLeftHandSideExpression), + parenthesizeOperandOfPostfixUnary: operand => cast(operand, isLeftHandSideExpression), + parenthesizeOperandOfPrefixUnary: operand => cast(operand, isUnaryExpression), + parenthesizeExpressionsOfCommaDelimitedList: nodes => cast(nodes, isNodeArray), parenthesizeExpressionForDisallowedComma: identity, parenthesizeExpressionOfExpressionStatement: identity, parenthesizeConciseBodyOfArrowFunction: identity, parenthesizeCheckTypeOfConditionalType: identity, parenthesizeExtendsTypeOfConditionalType: identity, - parenthesizeConstituentTypesOfUnionType: (nodes) => cast(nodes, isNodeArray), + parenthesizeConstituentTypesOfUnionType: nodes => cast(nodes, isNodeArray), parenthesizeConstituentTypeOfUnionType: identity, - parenthesizeConstituentTypesOfIntersectionType: (nodes) => cast(nodes, isNodeArray), + parenthesizeConstituentTypesOfIntersectionType: nodes => cast(nodes, isNodeArray), parenthesizeConstituentTypeOfIntersectionType: identity, parenthesizeOperandOfTypeOperator: identity, parenthesizeOperandOfReadonlyTypeOperator: identity, parenthesizeNonArrayTypeOfPostfixType: identity, - parenthesizeElementTypesOfTupleType: (nodes) => cast(nodes, isNodeArray), + parenthesizeElementTypesOfTupleType: nodes => cast(nodes, isNodeArray), parenthesizeElementTypeOfTupleType: identity, parenthesizeTypeOfOptionalType: identity, - parenthesizeTypeArguments: (nodes) => nodes && cast(nodes, isNodeArray), + parenthesizeTypeArguments: nodes => nodes && cast(nodes, isNodeArray), parenthesizeLeadingTypeArgument: identity }; } @@ -19989,8 +19444,7 @@ ${lanes.join("\n")} 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); @@ -19999,45 +19453,24 @@ ${lanes.join("\n")} } function convertToFunctionExpression(node) { var _a; - 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, - node.name, - node.typeParameters, - node.parameters, - node.type, - node.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, node.name, node.typeParameters, node.parameters, node.type, node.body); setOriginalNode(updated, node); setTextRange(updated, node); if (getStartsOnNewLine(node)) { - setStartsOnNewLine( - updated, - /*newLine*/ - true - ); + setStartsOnNewLine(updated, /*newLine*/ + true); } return updated; } function convertToClassExpression(node) { var _a; - const updated = factory2.createClassExpression( - (_a = node.modifiers) == null ? void 0 : _a.filter((modifier) => !isExportModifier(modifier) && !isDefaultModifier(modifier)), - node.name, - node.typeParameters, - node.heritageClauses, - node.members - ); + const updated = factory2.createClassExpression((_a = node.modifiers) == null ? void 0 : _a.filter(modifier => !isExportModifier(modifier) && !isDefaultModifier(modifier)), node.name, node.typeParameters, node.heritageClauses, node.members); setOriginalNode(updated, node); setTextRange(updated, node); if (getStartsOnNewLine(node)) { - setStartsOnNewLine( - updated, - /*newLine*/ - true - ); + setStartsOnNewLine(updated, /*newLine*/ + true); } return updated; } @@ -20048,13 +19481,7 @@ ${lanes.join("\n")} return setOriginalNode(setTextRange(factory2.createSpreadElement(element.name), element), element); } const expression = convertToAssignmentElementTarget(element.name); - return element.initializer ? setOriginalNode( - setTextRange( - factory2.createAssignment(expression, element.initializer), - element - ), - element - ) : expression; + return element.initializer ? setOriginalNode(setTextRange(factory2.createAssignment(expression, element.initializer), element), element) : expression; } return cast(element, isExpression); } @@ -20085,25 +19512,13 @@ ${lanes.join("\n")} } function convertToObjectAssignmentPattern(node) { if (isObjectBindingPattern(node)) { - return setOriginalNode( - setTextRange( - factory2.createObjectLiteralExpression(map(node.elements, convertToObjectAssignmentElement)), - node - ), - node - ); + return setOriginalNode(setTextRange(factory2.createObjectLiteralExpression(map(node.elements, convertToObjectAssignmentElement)), node), node); } return cast(node, isObjectLiteralExpression); } function convertToArrayAssignmentPattern(node) { if (isArrayBindingPattern(node)) { - return setOriginalNode( - setTextRange( - factory2.createArrayLiteralExpression(map(node.elements, convertToArrayAssignmentElement)), - node - ), - node - ); + return setOriginalNode(setTextRange(factory2.createArrayLiteralExpression(map(node.elements, convertToArrayAssignmentElement)), node), node); } return cast(node, isArrayLiteralExpression); } @@ -20118,6 +19533,7 @@ ${lanes.join("\n")} var init_nodeConverters = __esm({ "src/compiler/factory/nodeConverters.ts"() { "use strict"; + init_ts2(); nullNodeConverters = { convertToFunctionBlock: notImplemented, @@ -20141,18 +19557,18 @@ ${lanes.join("\n")} const update = flags & 8 /* NoOriginalNode */ ? updateWithoutOriginal : updateWithOriginal; const parenthesizerRules = memoize(() => flags & 1 /* NoParenthesizerRules */ ? nullParenthesizerRules : createParenthesizerRules(factory2)); const converters = memoize(() => flags & 2 /* NoNodeConverters */ ? nullNodeConverters : createNodeConverters(factory2)); - const getBinaryCreateFunction = memoizeOne((operator) => (left, right) => createBinaryExpression(left, operator, right)); - const getPrefixUnaryCreateFunction = memoizeOne((operator) => (operand) => createPrefixUnaryExpression(operator, operand)); - const getPostfixUnaryCreateFunction = memoizeOne((operator) => (operand) => createPostfixUnaryExpression(operand, operator)); - const getJSDocPrimaryTypeCreateFunction = memoizeOne((kind) => () => createJSDocPrimaryTypeWorker(kind)); - const getJSDocUnaryTypeCreateFunction = memoizeOne((kind) => (type) => createJSDocUnaryTypeWorker(kind, type)); - const getJSDocUnaryTypeUpdateFunction = memoizeOne((kind) => (node, type) => updateJSDocUnaryTypeWorker(kind, node, type)); - const getJSDocPrePostfixUnaryTypeCreateFunction = memoizeOne((kind) => (type, postfix) => createJSDocPrePostfixUnaryTypeWorker(kind, type, postfix)); - const getJSDocPrePostfixUnaryTypeUpdateFunction = memoizeOne((kind) => (node, type) => updateJSDocPrePostfixUnaryTypeWorker(kind, node, type)); - const getJSDocSimpleTagCreateFunction = memoizeOne((kind) => (tagName, comment) => createJSDocSimpleTagWorker(kind, tagName, comment)); - const getJSDocSimpleTagUpdateFunction = memoizeOne((kind) => (node, tagName, comment) => updateJSDocSimpleTagWorker(kind, node, tagName, comment)); - const getJSDocTypeLikeTagCreateFunction = memoizeOne((kind) => (tagName, typeExpression, comment) => createJSDocTypeLikeTagWorker(kind, tagName, typeExpression, comment)); - const getJSDocTypeLikeTagUpdateFunction = memoizeOne((kind) => (node, tagName, typeExpression, comment) => updateJSDocTypeLikeTagWorker(kind, node, tagName, typeExpression, comment)); + const getBinaryCreateFunction = memoizeOne(operator => (left, right) => createBinaryExpression(left, operator, right)); + const getPrefixUnaryCreateFunction = memoizeOne(operator => operand => createPrefixUnaryExpression(operator, operand)); + const getPostfixUnaryCreateFunction = memoizeOne(operator => operand => createPostfixUnaryExpression(operand, operator)); + const getJSDocPrimaryTypeCreateFunction = memoizeOne(kind => () => createJSDocPrimaryTypeWorker(kind)); + const getJSDocUnaryTypeCreateFunction = memoizeOne(kind => type => createJSDocUnaryTypeWorker(kind, type)); + const getJSDocUnaryTypeUpdateFunction = memoizeOne(kind => (node, type) => updateJSDocUnaryTypeWorker(kind, node, type)); + const getJSDocPrePostfixUnaryTypeCreateFunction = memoizeOne(kind => (type, postfix) => createJSDocPrePostfixUnaryTypeWorker(kind, type, postfix)); + const getJSDocPrePostfixUnaryTypeUpdateFunction = memoizeOne(kind => (node, type) => updateJSDocPrePostfixUnaryTypeWorker(kind, node, type)); + const getJSDocSimpleTagCreateFunction = memoizeOne(kind => (tagName, comment) => createJSDocSimpleTagWorker(kind, tagName, comment)); + const getJSDocSimpleTagUpdateFunction = memoizeOne(kind => (node, tagName, comment) => updateJSDocSimpleTagWorker(kind, node, tagName, comment)); + const getJSDocTypeLikeTagCreateFunction = memoizeOne(kind => (tagName, typeExpression, comment) => createJSDocTypeLikeTagWorker(kind, tagName, typeExpression, comment)); + const getJSDocTypeLikeTagUpdateFunction = memoizeOne(kind => (node, tagName, typeExpression, comment) => updateJSDocTypeLikeTagWorker(kind, node, tagName, typeExpression, comment)); const factory2 = { get parenthesizer() { return parenthesizerRules(); @@ -20441,39 +19857,51 @@ ${lanes.join("\n")} get createJSDocAllType() { return getJSDocPrimaryTypeCreateFunction(319 /* JSDocAllType */); }, + get createJSDocUnknownType() { return getJSDocPrimaryTypeCreateFunction(320 /* JSDocUnknownType */); }, + get createJSDocNonNullableType() { return getJSDocPrePostfixUnaryTypeCreateFunction(322 /* JSDocNonNullableType */); }, + get updateJSDocNonNullableType() { return getJSDocPrePostfixUnaryTypeUpdateFunction(322 /* JSDocNonNullableType */); }, + get createJSDocNullableType() { return getJSDocPrePostfixUnaryTypeCreateFunction(321 /* JSDocNullableType */); }, + get updateJSDocNullableType() { return getJSDocPrePostfixUnaryTypeUpdateFunction(321 /* JSDocNullableType */); }, + get createJSDocOptionalType() { return getJSDocUnaryTypeCreateFunction(323 /* JSDocOptionalType */); }, + get updateJSDocOptionalType() { return getJSDocUnaryTypeUpdateFunction(323 /* JSDocOptionalType */); }, + get createJSDocVariadicType() { return getJSDocUnaryTypeCreateFunction(325 /* JSDocVariadicType */); }, + get updateJSDocVariadicType() { return getJSDocUnaryTypeUpdateFunction(325 /* JSDocVariadicType */); }, + get createJSDocNamepathType() { return getJSDocUnaryTypeCreateFunction(326 /* JSDocNamepathType */); }, + get updateJSDocNamepathType() { return getJSDocUnaryTypeUpdateFunction(326 /* JSDocNamepathType */); }, + createJSDocFunctionType, updateJSDocFunctionType, createJSDocTypeLiteral, @@ -20514,81 +19942,107 @@ ${lanes.join("\n")} get createJSDocTypeTag() { return getJSDocTypeLikeTagCreateFunction(351 /* JSDocTypeTag */); }, + get updateJSDocTypeTag() { return getJSDocTypeLikeTagUpdateFunction(351 /* JSDocTypeTag */); }, + get createJSDocReturnTag() { return getJSDocTypeLikeTagCreateFunction(349 /* JSDocReturnTag */); }, + get updateJSDocReturnTag() { return getJSDocTypeLikeTagUpdateFunction(349 /* JSDocReturnTag */); }, + get createJSDocThisTag() { return getJSDocTypeLikeTagCreateFunction(350 /* JSDocThisTag */); }, + get updateJSDocThisTag() { return getJSDocTypeLikeTagUpdateFunction(350 /* JSDocThisTag */); }, + get createJSDocAuthorTag() { return getJSDocSimpleTagCreateFunction(337 /* JSDocAuthorTag */); }, + get updateJSDocAuthorTag() { return getJSDocSimpleTagUpdateFunction(337 /* JSDocAuthorTag */); }, + get createJSDocClassTag() { return getJSDocSimpleTagCreateFunction(339 /* JSDocClassTag */); }, + get updateJSDocClassTag() { return getJSDocSimpleTagUpdateFunction(339 /* JSDocClassTag */); }, + get createJSDocPublicTag() { return getJSDocSimpleTagCreateFunction(340 /* JSDocPublicTag */); }, + get updateJSDocPublicTag() { return getJSDocSimpleTagUpdateFunction(340 /* JSDocPublicTag */); }, + get createJSDocPrivateTag() { return getJSDocSimpleTagCreateFunction(341 /* JSDocPrivateTag */); }, + get updateJSDocPrivateTag() { return getJSDocSimpleTagUpdateFunction(341 /* JSDocPrivateTag */); }, + get createJSDocProtectedTag() { return getJSDocSimpleTagCreateFunction(342 /* JSDocProtectedTag */); }, + get updateJSDocProtectedTag() { return getJSDocSimpleTagUpdateFunction(342 /* JSDocProtectedTag */); }, + get createJSDocReadonlyTag() { return getJSDocSimpleTagCreateFunction(343 /* JSDocReadonlyTag */); }, + get updateJSDocReadonlyTag() { return getJSDocSimpleTagUpdateFunction(343 /* JSDocReadonlyTag */); }, + get createJSDocOverrideTag() { return getJSDocSimpleTagCreateFunction(344 /* JSDocOverrideTag */); }, + get updateJSDocOverrideTag() { return getJSDocSimpleTagUpdateFunction(344 /* JSDocOverrideTag */); }, + get createJSDocDeprecatedTag() { return getJSDocSimpleTagCreateFunction(338 /* JSDocDeprecatedTag */); }, + get updateJSDocDeprecatedTag() { return getJSDocSimpleTagUpdateFunction(338 /* JSDocDeprecatedTag */); }, + get createJSDocThrowsTag() { return getJSDocTypeLikeTagCreateFunction(356 /* JSDocThrowsTag */); }, + get updateJSDocThrowsTag() { return getJSDocTypeLikeTagUpdateFunction(356 /* JSDocThrowsTag */); }, + get createJSDocSatisfiesTag() { return getJSDocTypeLikeTagCreateFunction(357 /* JSDocSatisfiesTag */); }, + get updateJSDocSatisfiesTag() { return getJSDocTypeLikeTagUpdateFunction(357 /* JSDocSatisfiesTag */); }, + createJSDocEnumTag, updateJSDocEnumTag, createJSDocUnknownTag, @@ -20662,99 +20116,131 @@ ${lanes.join("\n")} get createComma() { return getBinaryCreateFunction(28 /* CommaToken */); }, + get createAssignment() { return getBinaryCreateFunction(64 /* EqualsToken */); }, + get createLogicalOr() { return getBinaryCreateFunction(57 /* BarBarToken */); }, + get createLogicalAnd() { return getBinaryCreateFunction(56 /* AmpersandAmpersandToken */); }, + get createBitwiseOr() { return getBinaryCreateFunction(52 /* BarToken */); }, + get createBitwiseXor() { return getBinaryCreateFunction(53 /* CaretToken */); }, + get createBitwiseAnd() { return getBinaryCreateFunction(51 /* AmpersandToken */); }, + get createStrictEquality() { return getBinaryCreateFunction(37 /* EqualsEqualsEqualsToken */); }, + get createStrictInequality() { return getBinaryCreateFunction(38 /* ExclamationEqualsEqualsToken */); }, + get createEquality() { return getBinaryCreateFunction(35 /* EqualsEqualsToken */); }, + get createInequality() { return getBinaryCreateFunction(36 /* ExclamationEqualsToken */); }, + get createLessThan() { return getBinaryCreateFunction(30 /* LessThanToken */); }, + get createLessThanEquals() { return getBinaryCreateFunction(33 /* LessThanEqualsToken */); }, + get createGreaterThan() { return getBinaryCreateFunction(32 /* GreaterThanToken */); }, + get createGreaterThanEquals() { return getBinaryCreateFunction(34 /* GreaterThanEqualsToken */); }, + get createLeftShift() { return getBinaryCreateFunction(48 /* LessThanLessThanToken */); }, + get createRightShift() { return getBinaryCreateFunction(49 /* GreaterThanGreaterThanToken */); }, + get createUnsignedRightShift() { return getBinaryCreateFunction(50 /* GreaterThanGreaterThanGreaterThanToken */); }, + get createAdd() { return getBinaryCreateFunction(40 /* PlusToken */); }, + get createSubtract() { return getBinaryCreateFunction(41 /* MinusToken */); }, + get createMultiply() { return getBinaryCreateFunction(42 /* AsteriskToken */); }, + get createDivide() { return getBinaryCreateFunction(44 /* SlashToken */); }, + get createModulo() { return getBinaryCreateFunction(45 /* PercentToken */); }, + get createExponent() { return getBinaryCreateFunction(43 /* AsteriskAsteriskToken */); }, + get createPrefixPlus() { return getPrefixUnaryCreateFunction(40 /* PlusToken */); }, + get createPrefixMinus() { return getPrefixUnaryCreateFunction(41 /* MinusToken */); }, + get createPrefixIncrement() { return getPrefixUnaryCreateFunction(46 /* PlusPlusToken */); }, + get createPrefixDecrement() { return getPrefixUnaryCreateFunction(47 /* MinusMinusToken */); }, + get createBitwiseNot() { return getPrefixUnaryCreateFunction(55 /* TildeToken */); }, + get createLogicalNot() { return getPrefixUnaryCreateFunction(54 /* ExclamationToken */); }, + get createPostfixIncrement() { return getPostfixUnaryCreateFunction(46 /* PlusPlusToken */); }, + get createPostfixDecrement() { return getPostfixUnaryCreateFunction(47 /* MinusMinusToken */); }, + // Compound nodes createImmediatelyInvokedFunctionExpression, createImmediatelyInvokedArrowFunction, @@ -20798,7 +20284,7 @@ ${lanes.join("\n")} replaceDecoratorsAndModifiers, replacePropertyName }; - forEach(nodeFactoryPatchers, (fn) => fn(factory2)); + forEach(nodeFactoryPatchers, fn => fn(factory2)); return factory2; function createNodeArray(elements, hasTrailingComma) { if (elements === void 0 || elements === emptyArray) { @@ -20848,8 +20334,7 @@ ${lanes.join("\n")} const node = createBaseDeclaration(9 /* NumericLiteral */); node.text = typeof value === "number" ? value + "" : value; node.numericLiteralFlags = numericLiteralFlags; - if (numericLiteralFlags & 384 /* BinaryOrOctalSpecifier */) - node.transformFlags |= 1024 /* ContainsES2015 */; + if (numericLiteralFlags & 384 /* BinaryOrOctalSpecifier */) node.transformFlags |= 1024 /* ContainsES2015 */; return node; } function createBigIntLiteral(value) { @@ -20867,16 +20352,12 @@ ${lanes.join("\n")} 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) { - const node = createBaseStringLiteral( - getTextOfIdentifierOrLiteral(sourceNode), - /*isSingleQuote*/ - void 0 - ); + const node = createBaseStringLiteral(getTextOfIdentifierOrLiteral(sourceNode), /*isSingleQuote*/ + void 0); node.textSourceNode = sourceNode; return node; } @@ -20888,42 +20369,25 @@ ${lanes.join("\n")} function createLiteralLikeNode(kind, text) { switch (kind) { case 9 /* NumericLiteral */: - return createNumericLiteral( - text, - /*numericLiteralFlags*/ - 0 - ); + return createNumericLiteral(text, /*numericLiteralFlags*/ + 0); case 10 /* BigIntLiteral */: return createBigIntLiteral(text); case 11 /* StringLiteral */: - return createStringLiteral( - text, - /*isSingleQuote*/ - void 0 - ); + return createStringLiteral(text, /*isSingleQuote*/ + void 0); case 12 /* JsxText */: - return createJsxText( - text, - /*containsOnlyTriviaWhiteSpaces*/ - false - ); + return createJsxText(text, /*containsOnlyTriviaWhiteSpaces*/ + false); case 13 /* JsxTextAllWhiteSpaces */: - return createJsxText( - text, - /*containsOnlyTriviaWhiteSpaces*/ - true - ); + return createJsxText(text, /*containsOnlyTriviaWhiteSpaces*/ + true); case 14 /* RegularExpressionLiteral */: return createRegularExpressionLiteral(text); case 15 /* NoSubstitutionTemplateLiteral */: - return createTemplateLiteralLikeNode( - kind, - text, - /*rawText*/ - void 0, - /*templateFlags*/ - 0 - ); + return createTemplateLiteralLikeNode(kind, text, /*rawText*/ + void 0, /*templateFlags*/ + 0); } } function createBaseIdentifier(escapedText) { @@ -20953,20 +20417,20 @@ ${lanes.join("\n")} 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 */; } + if (node.flags & 256 /* IdentifierHasExtendedUnicodeEscape */) { node.transformFlags |= 1024 /* ContainsES2015 */; } + return node; } 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); @@ -20975,16 +20439,10 @@ ${lanes.join("\n")} } function createLoopVariable(reservedInNestedScopes) { let flags2 = 2 /* Loop */; - if (reservedInNestedScopes) - flags2 |= 8 /* ReservedInNestedScopes */; - return createBaseGeneratedIdentifier( - "", - flags2, - /*prefix*/ - void 0, - /*suffix*/ - void 0 - ); + if (reservedInNestedScopes) flags2 |= 8 /* ReservedInNestedScopes */; + return createBaseGeneratedIdentifier("", flags2, /*prefix*/ + void 0, /*suffix*/ + void 0); } function createUniqueName(text, flags2 = 0 /* None */, prefix, suffix) { Debug.assert(!(flags2 & 7 /* KindMask */), "Argument out of range: flags"); @@ -20993,16 +20451,9 @@ ${lanes.join("\n")} } function getGeneratedNameForNode(node, flags2 = 0, prefix, suffix) { Debug.assert(!(flags2 & 7 /* KindMask */), "Argument out of range: flags"); - const text = !node ? "" : isMemberName(node) ? formatGeneratedName( - /*privateName*/ - false, - prefix, - node, - suffix, - idText - ) : `generated@${getNodeId(node)}`; - if (prefix || suffix) - flags2 |= 16 /* Optimistic */; + const text = !node ? "" : isMemberName(node) ? formatGeneratedName( /*privateName*/ + false, prefix, node, suffix, idText) : `generated@${getNodeId(node)}`; + if (prefix || suffix) flags2 |= 16 /* Optimistic */; const name = createBaseGeneratedIdentifier(text, 4 /* Node */ | flags2, prefix, suffix); name.original = node; return name; @@ -21014,8 +20465,7 @@ ${lanes.join("\n")} 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) { @@ -21030,20 +20480,13 @@ ${lanes.join("\n")} 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); + return createBaseGeneratedPrivateIdentifier(text !== null && text !== void 0 ? text : "", autoGenerateFlags, prefix, suffix); } function getGeneratedPrivateNameForNode(node, prefix, suffix) { - const text = isMemberName(node) ? formatGeneratedName( - /*privateName*/ - true, - prefix, - node, - suffix, - idText - ) : `#generated@${getNodeId(node)}`; + const text = isMemberName(node) ? formatGeneratedName( /*privateName*/ + true, prefix, node, suffix, idText) : `#generated@${getNodeId(node)}`; const flags2 = prefix || suffix ? 16 /* Optimistic */ : 0 /* None */; const name = createBaseGeneratedPrivateIdentifier(text, 4 /* Node */ | flags2, prefix, suffix); name.original = node; @@ -21112,53 +20555,43 @@ ${lanes.join("\n")} function createSuper() { return createToken(108 /* SuperKeyword */); } + function createThis() { return createToken(110 /* ThisKeyword */); } + function createNull() { return createToken(106 /* NullKeyword */); } + function createTrue() { return createToken(112 /* TrueKeyword */); } + function createFalse() { return createToken(97 /* FalseKeyword */); } + function createModifier(kind) { return createToken(kind); } 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) { @@ -21206,8 +20639,10 @@ ${lanes.join("\n")} if (isThisIdentifier(node.name)) { node.transformFlags = 1 /* ContainsTypeScript */; } else { - node.transformFlags = propagateChildrenFlags(node.modifiers) | propagateChildFlags(node.dotDotDotToken) | propagateNameFlags(node.name) | propagateChildFlags(node.questionToken) | propagateChildFlags(node.initializer) | (node.questionToken ?? node.type ? 1 /* ContainsTypeScript */ : 0 /* None */) | (node.dotDotDotToken ?? node.initializer ? 1024 /* ContainsES2015 */ : 0 /* None */) | (modifiersToFlags(node.modifiers) & 31 /* ParameterPropertyModifier */ ? 8192 /* ContainsTypeScriptClassSyntax */ : 0 /* None */); + var _node$questionToken, _node$dotDotDotToken; + node.transformFlags = propagateChildrenFlags(node.modifiers) | propagateChildFlags(node.dotDotDotToken) | propagateNameFlags(node.name) | propagateChildFlags(node.questionToken) | propagateChildFlags(node.initializer) | (((_node$questionToken = node.questionToken) !== null && _node$questionToken !== void 0 ? _node$questionToken : node.type) ? 1 /* ContainsTypeScript */ : 0 /* None */) | (((_node$dotDotDotToken = node.dotDotDotToken) !== null && _node$dotDotDotToken !== void 0 ? _node$dotDotDotToken : node.initializer) ? 1024 /* ContainsES2015 */ : 0 /* None */) | (modifiersToFlags(node.modifiers) & 31 /* ParameterPropertyModifier */ ? 8192 /* ContainsTypeScriptClassSyntax */ : 0 /* None */); } + node.jsDoc = void 0; return node; } @@ -21216,11 +20651,8 @@ ${lanes.join("\n")} } function createDecorator(expression) { const node = createBaseNode(170 /* Decorator */); - node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess( - expression, - /*optionalChain*/ - false - ); + node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression, /*optionalChain*/ + false); node.transformFlags |= propagateChildFlags(node.expression) | 1 /* ContainsTypeScript */ | 8192 /* ContainsTypeScriptClassSyntax */ | 33554432 /* ContainsDecorators */; return node; } @@ -21300,6 +20732,7 @@ ${lanes.join("\n")} const isAsyncGenerator = isAsync && isGenerator; node.transformFlags = propagateChildrenFlags(node.modifiers) | propagateChildFlags(node.asteriskToken) | propagateNameFlags(node.name) | propagateChildFlags(node.questionToken) | propagateChildrenFlags(node.typeParameters) | propagateChildrenFlags(node.parameters) | propagateChildFlags(node.type) | propagateChildFlags(node.body) & ~67108864 /* ContainsPossibleTopLevelAwait */ | (isAsyncGenerator ? 128 /* ContainsES2018 */ : isAsync ? 256 /* ContainsES2017 */ : isGenerator ? 2048 /* ContainsGenerator */ : 0 /* None */) | (node.questionToken || node.typeParameters || node.type ? 1 /* ContainsTypeScript */ : 0 /* None */) | 1024 /* ContainsES2015 */; } + node.typeArguments = void 0; node.jsDoc = void 0; node.locals = void 0; @@ -21377,6 +20810,7 @@ ${lanes.join("\n")} } else { node.transformFlags = propagateChildrenFlags(node.modifiers) | propagateNameFlags(node.name) | propagateChildrenFlags(node.parameters) | propagateChildFlags(node.type) | propagateChildFlags(node.body) & ~67108864 /* ContainsPossibleTopLevelAwait */ | (node.type ? 1 /* ContainsTypeScript */ : 0 /* None */); } + node.typeArguments = void 0; node.typeParameters = void 0; node.jsDoc = void 0; @@ -21407,6 +20841,7 @@ ${lanes.join("\n")} } else { node.transformFlags = propagateChildrenFlags(node.modifiers) | propagateNameFlags(node.name) | propagateChildrenFlags(node.parameters) | propagateChildFlags(node.body) & ~67108864 /* ContainsPossibleTopLevelAwait */ | (node.type ? 1 /* ContainsTypeScript */ : 0 /* None */); } + node.typeArguments = void 0; node.typeParameters = void 0; node.type = void 0; @@ -21546,13 +20981,8 @@ ${lanes.join("\n")} return node; } function createConstructorTypeNode2(typeParameters, parameters, type) { - return createConstructorTypeNode1( - /*modifiers*/ - void 0, - typeParameters, - parameters, - type - ); + return createConstructorTypeNode1( /*modifiers*/ + void 0, typeParameters, parameters, type); } function updateConstructorTypeNode(...args) { return args.length === 5 ? updateConstructorTypeNode1(...args) : args.length === 4 ? updateConstructorTypeNode2(...args) : Debug.fail("Incorrect number of arguments specified."); @@ -21767,6 +21197,7 @@ ${lanes.join("\n")} if (node.transformFlags & 32768 /* ContainsRestOrSpread */) { node.transformFlags |= 128 /* ContainsES2018 */ | 65536 /* ContainsObjectRestOrSpread */; } + return node; } function updateObjectBindingPattern(node, elements) { @@ -21828,19 +21259,13 @@ ${lanes.join("\n")} return node; } function createPropertyAccessExpression(expression, name) { - const node = createBasePropertyAccessExpression( - parenthesizerRules().parenthesizeLeftSideOfAccess( - expression, - /*optionalChain*/ - false - ), - /*questionDotToken*/ - void 0, - asName(name) - ); + const node = createBasePropertyAccessExpression(parenthesizerRules().parenthesizeLeftSideOfAccess(expression, /*optionalChain*/ + false), /*questionDotToken*/ + void 0, asName(name)); if (isSuperKeyword(expression)) { node.transformFlags |= 256 /* ContainsES2017 */ | 128 /* ContainsES2018 */; } + return node; } function updatePropertyAccessExpression(node, expression, name) { @@ -21850,15 +21275,8 @@ ${lanes.join("\n")} return node.expression !== expression || node.name !== name ? update(createPropertyAccessExpression(expression, name), node) : node; } function createPropertyAccessChain(expression, questionDotToken, name) { - const node = createBasePropertyAccessExpression( - parenthesizerRules().parenthesizeLeftSideOfAccess( - expression, - /*optionalChain*/ - true - ), - questionDotToken, - asName(name) - ); + const node = createBasePropertyAccessExpression(parenthesizerRules().parenthesizeLeftSideOfAccess(expression, /*optionalChain*/ + true), questionDotToken, asName(name)); node.flags |= 64 /* OptionalChain */; node.transformFlags |= 32 /* ContainsES2020 */; return node; @@ -21878,19 +21296,13 @@ ${lanes.join("\n")} return node; } function createElementAccessExpression(expression, index) { - const node = createBaseElementAccessExpression( - parenthesizerRules().parenthesizeLeftSideOfAccess( - expression, - /*optionalChain*/ - false - ), - /*questionDotToken*/ - void 0, - asExpression(index) - ); + const node = createBaseElementAccessExpression(parenthesizerRules().parenthesizeLeftSideOfAccess(expression, /*optionalChain*/ + false), /*questionDotToken*/ + void 0, asExpression(index)); if (isSuperKeyword(expression)) { node.transformFlags |= 256 /* ContainsES2017 */ | 128 /* ContainsES2018 */; } + return node; } function updateElementAccessExpression(node, expression, argumentExpression) { @@ -21900,15 +21312,8 @@ ${lanes.join("\n")} return node.expression !== expression || node.argumentExpression !== argumentExpression ? update(createElementAccessExpression(expression, argumentExpression), node) : node; } function createElementAccessChain(expression, questionDotToken, index) { - const node = createBaseElementAccessExpression( - parenthesizerRules().parenthesizeLeftSideOfAccess( - expression, - /*optionalChain*/ - true - ), - questionDotToken, - asExpression(index) - ); + const node = createBaseElementAccessExpression(parenthesizerRules().parenthesizeLeftSideOfAccess(expression, /*optionalChain*/ + true), questionDotToken, asExpression(index)); node.flags |= 64 /* OptionalChain */; node.transformFlags |= 32 /* ContainsES2020 */; return node; @@ -21927,26 +21332,21 @@ ${lanes.join("\n")} if (node.typeArguments) { node.transformFlags |= 1 /* ContainsTypeScript */; } + if (isSuperProperty(node.expression)) { node.transformFlags |= 16384 /* ContainsLexicalThis */; } + return node; } function createCallExpression(expression, typeArguments, argumentsArray) { - const node = createBaseCallExpression( - parenthesizerRules().parenthesizeLeftSideOfAccess( - expression, - /*optionalChain*/ - false - ), - /*questionDotToken*/ - void 0, - asNodeArray(typeArguments), - parenthesizerRules().parenthesizeExpressionsOfCommaDelimitedList(createNodeArray(argumentsArray)) - ); + const node = createBaseCallExpression(parenthesizerRules().parenthesizeLeftSideOfAccess(expression, /*optionalChain*/ + false), /*questionDotToken*/ + void 0, asNodeArray(typeArguments), parenthesizerRules().parenthesizeExpressionsOfCommaDelimitedList(createNodeArray(argumentsArray))); if (isImportKeyword(node.expression)) { node.transformFlags |= 8388608 /* ContainsDynamicImport */; } + return node; } function updateCallExpression(node, expression, typeArguments, argumentsArray) { @@ -21956,16 +21356,8 @@ ${lanes.join("\n")} return node.expression !== expression || node.typeArguments !== typeArguments || node.arguments !== argumentsArray ? update(createCallExpression(expression, typeArguments, argumentsArray), node) : node; } function createCallChain(expression, questionDotToken, typeArguments, argumentsArray) { - const node = createBaseCallExpression( - parenthesizerRules().parenthesizeLeftSideOfAccess( - expression, - /*optionalChain*/ - true - ), - questionDotToken, - asNodeArray(typeArguments), - parenthesizerRules().parenthesizeExpressionsOfCommaDelimitedList(createNodeArray(argumentsArray)) - ); + const node = createBaseCallExpression(parenthesizerRules().parenthesizeLeftSideOfAccess(expression, /*optionalChain*/ + true), questionDotToken, asNodeArray(typeArguments), parenthesizerRules().parenthesizeExpressionsOfCommaDelimitedList(createNodeArray(argumentsArray))); node.flags |= 64 /* OptionalChain */; node.transformFlags |= 32 /* ContainsES2020 */; return node; @@ -21983,6 +21375,7 @@ ${lanes.join("\n")} if (node.typeArguments) { node.transformFlags |= 1 /* ContainsTypeScript */; } + return node; } function updateNewExpression(node, expression, typeArguments, argumentsArray) { @@ -21990,20 +21383,19 @@ ${lanes.join("\n")} } function createTaggedTemplateExpression(tag, typeArguments, template) { const node = createBaseNode(215 /* TaggedTemplateExpression */); - node.tag = parenthesizerRules().parenthesizeLeftSideOfAccess( - tag, - /*optionalChain*/ - false - ); + node.tag = parenthesizerRules().parenthesizeLeftSideOfAccess(tag, /*optionalChain*/ + false); node.typeArguments = asNodeArray(typeArguments); node.template = template; node.transformFlags |= propagateChildFlags(node.tag) | propagateChildrenFlags(node.typeArguments) | propagateChildFlags(node.template) | 1024 /* ContainsES2015 */; if (node.typeArguments) { node.transformFlags |= 1 /* ContainsTypeScript */; } + if (hasInvalidEscape(node.template)) { node.transformFlags |= 128 /* ContainsES2018 */; } + return node; } function updateTaggedTemplateExpression(node, tag, typeArguments, template) { @@ -22060,7 +21452,7 @@ ${lanes.join("\n")} node.typeParameters = asNodeArray(typeParameters); node.parameters = createNodeArray(parameters); node.type = type; - node.equalsGreaterThanToken = equalsGreaterThanToken ?? createToken(39 /* EqualsGreaterThanToken */); + node.equalsGreaterThanToken = equalsGreaterThanToken !== null && equalsGreaterThanToken !== void 0 ? equalsGreaterThanToken : createToken(39 /* EqualsGreaterThanToken */); node.body = parenthesizerRules().parenthesizeConciseBodyOfArrowFunction(body); const isAsync = modifiersToFlags(node.modifiers) & 1024 /* Async */; node.transformFlags = propagateChildrenFlags(node.modifiers) | propagateChildrenFlags(node.typeParameters) | propagateChildrenFlags(node.parameters) | propagateChildFlags(node.type) | propagateChildFlags(node.equalsGreaterThanToken) | propagateChildFlags(node.body) & ~67108864 /* ContainsPossibleTopLevelAwait */ | (node.typeParameters || node.type ? 1 /* ContainsTypeScript */ : 0 /* None */) | (isAsync ? 256 /* ContainsES2017 */ | 16384 /* ContainsLexicalThis */ : 0 /* None */) | 1024 /* ContainsES2015 */; @@ -22120,6 +21512,7 @@ ${lanes.join("\n")} if ((operator === 46 /* PlusPlusToken */ || operator === 47 /* MinusMinusToken */) && isIdentifier(node.operand) && !isGeneratedIdentifier(node.operand) && !isLocalName(node.operand)) { node.transformFlags |= 268435456 /* ContainsUpdateExpressionForIdentifier */; } + return node; } function updatePrefixUnaryExpression(node, operand) { @@ -22133,6 +21526,7 @@ ${lanes.join("\n")} if (isIdentifier(node.operand) && !isGeneratedIdentifier(node.operand) && !isLocalName(node.operand)) { node.transformFlags |= 268435456 /* ContainsUpdateExpressionForIdentifier */; } + return node; } function updatePostfixUnaryExpression(node, operand) { @@ -22159,24 +21553,27 @@ ${lanes.join("\n")} } else if (isLogicalOrCoalescingAssignmentOperator(operatorKind)) { node.transformFlags |= 16 /* ContainsES2021 */; } + if (operatorKind === 103 /* InKeyword */ && isPrivateIdentifier(node.left)) { node.transformFlags |= 536870912 /* ContainsPrivateIdentifierInExpression */; } + node.jsDoc = void 0; return node; } function propagateAssignmentPatternFlags(node) { return containsObjectRestOrSpread(node) ? 65536 /* ContainsObjectRestOrSpread */ : 0 /* None */; } + function updateBinaryExpression(node, left, operator, right) { return node.left !== left || node.operatorToken !== operator || node.right !== right ? update(createBinaryExpression(left, operator, right), node) : node; } function createConditionalExpression(condition, questionToken, whenTrue, colonToken, whenFalse) { const node = createBaseNode(227 /* ConditionalExpression */); node.condition = parenthesizerRules().parenthesizeConditionOfConditionalExpression(condition); - node.questionToken = questionToken ?? createToken(58 /* QuestionToken */); + node.questionToken = questionToken !== null && questionToken !== void 0 ? questionToken : createToken(58 /* QuestionToken */); node.whenTrue = parenthesizerRules().parenthesizeBranchOfConditionalExpression(whenTrue); - node.colonToken = colonToken ?? createToken(59 /* ColonToken */); + node.colonToken = colonToken !== null && colonToken !== void 0 ? colonToken : createToken(59 /* ColonToken */); node.whenFalse = parenthesizerRules().parenthesizeBranchOfConditionalExpression(whenFalse); node.transformFlags |= propagateChildFlags(node.condition) | propagateChildFlags(node.questionToken) | propagateChildFlags(node.whenTrue) | propagateChildFlags(node.colonToken) | propagateChildFlags(node.whenFalse); return node; @@ -22218,6 +21615,7 @@ ${lanes.join("\n")} if (templateFlags) { transformFlags |= 128 /* ContainsES2018 */; } + return transformFlags; } function createTemplateLiteralLikeToken(kind, text, rawText, templateFlags) { @@ -22295,13 +21693,11 @@ ${lanes.join("\n")} function createOmittedExpression() { return createBaseNode(232 /* OmittedExpression */); } + function createExpressionWithTypeArguments(expression, typeArguments) { const node = createBaseNode(233 /* ExpressionWithTypeArguments */); - node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess( - expression, - /*optionalChain*/ - false - ); + node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression, /*optionalChain*/ + false); node.typeArguments = typeArguments && parenthesizerRules().parenthesizeTypeArguments(typeArguments); node.transformFlags |= propagateChildFlags(node.expression) | propagateChildrenFlags(node.typeArguments) | 1024 /* ContainsES2015 */; return node; @@ -22321,11 +21717,8 @@ ${lanes.join("\n")} } function createNonNullExpression(expression) { const node = createBaseNode(235 /* NonNullExpression */); - node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess( - expression, - /*optionalChain*/ - false - ); + node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression, /*optionalChain*/ + false); node.transformFlags |= propagateChildFlags(node.expression) | 1 /* ContainsTypeScript */; return node; } @@ -22348,11 +21741,8 @@ ${lanes.join("\n")} function createNonNullChain(expression) { const node = createBaseNode(235 /* NonNullExpression */); node.flags |= 64 /* OptionalChain */; - node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess( - expression, - /*optionalChain*/ - true - ); + node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression, /*optionalChain*/ + true); node.transformFlags |= propagateChildFlags(node.expression) | 1 /* ContainsTypeScript */; return node; } @@ -22417,6 +21807,7 @@ ${lanes.join("\n")} if (modifiersToFlags(node.modifiers) & 128 /* Ambient */) { node.transformFlags = 1 /* ContainsTypeScript */; } + node.jsDoc = void 0; node.flowNode = void 0; return node; @@ -22515,8 +21906,7 @@ ${lanes.join("\n")} 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; @@ -22627,12 +22017,13 @@ ${lanes.join("\n")} return node; } function createVariableDeclaration(name, exclamationToken, type, initializer) { + var _node$exclamationToke; const node = createBaseDeclaration(260 /* VariableDeclaration */); node.name = asName(name); node.exclamationToken = exclamationToken; node.type = type; node.initializer = asInitializer(initializer); - node.transformFlags |= propagateNameFlags(node.name) | propagateChildFlags(node.initializer) | (node.exclamationToken ?? node.type ? 1 /* ContainsTypeScript */ : 0 /* None */); + node.transformFlags |= propagateNameFlags(node.name) | propagateChildFlags(node.initializer) | (((_node$exclamationToke = node.exclamationToken) !== null && _node$exclamationToke !== void 0 ? _node$exclamationToke : node.type) ? 1 /* ContainsTypeScript */ : 0 /* None */); node.jsDoc = void 0; return node; } @@ -22647,9 +22038,11 @@ ${lanes.join("\n")} if (flags2 & 7 /* BlockScoped */) { node.transformFlags |= 1024 /* ContainsES2015 */ | 262144 /* ContainsBlockScopedBinding */; } + if (flags2 & 4 /* Using */) { node.transformFlags |= 4 /* ContainsESNext */; } + return node; } function updateVariableDeclarationList(node, declarations) { @@ -22672,6 +22065,7 @@ ${lanes.join("\n")} const isAsyncGenerator = isAsync && isGenerator; node.transformFlags = propagateChildrenFlags(node.modifiers) | propagateChildFlags(node.asteriskToken) | propagateNameFlags(node.name) | propagateChildrenFlags(node.typeParameters) | propagateChildrenFlags(node.parameters) | propagateChildFlags(node.type) | propagateChildFlags(node.body) & ~67108864 /* ContainsPossibleTopLevelAwait */ | (isAsyncGenerator ? 128 /* ContainsES2018 */ : isAsync ? 256 /* ContainsES2017 */ : isGenerator ? 2048 /* ContainsGenerator */ : 0 /* None */) | (node.typeParameters || node.type ? 1 /* ContainsTypeScript */ : 0 /* None */) | 4194304 /* ContainsHoistedDeclarationOrCompletion */; } + node.typeArguments = void 0; node.jsDoc = void 0; node.locals = void 0; @@ -22706,6 +22100,7 @@ ${lanes.join("\n")} node.transformFlags |= 1 /* ContainsTypeScript */; } } + node.jsDoc = void 0; return node; } @@ -22765,6 +22160,7 @@ ${lanes.join("\n")} } else { node.transformFlags |= propagateChildrenFlags(node.modifiers) | propagateChildFlags(node.name) | propagateChildFlags(node.body) | 1 /* ContainsTypeScript */; } + node.transformFlags &= ~67108864 /* ContainsPossibleTopLevelAwait */; node.jsDoc = void 0; node.locals = void 0; @@ -22822,6 +22218,7 @@ ${lanes.join("\n")} if (!isExternalModuleReference(node.moduleReference)) { node.transformFlags |= 1 /* ContainsTypeScript */; } + node.transformFlags &= ~67108864 /* ContainsPossibleTopLevelAwait */; node.jsDoc = void 0; return node; @@ -22852,6 +22249,7 @@ ${lanes.join("\n")} if (isTypeOnly) { node.transformFlags |= 1 /* ContainsTypeScript */; } + node.transformFlags &= ~67108864 /* ContainsPossibleTopLevelAwait */; return node; } @@ -22890,7 +22288,7 @@ ${lanes.join("\n")} } function createImportAttributes(elements, multiLine, token) { const node = createBaseNode(300 /* ImportAttributes */); - node.token = token ?? 118 /* WithKeyword */; + node.token = token !== null && token !== void 0 ? token : 118 /* WithKeyword */; node.elements = createNodeArray(elements); node.multiLine = multiLine; node.transformFlags |= 4 /* ContainsESNext */; @@ -22955,12 +22353,8 @@ ${lanes.join("\n")} const node = createBaseDeclaration(277 /* ExportAssignment */); node.modifiers = asNodeArray(modifiers); node.isExportEquals = isExportEquals; - node.expression = isExportEquals ? parenthesizerRules().parenthesizeRightSideOfBinary( - 64 /* EqualsToken */, - /*leftSide*/ - void 0, - expression - ) : parenthesizerRules().parenthesizeExpressionOfExportDefault(expression); + node.expression = isExportEquals ? parenthesizerRules().parenthesizeRightSideOfBinary(64 /* EqualsToken */, /*leftSide*/ + void 0, expression) : parenthesizerRules().parenthesizeExpressionOfExportDefault(expression); node.transformFlags |= propagateChildrenFlags(node.modifiers) | propagateChildFlags(node.expression); node.transformFlags &= ~67108864 /* ContainsPossibleTopLevelAwait */; node.jsDoc = void 0; @@ -23034,10 +22428,7 @@ ${lanes.join("\n")} return createBaseNode(kind); } function createJSDocPrePostfixUnaryTypeWorker(kind, type, postfix = false) { - const node = createJSDocUnaryTypeWorker( - kind, - postfix ? type && parenthesizerRules().parenthesizeNonArrayTypeOfPostfixType(type) : type - ); + const node = createJSDocUnaryTypeWorker(kind, postfix ? type && parenthesizerRules().parenthesizeNonArrayTypeOfPostfixType(type) : type); node.postfix = postfix; return node; } @@ -23113,7 +22504,7 @@ ${lanes.join("\n")} return node; } function createJSDocTemplateTag(tagName, constraint, typeParameters, comment) { - const node = createBaseJSDocTag(352 /* JSDocTemplateTag */, tagName ?? createIdentifier("template"), comment); + const node = createBaseJSDocTag(352 /* JSDocTemplateTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("template"), comment); node.constraint = constraint; node.typeParameters = createNodeArray(typeParameters); return node; @@ -23122,7 +22513,7 @@ ${lanes.join("\n")} return node.tagName !== tagName || node.constraint !== constraint || node.typeParameters !== typeParameters || node.comment !== comment ? update(createJSDocTemplateTag(tagName, constraint, typeParameters, comment), node) : node; } function createJSDocTypedefTag(tagName, typeExpression, fullName, comment) { - const node = createBaseJSDocTagDeclaration(353 /* JSDocTypedefTag */, tagName ?? createIdentifier("typedef"), comment); + const node = createBaseJSDocTagDeclaration(353 /* JSDocTypedefTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("typedef"), comment); node.typeExpression = typeExpression; node.fullName = fullName; node.name = getJSDocTypeAliasName(fullName); @@ -23134,7 +22525,7 @@ ${lanes.join("\n")} return node.tagName !== tagName || node.typeExpression !== typeExpression || node.fullName !== fullName || node.comment !== comment ? update(createJSDocTypedefTag(tagName, typeExpression, fullName, comment), node) : node; } function createJSDocParameterTag(tagName, name, isBracketed, typeExpression, isNameFirst, comment) { - const node = createBaseJSDocTagDeclaration(348 /* JSDocParameterTag */, tagName ?? createIdentifier("param"), comment); + const node = createBaseJSDocTagDeclaration(348 /* JSDocParameterTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("param"), comment); node.typeExpression = typeExpression; node.name = name; node.isNameFirst = !!isNameFirst; @@ -23145,7 +22536,7 @@ ${lanes.join("\n")} return node.tagName !== tagName || node.name !== name || node.isBracketed !== isBracketed || node.typeExpression !== typeExpression || node.isNameFirst !== isNameFirst || node.comment !== comment ? update(createJSDocParameterTag(tagName, name, isBracketed, typeExpression, isNameFirst, comment), node) : node; } function createJSDocPropertyTag(tagName, name, isBracketed, typeExpression, isNameFirst, comment) { - const node = createBaseJSDocTagDeclaration(355 /* JSDocPropertyTag */, tagName ?? createIdentifier("prop"), comment); + const node = createBaseJSDocTagDeclaration(355 /* JSDocPropertyTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("prop"), comment); node.typeExpression = typeExpression; node.name = name; node.isNameFirst = !!isNameFirst; @@ -23156,7 +22547,7 @@ ${lanes.join("\n")} return node.tagName !== tagName || node.name !== name || node.isBracketed !== isBracketed || node.typeExpression !== typeExpression || node.isNameFirst !== isNameFirst || node.comment !== comment ? update(createJSDocPropertyTag(tagName, name, isBracketed, typeExpression, isNameFirst, comment), node) : node; } function createJSDocCallbackTag(tagName, typeExpression, fullName, comment) { - const node = createBaseJSDocTagDeclaration(345 /* JSDocCallbackTag */, tagName ?? createIdentifier("callback"), comment); + const node = createBaseJSDocTagDeclaration(345 /* JSDocCallbackTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("callback"), comment); node.typeExpression = typeExpression; node.fullName = fullName; node.name = getJSDocTypeAliasName(fullName); @@ -23168,7 +22559,7 @@ ${lanes.join("\n")} return node.tagName !== tagName || node.typeExpression !== typeExpression || node.fullName !== fullName || node.comment !== comment ? update(createJSDocCallbackTag(tagName, typeExpression, fullName, comment), node) : node; } function createJSDocOverloadTag(tagName, typeExpression, comment) { - const node = createBaseJSDocTag(346 /* JSDocOverloadTag */, tagName ?? createIdentifier("overload"), comment); + const node = createBaseJSDocTag(346 /* JSDocOverloadTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("overload"), comment); node.typeExpression = typeExpression; return node; } @@ -23176,7 +22567,7 @@ ${lanes.join("\n")} return node.tagName !== tagName || node.typeExpression !== typeExpression || node.comment !== comment ? update(createJSDocOverloadTag(tagName, typeExpression, comment), node) : node; } function createJSDocAugmentsTag(tagName, className, comment) { - const node = createBaseJSDocTag(335 /* JSDocAugmentsTag */, tagName ?? createIdentifier("augments"), comment); + const node = createBaseJSDocTag(335 /* JSDocAugmentsTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("augments"), comment); node.class = className; return node; } @@ -23184,12 +22575,12 @@ ${lanes.join("\n")} return node.tagName !== tagName || node.class !== className || node.comment !== comment ? update(createJSDocAugmentsTag(tagName, className, comment), node) : node; } function createJSDocImplementsTag(tagName, className, comment) { - const node = createBaseJSDocTag(336 /* JSDocImplementsTag */, tagName ?? createIdentifier("implements"), comment); + const node = createBaseJSDocTag(336 /* JSDocImplementsTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("implements"), comment); node.class = className; return node; } function createJSDocSeeTag(tagName, name, comment) { - const node = createBaseJSDocTag(354 /* JSDocSeeTag */, tagName ?? createIdentifier("see"), comment); + const node = createBaseJSDocTag(354 /* JSDocSeeTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("see"), comment); node.name = name; return node; } @@ -23245,14 +22636,14 @@ ${lanes.join("\n")} return node.tagName !== tagName || node.class !== className || node.comment !== comment ? update(createJSDocImplementsTag(tagName, className, comment), node) : node; } function createJSDocSimpleTagWorker(kind, tagName, comment) { - const node = createBaseJSDocTag(kind, tagName ?? createIdentifier(getDefaultTagNameForKind(kind)), comment); + const node = createBaseJSDocTag(kind, tagName !== null && tagName !== void 0 ? tagName : createIdentifier(getDefaultTagNameForKind(kind)), comment); return node; } function updateJSDocSimpleTagWorker(kind, node, tagName = getDefaultTagName(node), comment) { return node.tagName !== tagName || node.comment !== comment ? update(createJSDocSimpleTagWorker(kind, tagName, comment), node) : node; } function createJSDocTypeLikeTagWorker(kind, tagName, typeExpression, comment) { - const node = createBaseJSDocTag(kind, tagName ?? createIdentifier(getDefaultTagNameForKind(kind)), comment); + const node = createBaseJSDocTag(kind, tagName !== null && tagName !== void 0 ? tagName : createIdentifier(getDefaultTagNameForKind(kind)), comment); node.typeExpression = typeExpression; return node; } @@ -23267,7 +22658,7 @@ ${lanes.join("\n")} return node.tagName !== tagName || node.comment !== comment ? update(createJSDocUnknownTag(tagName, comment), node) : node; } function createJSDocEnumTag(tagName, typeExpression, comment) { - const node = createBaseJSDocTagDeclaration(347 /* JSDocEnumTag */, tagName ?? createIdentifier(getDefaultTagNameForKind(347 /* JSDocEnumTag */)), comment); + const node = createBaseJSDocTagDeclaration(347 /* JSDocEnumTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier(getDefaultTagNameForKind(347 /* JSDocEnumTag */)), comment); node.typeExpression = typeExpression; node.locals = void 0; node.nextContainer = void 0; @@ -23313,6 +22704,7 @@ ${lanes.join("\n")} if (node.typeArguments) { node.transformFlags |= 1 /* ContainsTypeScript */; } + return node; } function updateJsxSelfClosingElement(node, tagName, typeArguments, attributes) { @@ -23327,6 +22719,7 @@ ${lanes.join("\n")} if (typeArguments) { node.transformFlags |= 1 /* ContainsTypeScript */; } + return node; } function updateJsxOpeningElement(node, tagName, typeArguments, attributes) { @@ -23675,7 +23068,7 @@ ${lanes.join("\n")} node.text = ""; node.referencedFiles = emptyArray; node.libReferenceDirectives = emptyArray; - node.getLineAndCharacterOfPosition = (pos) => getLineAndCharacterOfPosition(node, pos); + node.getLineAndCharacterOfPosition = pos => getLineAndCharacterOfPosition(node, pos); return node; } function createBaseUnparsedNode(kind, data) { @@ -23770,7 +23163,9 @@ ${lanes.join("\n")} clone2.flags |= node.flags & ~16 /* Synthesized */; clone2.transformFlags = node.transformFlags; setOriginalNode(clone2, node); - setIdentifierAutoGenerate(clone2, { ...node.emitNode.autoGenerate }); + setIdentifierAutoGenerate(clone2, { + ...node.emitNode.autoGenerate + }); return clone2; } function cloneIdentifier(node) { @@ -23782,8 +23177,7 @@ ${lanes.join("\n")} clone2.transformFlags = node.transformFlags; setOriginalNode(clone2, node); const typeArguments = getIdentifierTypeArguments(node); - if (typeArguments) - setIdentifierTypeArguments(clone2, typeArguments); + if (typeArguments) setIdentifierTypeArguments(clone2, typeArguments); return clone2; } function cloneGeneratedPrivateIdentifier(node) { @@ -23791,7 +23185,9 @@ ${lanes.join("\n")} clone2.flags |= node.flags & ~16 /* Synthesized */; clone2.transformFlags = node.transformFlags; setOriginalNode(clone2, node); - setIdentifierAutoGenerate(clone2, { ...node.emitNode.autoGenerate }); + setIdentifierAutoGenerate(clone2, { + ...node.emitNode.autoGenerate + }); return clone2; } function clonePrivateIdentifier(node) { @@ -23833,85 +23229,42 @@ ${lanes.join("\n")} return clone2; } function createImmediatelyInvokedFunctionExpression(statements, param, paramValue) { - return createCallExpression( - createFunctionExpression( - /*modifiers*/ - void 0, - /*asteriskToken*/ - void 0, - /*name*/ - void 0, - /*typeParameters*/ - void 0, - /*parameters*/ - param ? [param] : [], - /*type*/ - void 0, - createBlock( - statements, - /*multiLine*/ - true - ) - ), - /*typeArguments*/ - void 0, - /*argumentsArray*/ - paramValue ? [paramValue] : [] - ); + return createCallExpression(createFunctionExpression( /*modifiers*/ + void 0, /*asteriskToken*/ + void 0, /*name*/ + void 0, /*typeParameters*/ + void 0, /*parameters*/ + param ? [param] : [], /*type*/ + void 0, createBlock(statements, /*multiLine*/ + true)), /*typeArguments*/ + void 0, /*argumentsArray*/ + paramValue ? [paramValue] : []); } function createImmediatelyInvokedArrowFunction(statements, param, paramValue) { - return createCallExpression( - createArrowFunction( - /*modifiers*/ - void 0, - /*typeParameters*/ - void 0, - /*parameters*/ - param ? [param] : [], - /*type*/ - void 0, - /*equalsGreaterThanToken*/ - void 0, - createBlock( - statements, - /*multiLine*/ - true - ) - ), - /*typeArguments*/ - void 0, - /*argumentsArray*/ - paramValue ? [paramValue] : [] - ); + return createCallExpression(createArrowFunction( /*modifiers*/ + void 0, /*typeParameters*/ + void 0, /*parameters*/ + param ? [param] : [], /*type*/ + void 0, /*equalsGreaterThanToken*/ + void 0, createBlock(statements, /*multiLine*/ + true)), /*typeArguments*/ + void 0, /*argumentsArray*/ + paramValue ? [paramValue] : []); } function createVoidZero() { return createVoidExpression(createNumericLiteral("0")); } function createExportDefault(expression) { - return createExportAssignment2( - /*modifiers*/ - void 0, - /*isExportEquals*/ - false, - expression - ); + return createExportAssignment2( /*modifiers*/ + void 0, /*isExportEquals*/ + false, expression); } function createExternalModuleExport(exportName) { - return createExportDeclaration( - /*modifiers*/ - void 0, - /*isTypeOnly*/ - false, - createNamedExports([ - createExportSpecifier( - /*isTypeOnly*/ - false, - /*propertyName*/ - void 0, - exportName - ) - ]) - ); + return createExportDeclaration( /*modifiers*/ + void 0, /*isTypeOnly*/ + false, createNamedExports([createExportSpecifier( /*isTypeOnly*/ + false, /*propertyName*/ + void 0, exportName)])); } function createTypeCheck(value, tag) { return tag === "null" ? factory2.createStrictEquality(value, createNull()) : tag === "undefined" ? factory2.createStrictEquality(value, createVoidZero()) : factory2.createStrictEquality(createTypeOfExpression(value), createStringLiteral(tag)); @@ -23921,26 +23274,13 @@ ${lanes.join("\n")} } function createMethodCall(object, methodName, argumentsList) { if (isCallChain(object)) { - return createCallChain( - createPropertyAccessChain( - object, - /*questionDotToken*/ - void 0, - methodName - ), - /*questionDotToken*/ - void 0, - /*typeArguments*/ - void 0, - argumentsList - ); + return createCallChain(createPropertyAccessChain(object, /*questionDotToken*/ + void 0, methodName), /*questionDotToken*/ + void 0, /*typeArguments*/ + void 0, argumentsList); } - return createCallExpression( - createPropertyAccessExpression(object, methodName), - /*typeArguments*/ - void 0, - argumentsList - ); + return createCallExpression(createPropertyAccessExpression(object, methodName), /*typeArguments*/ + void 0, argumentsList); } function createFunctionBindCall(target, thisArg, argumentsList) { return createMethodCall(target, "bind", [thisArg, ...argumentsList]); @@ -24011,10 +23351,7 @@ ${lanes.join("\n")} } function restoreOuterExpressions(outerExpression, innerExpression, kinds = 15 /* All */) { if (outerExpression && isOuterExpression(outerExpression, kinds) && !isIgnorableParen(outerExpression)) { - return updateOuterExpression( - outerExpression, - restoreOuterExpressions(outerExpression.expression, innerExpression) - ); + return updateOuterExpression(outerExpression, restoreOuterExpressions(outerExpression.expression, innerExpression)); } return innerExpression; } @@ -24022,11 +23359,7 @@ ${lanes.join("\n")} if (!outermostLabeledStatement) { return node; } - const updated = updateLabeledStatement( - outermostLabeledStatement, - outermostLabeledStatement.label, - isLabeledStatement(outermostLabeledStatement.statement) ? restoreEnclosingLabel(node, outermostLabeledStatement.statement) : node - ); + const updated = updateLabeledStatement(outermostLabeledStatement, outermostLabeledStatement.label, isLabeledStatement(outermostLabeledStatement.statement) ? restoreEnclosingLabel(node, outermostLabeledStatement.statement) : node); if (afterRestoreLabelCallback) { afterRestoreLabelCallback(outermostLabeledStatement); } @@ -24066,24 +23399,12 @@ ${lanes.join("\n")} target = languageVersion !== void 0 && languageVersion < 2 /* ES2015 */ ? setTextRange(createIdentifier("_super"), callee) : callee; } else if (getEmitFlags(callee) & 8192 /* HelperName */) { thisArg = createVoidZero(); - target = parenthesizerRules().parenthesizeLeftSideOfAccess( - callee, - /*optionalChain*/ - false - ); + target = parenthesizerRules().parenthesizeLeftSideOfAccess(callee, /*optionalChain*/ + false); } else if (isPropertyAccessExpression(callee)) { if (shouldBeCapturedInTempVariable(callee.expression, cacheIdentifiers)) { thisArg = createTempVariable(recordTempVariable); - target = createPropertyAccessExpression( - setTextRange( - factory2.createAssignment( - thisArg, - callee.expression - ), - callee.expression - ), - callee.name - ); + target = createPropertyAccessExpression(setTextRange(factory2.createAssignment(thisArg, callee.expression), callee.expression), callee.name); setTextRange(target, callee); } else { thisArg = callee.expression; @@ -24092,16 +23413,7 @@ ${lanes.join("\n")} } else if (isElementAccessExpression(callee)) { if (shouldBeCapturedInTempVariable(callee.expression, cacheIdentifiers)) { thisArg = createTempVariable(recordTempVariable); - target = createElementAccessExpression( - setTextRange( - factory2.createAssignment( - thisArg, - callee.expression - ), - callee.expression - ), - callee.argumentExpression - ); + target = createElementAccessExpression(setTextRange(factory2.createAssignment(thisArg, callee.expression), callee.expression), callee.argumentExpression); setTextRange(target, callee); } else { thisArg = callee.expression; @@ -24109,44 +23421,24 @@ ${lanes.join("\n")} } } else { thisArg = createVoidZero(); - target = parenthesizerRules().parenthesizeLeftSideOfAccess( - expression, - /*optionalChain*/ - false - ); + target = parenthesizerRules().parenthesizeLeftSideOfAccess(expression, /*optionalChain*/ + false); } - return { target, thisArg }; + return { + target, + thisArg + }; } function createAssignmentTargetWrapper(paramName, expression) { return createPropertyAccessExpression( - // Explicit parens required because of v8 regression (https://bugs.chromium.org/p/v8/issues/detail?id=9560) - createParenthesizedExpression( - createObjectLiteralExpression([ - createSetAccessorDeclaration( - /*modifiers*/ - void 0, - "value", - [createParameterDeclaration( - /*modifiers*/ - void 0, - /*dotDotDotToken*/ - void 0, - paramName, - /*questionToken*/ - void 0, - /*type*/ - void 0, - /*initializer*/ - void 0 - )], - createBlock([ - createExpressionStatement(expression) - ]) - ) - ]) - ), - "value" - ); + // Explicit parens required because of v8 regression (https://bugs.chromium.org/p/v8/issues/detail?id=9560) + createParenthesizedExpression(createObjectLiteralExpression([createSetAccessorDeclaration( /*modifiers*/ + void 0, "value", [createParameterDeclaration( /*modifiers*/ + void 0, /*dotDotDotToken*/ + void 0, paramName, /*questionToken*/ + void 0, /*type*/ + void 0, /*initializer*/ + void 0)], createBlock([createExpressionStatement(expression)]))])), "value"); } function inlineExpressions(expressions) { return expressions.length > 10 ? createCommaListExpression(expressions) : reduceLeft(expressions, factory2.createComma); @@ -24156,12 +23448,9 @@ ${lanes.join("\n")} 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); @@ -24169,12 +23458,14 @@ ${lanes.join("\n")} function getInternalName(node, allowComments, allowSourceMaps) { return getName(node, allowComments, allowSourceMaps, 32768 /* LocalName */ | 65536 /* InternalName */); } + function getLocalName(node, allowComments, allowSourceMaps, ignoreAssignedName) { return getName(node, allowComments, allowSourceMaps, 32768 /* LocalName */, ignoreAssignedName); } function getExportName(node, allowComments, allowSourceMaps) { return getName(node, allowComments, allowSourceMaps, 16384 /* ExportName */); } + function getDeclarationName(node, allowComments, allowSourceMaps) { return getName(node, allowComments, allowSourceMaps); } @@ -24182,12 +23473,9 @@ ${lanes.join("\n")} 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) { @@ -24284,7 +23572,7 @@ ${lanes.join("\n")} if (leftStandardPrologueEnd === 0) { left.splice(0, 0, ...declarations.slice(0, rightStandardPrologueEnd)); } else { - const leftPrologues = /* @__PURE__ */ new Map(); + const leftPrologues = /* @__PURE__ */new Map(); for (let i = 0; i < leftStandardPrologueEnd; i++) { const leftPrologue = statements[i]; leftPrologues.set(leftPrologue.expression.text, true); @@ -24303,18 +23591,21 @@ ${lanes.join("\n")} return statements; } function replaceModifiers(node, modifiers) { + var _node$questionToken2; let modifierArray; if (typeof modifiers === "number") { modifierArray = createModifiersFromModifierFlags(modifiers); } else { modifierArray = modifiers; } - return isTypeParameterDeclaration(node) ? updateTypeParameterDeclaration(node, modifierArray, node.name, node.constraint, node.default) : isParameter(node) ? updateParameterDeclaration(node, modifierArray, node.dotDotDotToken, node.name, node.questionToken, node.type, node.initializer) : isConstructorTypeNode(node) ? updateConstructorTypeNode1(node, modifierArray, node.typeParameters, node.parameters, node.type) : isPropertySignature(node) ? updatePropertySignature(node, modifierArray, node.name, node.questionToken, node.type) : isPropertyDeclaration(node) ? updatePropertyDeclaration2(node, modifierArray, node.name, node.questionToken ?? node.exclamationToken, node.type, node.initializer) : isMethodSignature(node) ? updateMethodSignature(node, modifierArray, node.name, node.questionToken, node.typeParameters, node.parameters, node.type) : isMethodDeclaration(node) ? updateMethodDeclaration(node, modifierArray, node.asteriskToken, node.name, node.questionToken, node.typeParameters, node.parameters, node.type, node.body) : isConstructorDeclaration(node) ? updateConstructorDeclaration(node, modifierArray, node.parameters, node.body) : isGetAccessorDeclaration(node) ? updateGetAccessorDeclaration(node, modifierArray, node.name, node.parameters, node.type, node.body) : isSetAccessorDeclaration(node) ? updateSetAccessorDeclaration(node, modifierArray, node.name, node.parameters, node.body) : isIndexSignatureDeclaration(node) ? updateIndexSignature(node, modifierArray, node.parameters, node.type) : isFunctionExpression(node) ? updateFunctionExpression(node, modifierArray, node.asteriskToken, node.name, node.typeParameters, node.parameters, node.type, node.body) : isArrowFunction(node) ? updateArrowFunction(node, modifierArray, node.typeParameters, node.parameters, node.type, node.equalsGreaterThanToken, node.body) : isClassExpression(node) ? updateClassExpression(node, modifierArray, node.name, node.typeParameters, node.heritageClauses, node.members) : isVariableStatement(node) ? updateVariableStatement(node, modifierArray, node.declarationList) : isFunctionDeclaration(node) ? updateFunctionDeclaration(node, modifierArray, node.asteriskToken, node.name, node.typeParameters, node.parameters, node.type, node.body) : isClassDeclaration(node) ? updateClassDeclaration(node, modifierArray, node.name, node.typeParameters, node.heritageClauses, node.members) : isInterfaceDeclaration(node) ? updateInterfaceDeclaration(node, modifierArray, node.name, node.typeParameters, node.heritageClauses, node.members) : isTypeAliasDeclaration(node) ? updateTypeAliasDeclaration(node, modifierArray, node.name, node.typeParameters, node.type) : isEnumDeclaration(node) ? updateEnumDeclaration(node, modifierArray, node.name, node.members) : isModuleDeclaration(node) ? updateModuleDeclaration(node, modifierArray, node.name, node.body) : isImportEqualsDeclaration(node) ? updateImportEqualsDeclaration(node, modifierArray, node.isTypeOnly, node.name, node.moduleReference) : isImportDeclaration(node) ? updateImportDeclaration(node, modifierArray, node.importClause, node.moduleSpecifier, node.attributes) : isExportAssignment(node) ? updateExportAssignment(node, modifierArray, node.expression) : isExportDeclaration(node) ? updateExportDeclaration(node, modifierArray, node.isTypeOnly, node.exportClause, node.moduleSpecifier, node.attributes) : Debug.assertNever(node); + return isTypeParameterDeclaration(node) ? updateTypeParameterDeclaration(node, modifierArray, node.name, node.constraint, node.default) : isParameter(node) ? updateParameterDeclaration(node, modifierArray, node.dotDotDotToken, node.name, node.questionToken, node.type, node.initializer) : isConstructorTypeNode(node) ? updateConstructorTypeNode1(node, modifierArray, node.typeParameters, node.parameters, node.type) : isPropertySignature(node) ? updatePropertySignature(node, modifierArray, node.name, node.questionToken, node.type) : isPropertyDeclaration(node) ? updatePropertyDeclaration2(node, modifierArray, node.name, (_node$questionToken2 = node.questionToken) !== null && _node$questionToken2 !== void 0 ? _node$questionToken2 : node.exclamationToken, node.type, node.initializer) : isMethodSignature(node) ? updateMethodSignature(node, modifierArray, node.name, node.questionToken, node.typeParameters, node.parameters, node.type) : isMethodDeclaration(node) ? updateMethodDeclaration(node, modifierArray, node.asteriskToken, node.name, node.questionToken, node.typeParameters, node.parameters, node.type, node.body) : isConstructorDeclaration(node) ? updateConstructorDeclaration(node, modifierArray, node.parameters, node.body) : isGetAccessorDeclaration(node) ? updateGetAccessorDeclaration(node, modifierArray, node.name, node.parameters, node.type, node.body) : isSetAccessorDeclaration(node) ? updateSetAccessorDeclaration(node, modifierArray, node.name, node.parameters, node.body) : isIndexSignatureDeclaration(node) ? updateIndexSignature(node, modifierArray, node.parameters, node.type) : isFunctionExpression(node) ? updateFunctionExpression(node, modifierArray, node.asteriskToken, node.name, node.typeParameters, node.parameters, node.type, node.body) : isArrowFunction(node) ? updateArrowFunction(node, modifierArray, node.typeParameters, node.parameters, node.type, node.equalsGreaterThanToken, node.body) : isClassExpression(node) ? updateClassExpression(node, modifierArray, node.name, node.typeParameters, node.heritageClauses, node.members) : isVariableStatement(node) ? updateVariableStatement(node, modifierArray, node.declarationList) : isFunctionDeclaration(node) ? updateFunctionDeclaration(node, modifierArray, node.asteriskToken, node.name, node.typeParameters, node.parameters, node.type, node.body) : isClassDeclaration(node) ? updateClassDeclaration(node, modifierArray, node.name, node.typeParameters, node.heritageClauses, node.members) : isInterfaceDeclaration(node) ? updateInterfaceDeclaration(node, modifierArray, node.name, node.typeParameters, node.heritageClauses, node.members) : isTypeAliasDeclaration(node) ? updateTypeAliasDeclaration(node, modifierArray, node.name, node.typeParameters, node.type) : isEnumDeclaration(node) ? updateEnumDeclaration(node, modifierArray, node.name, node.members) : isModuleDeclaration(node) ? updateModuleDeclaration(node, modifierArray, node.name, node.body) : isImportEqualsDeclaration(node) ? updateImportEqualsDeclaration(node, modifierArray, node.isTypeOnly, node.name, node.moduleReference) : isImportDeclaration(node) ? updateImportDeclaration(node, modifierArray, node.importClause, node.moduleSpecifier, node.attributes) : isExportAssignment(node) ? updateExportAssignment(node, modifierArray, node.expression) : isExportDeclaration(node) ? updateExportDeclaration(node, modifierArray, node.isTypeOnly, node.exportClause, node.moduleSpecifier, node.attributes) : Debug.assertNever(node); } function replaceDecoratorsAndModifiers(node, modifierArray) { - return isParameter(node) ? updateParameterDeclaration(node, modifierArray, node.dotDotDotToken, node.name, node.questionToken, node.type, node.initializer) : isPropertyDeclaration(node) ? updatePropertyDeclaration2(node, modifierArray, node.name, node.questionToken ?? node.exclamationToken, node.type, node.initializer) : isMethodDeclaration(node) ? updateMethodDeclaration(node, modifierArray, node.asteriskToken, node.name, node.questionToken, node.typeParameters, node.parameters, node.type, node.body) : isGetAccessorDeclaration(node) ? updateGetAccessorDeclaration(node, modifierArray, node.name, node.parameters, node.type, node.body) : isSetAccessorDeclaration(node) ? updateSetAccessorDeclaration(node, modifierArray, node.name, node.parameters, node.body) : isClassExpression(node) ? updateClassExpression(node, modifierArray, node.name, node.typeParameters, node.heritageClauses, node.members) : isClassDeclaration(node) ? updateClassDeclaration(node, modifierArray, node.name, node.typeParameters, node.heritageClauses, node.members) : Debug.assertNever(node); + var _node$questionToken3; + return isParameter(node) ? updateParameterDeclaration(node, modifierArray, node.dotDotDotToken, node.name, node.questionToken, node.type, node.initializer) : isPropertyDeclaration(node) ? updatePropertyDeclaration2(node, modifierArray, node.name, (_node$questionToken3 = node.questionToken) !== null && _node$questionToken3 !== void 0 ? _node$questionToken3 : node.exclamationToken, node.type, node.initializer) : isMethodDeclaration(node) ? updateMethodDeclaration(node, modifierArray, node.asteriskToken, node.name, node.questionToken, node.typeParameters, node.parameters, node.type, node.body) : isGetAccessorDeclaration(node) ? updateGetAccessorDeclaration(node, modifierArray, node.name, node.parameters, node.type, node.body) : isSetAccessorDeclaration(node) ? updateSetAccessorDeclaration(node, modifierArray, node.name, node.parameters, node.body) : isClassExpression(node) ? updateClassExpression(node, modifierArray, node.name, node.typeParameters, node.heritageClauses, node.members) : isClassDeclaration(node) ? updateClassDeclaration(node, modifierArray, node.name, node.typeParameters, node.heritageClauses, node.members) : Debug.assertNever(node); } function replacePropertyName(node, name) { + var _node$questionToken4; switch (node.kind) { case 177 /* GetAccessor */: return updateGetAccessorDeclaration(node, node.modifiers, name, node.parameters, node.type, node.body); @@ -24325,7 +23616,7 @@ ${lanes.join("\n")} case 173 /* MethodSignature */: return updateMethodSignature(node, node.modifiers, name, node.questionToken, node.typeParameters, node.parameters, node.type); case 172 /* PropertyDeclaration */: - return updatePropertyDeclaration2(node, node.modifiers, name, node.questionToken ?? node.exclamationToken, node.type, node.initializer); + return updatePropertyDeclaration2(node, node.modifiers, name, (_node$questionToken4 = node.questionToken) !== null && _node$questionToken4 !== void 0 ? _node$questionToken4 : node.exclamationToken, node.type, node.initializer); case 171 /* PropertySignature */: return updatePropertySignature(node, node.modifiers, name, node.questionToken, node.type); case 303 /* PropertyAssignment */: @@ -24352,15 +23643,10 @@ ${lanes.join("\n")} } function asVariableDeclaration(variableDeclaration) { if (typeof variableDeclaration === "string" || variableDeclaration && !isVariableDeclaration(variableDeclaration)) { - return createVariableDeclaration( - variableDeclaration, - /*exclamationToken*/ - void 0, - /*type*/ - void 0, - /*initializer*/ - void 0 - ); + return createVariableDeclaration(variableDeclaration, /*exclamationToken*/ + void 0, /*type*/ + void 0, /*initializer*/ + void 0); } return variableDeclaration; } @@ -24424,13 +23710,10 @@ ${lanes.join("\n")} } function getCookedText(kind, rawText) { if (!rawTextScanner) { - rawTextScanner = createScanner( - 99 /* Latest */, - /*skipTrivia*/ - false, - 0 /* Standard */ - ); + rawTextScanner = createScanner(99 /* Latest */, /*skipTrivia*/ + false, 0 /* Standard */); } + switch (kind) { case 15 /* NoSubstitutionTemplateLiteral */: rawTextScanner.setText("`" + rawText + "`"); @@ -24447,10 +23730,8 @@ ${lanes.join("\n")} } let token = rawTextScanner.scan(); if (token === 20 /* CloseBraceToken */) { - token = rawTextScanner.reScanTemplateToken( - /*isTaggedTemplate*/ - false - ); + token = rawTextScanner.reScanTemplateToken( /*isTaggedTemplate*/ + false); } if (rawTextScanner.isUnterminated()) { rawTextScanner.setText(void 0); @@ -24478,18 +23759,20 @@ ${lanes.join("\n")} function propagateIdentifierNameFlags(node) { return propagateChildFlags(node) & ~67108864 /* ContainsPossibleTopLevelAwait */; } + 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; } function propagateChildrenFlags(children) { return children ? children.transformFlags : 0 /* None */; } + function aggregateChildrenFlags(children) { let subtreeFlags = 0 /* None */; for (const child of children) { @@ -24501,6 +23784,7 @@ ${lanes.join("\n")} if (kind >= 182 /* FirstTypeNode */ && kind <= 205 /* LastTypeNode */) { return -2 /* TypeExcludes */; } + switch (kind) { case 213 /* CallExpression */: case 214 /* NewExpression */: @@ -24567,6 +23851,7 @@ ${lanes.join("\n")} return -2147483648 /* NodeExcludes */; } } + function makeSynthetic(node) { node.flags |= 16 /* Synthesized */; return node; @@ -24607,16 +23892,22 @@ ${lanes.join("\n")} node.sourceMapPath = sourceMapPath; node.oldFileOfCurrentEmit = oldFileOfCurrentEmit; if (getText && getSourceMapText) { - Object.defineProperty(node, "text", { get: getText }); - Object.defineProperty(node, "sourceMapText", { get: getSourceMapText }); + Object.defineProperty(node, "text", { + get: getText + }); + Object.defineProperty(node, "sourceMapText", { + get: getSourceMapText + }); } else { + var _text; Debug.assert(!oldFileOfCurrentEmit); - node.text = text ?? ""; + node.text = (_text = text) !== null && _text !== void 0 ? _text : ""; node.sourceMapText = sourceMapText; } return node; } function parseUnparsedSourceFile(bundleFileInfo, stripInternal, length2) { + var _prependTexts, _prologues; let prologues; let helpers; let referencedFiles; @@ -24637,19 +23928,41 @@ ${lanes.join("\n")} hasNoDefaultLib = true; break; case "reference" /* Reference */: - referencedFiles = append(referencedFiles, { pos: -1, end: -1, fileName: section.data }); + referencedFiles = append(referencedFiles, { + pos: -1, + end: -1, + fileName: section.data + }); break; case "type" /* Type */: - typeReferenceDirectives = append(typeReferenceDirectives, { pos: -1, end: -1, fileName: section.data }); + typeReferenceDirectives = append(typeReferenceDirectives, { + pos: -1, + end: -1, + fileName: section.data + }); break; case "type-import" /* TypeResolutionModeImport */: - typeReferenceDirectives = append(typeReferenceDirectives, { pos: -1, end: -1, fileName: section.data, resolutionMode: 99 /* ESNext */ }); + typeReferenceDirectives = append(typeReferenceDirectives, { + pos: -1, + end: -1, + fileName: section.data, + resolutionMode: 99 /* ESNext */ + }); break; case "type-require" /* TypeResolutionModeRequire */: - typeReferenceDirectives = append(typeReferenceDirectives, { pos: -1, end: -1, fileName: section.data, resolutionMode: 1 /* CommonJS */ }); + typeReferenceDirectives = append(typeReferenceDirectives, { + pos: -1, + end: -1, + fileName: section.data, + resolutionMode: 1 /* CommonJS */ + }); break; case "lib" /* Lib */: - libReferenceDirectives = append(libReferenceDirectives, { pos: -1, end: -1, fileName: section.data }); + libReferenceDirectives = append(libReferenceDirectives, { + pos: -1, + end: -1, + fileName: section.data + }); break; case "prepend" /* Prepend */: let prependTexts; @@ -24659,12 +23972,11 @@ ${lanes.join("\n")} } } prependChildren = addRange(prependChildren, prependTexts); - texts = append(texts, factory.createUnparsedPrepend(section.data, prependTexts ?? emptyArray)); + texts = append(texts, factory.createUnparsedPrepend(section.data, (_prependTexts = prependTexts) !== null && _prependTexts !== void 0 ? _prependTexts : emptyArray)); break; case "internal" /* Internal */: if (stripInternal) { - if (!texts) - texts = []; + if (!texts) texts = []; break; } case "text" /* Text */: @@ -24675,21 +23987,14 @@ ${lanes.join("\n")} } } if (!texts) { - const textNode = factory.createUnparsedTextLike( - /*data*/ - void 0, - /*internal*/ - false - ); + const textNode = factory.createUnparsedTextLike( /*data*/ + void 0, /*internal*/ + false); setTextRangePosWidth(textNode, 0, typeof length2 === "function" ? length2() : length2); texts = [textNode]; } - const node = parseNodeFactory.createUnparsedSource( - prologues ?? emptyArray, - /*syntheticReferences*/ - void 0, - texts - ); + const node = parseNodeFactory.createUnparsedSource((_prologues = prologues) !== null && _prologues !== void 0 ? _prologues : emptyArray, /*syntheticReferences*/ + void 0, texts); setEachParent(prologues, node); setEachParent(texts, node); setEachParent(prependChildren, node); @@ -24701,6 +24006,7 @@ ${lanes.join("\n")} return node; } function parseOldFileOfCurrentEmit(bundleFileInfo) { + var _texts; let texts; let syntheticReferences; for (const section of bundleFileInfo.sections) { @@ -24725,32 +24031,16 @@ ${lanes.join("\n")} Debug.assertNever(section); } } - const node = factory.createUnparsedSource(emptyArray, syntheticReferences, texts ?? emptyArray); + const node = factory.createUnparsedSource(emptyArray, syntheticReferences, (_texts = texts) !== null && _texts !== void 0 ? _texts : emptyArray); setEachParent(syntheticReferences, node); setEachParent(texts, node); - node.helpers = map(bundleFileInfo.sources && bundleFileInfo.sources.helpers, (name) => getAllUnscopedEmitHelpers().get(name)); + node.helpers = map(bundleFileInfo.sources && bundleFileInfo.sources.helpers, name => getAllUnscopedEmitHelpers().get(name)); return node; } function createInputFiles(javascriptTextOrReadFileText, declarationTextOrJavascriptPath, javascriptMapPath, javascriptMapTextOrDeclarationPath, declarationMapPath, declarationMapTextOrBuildInfoPath) { - return !isString(javascriptTextOrReadFileText) ? createInputFilesWithFilePaths( - javascriptTextOrReadFileText, - declarationTextOrJavascriptPath, - javascriptMapPath, - javascriptMapTextOrDeclarationPath, - declarationMapPath, - declarationMapTextOrBuildInfoPath - ) : createInputFilesWithFileTexts( - /*javascriptPath*/ - void 0, - javascriptTextOrReadFileText, - javascriptMapPath, - javascriptMapTextOrDeclarationPath, - /*declarationPath*/ - void 0, - declarationTextOrJavascriptPath, - declarationMapPath, - declarationMapTextOrBuildInfoPath - ); + return !isString(javascriptTextOrReadFileText) ? createInputFilesWithFilePaths(javascriptTextOrReadFileText, declarationTextOrJavascriptPath, javascriptMapPath, javascriptMapTextOrDeclarationPath, declarationMapPath, declarationMapTextOrBuildInfoPath) : createInputFilesWithFileTexts( /*javascriptPath*/ + void 0, javascriptTextOrReadFileText, javascriptMapPath, javascriptMapTextOrDeclarationPath, /*declarationPath*/ + void 0, declarationTextOrJavascriptPath, declarationMapPath, declarationMapTextOrBuildInfoPath); } function createInputFilesWithFilePaths(readFileText, javascriptPath, javascriptMapPath, declarationPath, declarationMapPath, buildInfoPath, host, options) { const node = parseNodeFactory.createInputFiles(); @@ -24759,10 +24049,9 @@ ${lanes.join("\n")} node.declarationPath = declarationPath; node.declarationMapPath = declarationMapPath; node.buildInfoPath = buildInfoPath; - const cache = /* @__PURE__ */ new Map(); - const textGetter = (path) => { - if (path === void 0) - return void 0; + const cache = /* @__PURE__ */new Map(); + const textGetter = path => { + if (path === void 0) return void 0; let value = cache.get(path); if (value === void 0) { value = readFileText(path); @@ -24770,7 +24059,7 @@ ${lanes.join("\n")} } return value !== false ? value : void 0; }; - const definedTextGetter = (path) => { + const definedTextGetter = path => { const result = textGetter(path); return result !== void 0 ? result : `/* Input file ${path} was missing */\r `; @@ -24779,22 +24068,34 @@ ${lanes.join("\n")} const getAndCacheBuildInfo = () => { if (buildInfo === void 0 && buildInfoPath) { if (host == null ? void 0 : host.getBuildInfo) { - buildInfo = host.getBuildInfo(buildInfoPath, options.configFilePath) ?? false; + var _host$getBuildInfo; + buildInfo = (_host$getBuildInfo = host.getBuildInfo(buildInfoPath, options.configFilePath)) !== null && _host$getBuildInfo !== void 0 ? _host$getBuildInfo : false; } else { + var _getBuildInfo; const result = textGetter(buildInfoPath); - buildInfo = result !== void 0 ? getBuildInfo(buildInfoPath, result) ?? false : false; + buildInfo = result !== void 0 ? (_getBuildInfo = getBuildInfo(buildInfoPath, result)) !== null && _getBuildInfo !== void 0 ? _getBuildInfo : false : false; } } return buildInfo || void 0; }; Object.defineProperties(node, { - javascriptText: { get: () => definedTextGetter(javascriptPath) }, - javascriptMapText: { get: () => textGetter(javascriptMapPath) }, + javascriptText: { + get: () => definedTextGetter(javascriptPath) + }, + javascriptMapText: { + get: () => textGetter(javascriptMapPath) + }, // TODO:: if there is inline sourceMap in jsFile, use that - declarationText: { get: () => definedTextGetter(Debug.checkDefined(declarationPath)) }, - declarationMapText: { get: () => textGetter(declarationMapPath) }, + declarationText: { + get: () => definedTextGetter(Debug.checkDefined(declarationPath)) + }, + declarationMapText: { + get: () => textGetter(declarationMapPath) + }, // TODO:: if there is inline sourceMap in dtsFile, use that - buildInfo: { get: getAndCacheBuildInfo } + buildInfo: { + get: getAndCacheBuildInfo + } }); return node; } @@ -24821,8 +24122,7 @@ ${lanes.join("\n")} 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; @@ -24843,14 +24143,14 @@ ${lanes.join("\n")} classThis, assignedName } = sourceEmitNode; - if (!destEmitNode) - destEmitNode = {}; + if (!destEmitNode) destEmitNode = {}; if (flags) { destEmitNode.flags = flags; } if (internalFlags) { destEmitNode.internalFlags = internalFlags & ~8 /* Immutable */; } + if (leadingComments) { destEmitNode.leadingComments = addRange(leadingComments.slice(), destEmitNode.leadingComments); } @@ -24889,8 +24189,7 @@ ${lanes.join("\n")} return destEmitNode; } function mergeTokenSourceMapRanges(sourceRanges, destRanges) { - if (!destRanges) - destRanges = []; + if (!destRanges) destRanges = []; for (const key in sourceRanges) { destRanges[key] = sourceRanges[key]; } @@ -24900,9 +24199,10 @@ ${lanes.join("\n")} var init_nodeFactory = __esm({ "src/compiler/factory/nodeFactory.ts"() { "use strict"; + init_ts2(); nextAutoGenerateId = 0; - NodeFactoryFlags = /* @__PURE__ */ ((NodeFactoryFlags2) => { + NodeFactoryFlags = /* @__PURE__ */(NodeFactoryFlags2 => { NodeFactoryFlags2[NodeFactoryFlags2["None"] = 0] = "None"; NodeFactoryFlags2[NodeFactoryFlags2["NoParenthesizerRules"] = 1] = "NoParenthesizerRules"; NodeFactoryFlags2[NodeFactoryFlags2["NoNodeConverters"] = 2] = "NoNodeConverters"; @@ -24914,11 +24214,11 @@ ${lanes.join("\n")} invalidValueSentinel = {}; baseFactory = createBaseNodeFactory(); syntheticFactory = { - createBaseSourceFileNode: (kind) => makeSynthetic(baseFactory.createBaseSourceFileNode(kind)), - createBaseIdentifierNode: (kind) => makeSynthetic(baseFactory.createBaseIdentifierNode(kind)), - createBasePrivateIdentifierNode: (kind) => makeSynthetic(baseFactory.createBasePrivateIdentifierNode(kind)), - createBaseTokenNode: (kind) => makeSynthetic(baseFactory.createBaseTokenNode(kind)), - createBaseNode: (kind) => makeSynthetic(baseFactory.createBaseNode(kind)) + createBaseSourceFileNode: kind => makeSynthetic(baseFactory.createBaseSourceFileNode(kind)), + createBaseIdentifierNode: kind => makeSynthetic(baseFactory.createBaseIdentifierNode(kind)), + createBasePrivateIdentifierNode: kind => makeSynthetic(baseFactory.createBasePrivateIdentifierNode(kind)), + createBaseTokenNode: kind => makeSynthetic(baseFactory.createBaseTokenNode(kind)), + createBaseNode: kind => makeSynthetic(baseFactory.createBaseNode(kind)) }; factory = createNodeFactory(4 /* NoIndentationOnFreshPropertyAccess */, syntheticFactory); } @@ -24928,10 +24228,13 @@ ${lanes.join("\n")} function getOrCreateEmitNode(node) { if (!node.emitNode) { if (isParseTreeNode(node)) { + var _getSourceFileOfNode; if (node.kind === 312 /* SourceFile */) { - return node.emitNode = { annotatedNodes: [node] }; + return node.emitNode = { + annotatedNodes: [node] + }; } - const sourceFile = getSourceFileOfNode(getParseTreeNode(getSourceFileOfNode(node))) ?? Debug.fail("Could not determine parsed source file."); + const sourceFile = (_getSourceFileOfNode = getSourceFileOfNode(getParseTreeNode(getSourceFileOfNode(node)))) !== null && _getSourceFileOfNode !== void 0 ? _getSourceFileOfNode : Debug.fail("Could not determine parsed source file."); getOrCreateEmitNode(sourceFile).annotatedNodes.push(node); } node.emitNode = {}; @@ -24975,8 +24278,9 @@ ${lanes.join("\n")} return node; } function getSourceMapRange(node) { + var _ref6; var _a; - return ((_a = node.emitNode) == null ? void 0 : _a.sourceMapRange) ?? node; + return (_ref6 = (_a = node.emitNode) == null ? void 0 : _a.sourceMapRange) !== null && _ref6 !== void 0 ? _ref6 : node; } function setSourceMapRange(node, range) { getOrCreateEmitNode(node).sourceMapRange = range; @@ -24987,8 +24291,9 @@ ${lanes.join("\n")} return (_b = (_a = node.emitNode) == null ? void 0 : _a.tokenSourceMapRanges) == null ? void 0 : _b[token]; } function setTokenSourceMapRange(node, token, range) { + var _emitNode$tokenSource; const emitNode = getOrCreateEmitNode(node); - const tokenSourceMapRanges = emitNode.tokenSourceMapRanges ?? (emitNode.tokenSourceMapRanges = []); + const tokenSourceMapRanges = (_emitNode$tokenSource = emitNode.tokenSourceMapRanges) !== null && _emitNode$tokenSource !== void 0 ? _emitNode$tokenSource : emitNode.tokenSourceMapRanges = []; tokenSourceMapRanges[token] = range; return node; } @@ -25001,8 +24306,9 @@ ${lanes.join("\n")} return node; } function getCommentRange(node) { + var _ref7; var _a; - return ((_a = node.emitNode) == null ? void 0 : _a.commentRange) ?? node; + return (_ref7 = (_a = node.emitNode) == null ? void 0 : _a.commentRange) !== null && _ref7 !== void 0 ? _ref7 : node; } function setCommentRange(node, range) { getOrCreateEmitNode(node).commentRange = range; @@ -25017,7 +24323,13 @@ ${lanes.join("\n")} return node; } function addSyntheticLeadingComment(node, kind, text, hasTrailingNewLine) { - return setSyntheticLeadingComments(node, append(getSyntheticLeadingComments(node), { kind, pos: -1, end: -1, hasTrailingNewLine, text })); + return setSyntheticLeadingComments(node, append(getSyntheticLeadingComments(node), { + kind, + pos: -1, + end: -1, + hasTrailingNewLine, + text + })); } function getSyntheticTrailingComments(node) { var _a; @@ -25028,7 +24340,13 @@ ${lanes.join("\n")} return node; } function addSyntheticTrailingComment(node, kind, text, hasTrailingNewLine) { - return setSyntheticTrailingComments(node, append(getSyntheticTrailingComments(node), { kind, pos: -1, end: -1, hasTrailingNewLine, text })); + return setSyntheticTrailingComments(node, append(getSyntheticTrailingComments(node), { + kind, + pos: -1, + end: -1, + hasTrailingNewLine, + text + })); } function moveSyntheticComments(node, original) { setSyntheticLeadingComments(node, getSyntheticLeadingComments(original)); @@ -25076,8 +24394,7 @@ ${lanes.join("\n")} 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++) { @@ -25142,6 +24459,7 @@ ${lanes.join("\n")} var init_emitNode = __esm({ "src/compiler/factory/emitNode.ts"() { "use strict"; + init_ts2(); } }); @@ -25198,14 +24516,12 @@ ${lanes.join("\n")} function getUnscopedHelperName(name) { return setEmitFlags(factory2.createIdentifier(name), 8192 /* HelperName */ | 4 /* AdviseOnEmitNode */); } + function createDecorateHelper(decoratorExpressions, target, memberName, descriptor) { context.requestEmitHelper(decorateHelper); const argumentsArray = []; - argumentsArray.push(factory2.createArrayLiteralExpression( - decoratorExpressions, - /*multiLine*/ - true - )); + argumentsArray.push(factory2.createArrayLiteralExpression(decoratorExpressions, /*multiLine*/ + true)); argumentsArray.push(target); if (memberName) { argumentsArray.push(memberName); @@ -25213,158 +24529,64 @@ ${lanes.join("\n")} argumentsArray.push(descriptor); } } - return factory2.createCallExpression( - getUnscopedHelperName("__decorate"), - /*typeArguments*/ - void 0, - argumentsArray - ); + return factory2.createCallExpression(getUnscopedHelperName("__decorate"), /*typeArguments*/ + void 0, argumentsArray); } function createMetadataHelper(metadataKey, metadataValue) { context.requestEmitHelper(metadataHelper); - return factory2.createCallExpression( - getUnscopedHelperName("__metadata"), - /*typeArguments*/ - void 0, - [ - factory2.createStringLiteral(metadataKey), - metadataValue - ] - ); + return factory2.createCallExpression(getUnscopedHelperName("__metadata"), /*typeArguments*/ + void 0, [factory2.createStringLiteral(metadataKey), metadataValue]); } function createParamHelper(expression, parameterOffset, location) { context.requestEmitHelper(paramHelper); - return setTextRange( - factory2.createCallExpression( - getUnscopedHelperName("__param"), - /*typeArguments*/ - void 0, - [ - factory2.createNumericLiteral(parameterOffset + ""), - expression - ] - ), - location - ); + return setTextRange(factory2.createCallExpression(getUnscopedHelperName("__param"), /*typeArguments*/ + void 0, [factory2.createNumericLiteral(parameterOffset + ""), expression]), location); } function createESDecorateClassContextObject(contextIn) { - const properties = [ - factory2.createPropertyAssignment(factory2.createIdentifier("kind"), factory2.createStringLiteral("class")), - factory2.createPropertyAssignment(factory2.createIdentifier("name"), contextIn.name), - factory2.createPropertyAssignment(factory2.createIdentifier("metadata"), contextIn.metadata) - ]; + const properties = [factory2.createPropertyAssignment(factory2.createIdentifier("kind"), factory2.createStringLiteral("class")), factory2.createPropertyAssignment(factory2.createIdentifier("name"), contextIn.name), factory2.createPropertyAssignment(factory2.createIdentifier("metadata"), contextIn.metadata)]; return factory2.createObjectLiteralExpression(properties); } function createESDecorateClassElementAccessGetMethod(elementName) { const accessor = elementName.computed ? factory2.createElementAccessExpression(factory2.createIdentifier("obj"), elementName.name) : factory2.createPropertyAccessExpression(factory2.createIdentifier("obj"), elementName.name); - return factory2.createPropertyAssignment( - "get", - factory2.createArrowFunction( - /*modifiers*/ - void 0, - /*typeParameters*/ - void 0, - [factory2.createParameterDeclaration( - /*modifiers*/ - void 0, - /*dotDotDotToken*/ - void 0, - factory2.createIdentifier("obj") - )], - /*type*/ - void 0, - /*equalsGreaterThanToken*/ - void 0, - accessor - ) - ); + return factory2.createPropertyAssignment("get", factory2.createArrowFunction( /*modifiers*/ + void 0, /*typeParameters*/ + void 0, [factory2.createParameterDeclaration( /*modifiers*/ + void 0, /*dotDotDotToken*/ + void 0, factory2.createIdentifier("obj"))], /*type*/ + void 0, /*equalsGreaterThanToken*/ + void 0, accessor)); } function createESDecorateClassElementAccessSetMethod(elementName) { const accessor = elementName.computed ? factory2.createElementAccessExpression(factory2.createIdentifier("obj"), elementName.name) : factory2.createPropertyAccessExpression(factory2.createIdentifier("obj"), elementName.name); - return factory2.createPropertyAssignment( - "set", - factory2.createArrowFunction( - /*modifiers*/ - void 0, - /*typeParameters*/ - void 0, - [ - factory2.createParameterDeclaration( - /*modifiers*/ - void 0, - /*dotDotDotToken*/ - void 0, - factory2.createIdentifier("obj") - ), - factory2.createParameterDeclaration( - /*modifiers*/ - void 0, - /*dotDotDotToken*/ - void 0, - factory2.createIdentifier("value") - ) - ], - /*type*/ - void 0, - /*equalsGreaterThanToken*/ - void 0, - factory2.createBlock([ - factory2.createExpressionStatement( - factory2.createAssignment( - accessor, - factory2.createIdentifier("value") - ) - ) - ]) - ) - ); + return factory2.createPropertyAssignment("set", factory2.createArrowFunction( /*modifiers*/ + void 0, /*typeParameters*/ + void 0, [factory2.createParameterDeclaration( /*modifiers*/ + void 0, /*dotDotDotToken*/ + void 0, factory2.createIdentifier("obj")), factory2.createParameterDeclaration( /*modifiers*/ + void 0, /*dotDotDotToken*/ + void 0, factory2.createIdentifier("value"))], /*type*/ + void 0, /*equalsGreaterThanToken*/ + void 0, factory2.createBlock([factory2.createExpressionStatement(factory2.createAssignment(accessor, factory2.createIdentifier("value")))]))); } function createESDecorateClassElementAccessHasMethod(elementName) { const propertyName = elementName.computed ? elementName.name : isIdentifier(elementName.name) ? factory2.createStringLiteralFromNode(elementName.name) : elementName.name; - return factory2.createPropertyAssignment( - "has", - factory2.createArrowFunction( - /*modifiers*/ - void 0, - /*typeParameters*/ - void 0, - [factory2.createParameterDeclaration( - /*modifiers*/ - void 0, - /*dotDotDotToken*/ - void 0, - factory2.createIdentifier("obj") - )], - /*type*/ - void 0, - /*equalsGreaterThanToken*/ - void 0, - factory2.createBinaryExpression( - propertyName, - 103 /* InKeyword */, - factory2.createIdentifier("obj") - ) - ) - ); + return factory2.createPropertyAssignment("has", factory2.createArrowFunction( /*modifiers*/ + void 0, /*typeParameters*/ + void 0, [factory2.createParameterDeclaration( /*modifiers*/ + void 0, /*dotDotDotToken*/ + void 0, factory2.createIdentifier("obj"))], /*type*/ + void 0, /*equalsGreaterThanToken*/ + void 0, factory2.createBinaryExpression(propertyName, 103 /* InKeyword */, factory2.createIdentifier("obj")))); } 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) { - const properties = [ - factory2.createPropertyAssignment(factory2.createIdentifier("kind"), factory2.createStringLiteral(contextIn.kind)), - factory2.createPropertyAssignment(factory2.createIdentifier("name"), contextIn.name.computed ? contextIn.name.name : factory2.createStringLiteralFromNode(contextIn.name.name)), - factory2.createPropertyAssignment(factory2.createIdentifier("static"), contextIn.static ? factory2.createTrue() : factory2.createFalse()), - factory2.createPropertyAssignment(factory2.createIdentifier("private"), contextIn.private ? factory2.createTrue() : factory2.createFalse()), - factory2.createPropertyAssignment(factory2.createIdentifier("access"), createESDecorateClassElementAccessObject(contextIn.name, contextIn.access)), - factory2.createPropertyAssignment(factory2.createIdentifier("metadata"), contextIn.metadata) - ]; + const properties = [factory2.createPropertyAssignment(factory2.createIdentifier("kind"), factory2.createStringLiteral(contextIn.kind)), factory2.createPropertyAssignment(factory2.createIdentifier("name"), contextIn.name.computed ? contextIn.name.name : factory2.createStringLiteralFromNode(contextIn.name.name)), factory2.createPropertyAssignment(factory2.createIdentifier("static"), contextIn.static ? factory2.createTrue() : factory2.createFalse()), factory2.createPropertyAssignment(factory2.createIdentifier("private"), contextIn.private ? factory2.createTrue() : factory2.createFalse()), factory2.createPropertyAssignment(factory2.createIdentifier("access"), createESDecorateClassElementAccessObject(contextIn.name, contextIn.access)), factory2.createPropertyAssignment(factory2.createIdentifier("metadata"), contextIn.metadata)]; return factory2.createObjectLiteralExpression(properties); } function createESDecorateContextObject(contextIn) { @@ -25372,88 +24594,45 @@ ${lanes.join("\n")} } function createESDecorateHelper(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) { context.requestEmitHelper(esDecorateHelper); - return factory2.createCallExpression( - getUnscopedHelperName("__esDecorate"), - /*typeArguments*/ - void 0, - [ - ctor ?? factory2.createNull(), - descriptorIn ?? factory2.createNull(), - decorators, - createESDecorateContextObject(contextIn), - initializers, - extraInitializers - ] - ); + return factory2.createCallExpression(getUnscopedHelperName("__esDecorate"), /*typeArguments*/ + void 0, [ctor !== null && ctor !== void 0 ? ctor : factory2.createNull(), descriptorIn !== null && descriptorIn !== void 0 ? descriptorIn : factory2.createNull(), decorators, createESDecorateContextObject(contextIn), initializers, extraInitializers]); } function createRunInitializersHelper(thisArg, initializers, value) { context.requestEmitHelper(runInitializersHelper); - return factory2.createCallExpression( - getUnscopedHelperName("__runInitializers"), - /*typeArguments*/ - void 0, - value ? [thisArg, initializers, value] : [thisArg, initializers] - ); + return factory2.createCallExpression(getUnscopedHelperName("__runInitializers"), /*typeArguments*/ + void 0, value ? [thisArg, initializers, value] : [thisArg, initializers]); } function createAssignHelper(attributesSegments) { if (getEmitScriptTarget(context.getCompilerOptions()) >= 2 /* ES2015 */) { - return factory2.createCallExpression( - factory2.createPropertyAccessExpression(factory2.createIdentifier("Object"), "assign"), - /*typeArguments*/ - void 0, - attributesSegments - ); + return factory2.createCallExpression(factory2.createPropertyAccessExpression(factory2.createIdentifier("Object"), "assign"), /*typeArguments*/ + void 0, attributesSegments); } context.requestEmitHelper(assignHelper); - return factory2.createCallExpression( - getUnscopedHelperName("__assign"), - /*typeArguments*/ - void 0, - attributesSegments - ); + return factory2.createCallExpression(getUnscopedHelperName("__assign"), /*typeArguments*/ + void 0, attributesSegments); } function createAwaitHelper(expression) { context.requestEmitHelper(awaitHelper); - return factory2.createCallExpression( - getUnscopedHelperName("__await"), - /*typeArguments*/ - void 0, - [expression] - ); + return factory2.createCallExpression(getUnscopedHelperName("__await"), /*typeArguments*/ + void 0, [expression]); } function createAsyncGeneratorHelper(generatorFunc, hasLexicalThis) { context.requestEmitHelper(awaitHelper); context.requestEmitHelper(asyncGeneratorHelper); (generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 524288 /* AsyncFunctionBody */ | 1048576 /* ReuseTempVariableScope */; - return factory2.createCallExpression( - getUnscopedHelperName("__asyncGenerator"), - /*typeArguments*/ - void 0, - [ - hasLexicalThis ? factory2.createThis() : factory2.createVoidZero(), - factory2.createIdentifier("arguments"), - generatorFunc - ] - ); + return factory2.createCallExpression(getUnscopedHelperName("__asyncGenerator"), /*typeArguments*/ + void 0, [hasLexicalThis ? factory2.createThis() : factory2.createVoidZero(), factory2.createIdentifier("arguments"), generatorFunc]); } function createAsyncDelegatorHelper(expression) { context.requestEmitHelper(awaitHelper); context.requestEmitHelper(asyncDelegator); - return factory2.createCallExpression( - getUnscopedHelperName("__asyncDelegator"), - /*typeArguments*/ - void 0, - [expression] - ); + return factory2.createCallExpression(getUnscopedHelperName("__asyncDelegator"), /*typeArguments*/ + void 0, [expression]); } function createAsyncValuesHelper(expression) { context.requestEmitHelper(asyncValues); - return factory2.createCallExpression( - getUnscopedHelperName("__asyncValues"), - /*typeArguments*/ - void 0, - [expression] - ); + return factory2.createCallExpression(getUnscopedHelperName("__asyncValues"), /*typeArguments*/ + void 0, [expression]); } function createRestHelper(value, elements, computedTempVariables, location) { context.requestEmitHelper(restHelper); @@ -25466,153 +24645,79 @@ ${lanes.join("\n")} Debug.assertIsDefined(computedTempVariables, "Encountered computed property name but 'computedTempVariables' argument was not provided."); const temp = computedTempVariables[computedTempVariableOffset]; computedTempVariableOffset++; - propertyNames.push( - factory2.createConditionalExpression( - factory2.createTypeCheck(temp, "symbol"), - /*questionToken*/ - void 0, - temp, - /*colonToken*/ - void 0, - factory2.createAdd(temp, factory2.createStringLiteral("")) - ) - ); + propertyNames.push(factory2.createConditionalExpression(factory2.createTypeCheck(temp, "symbol"), /*questionToken*/ + void 0, temp, /*colonToken*/ + void 0, factory2.createAdd(temp, factory2.createStringLiteral("")))); } else { propertyNames.push(factory2.createStringLiteralFromNode(propertyName)); } } } - return factory2.createCallExpression( - getUnscopedHelperName("__rest"), - /*typeArguments*/ - void 0, - [ - value, - setTextRange( - factory2.createArrayLiteralExpression(propertyNames), - location - ) - ] - ); + return factory2.createCallExpression(getUnscopedHelperName("__rest"), /*typeArguments*/ + void 0, [value, setTextRange(factory2.createArrayLiteralExpression(propertyNames), location)]); } function createAwaiterHelper(hasLexicalThis, hasLexicalArguments, promiseConstructor, body) { context.requestEmitHelper(awaiterHelper); - const generatorFunc = factory2.createFunctionExpression( - /*modifiers*/ - void 0, - factory2.createToken(42 /* AsteriskToken */), - /*name*/ - void 0, - /*typeParameters*/ - void 0, - /*parameters*/ - [], - /*type*/ - void 0, - body - ); + const generatorFunc = factory2.createFunctionExpression( /*modifiers*/ + void 0, factory2.createToken(42 /* AsteriskToken */), /*name*/ + void 0, /*typeParameters*/ + void 0, /*parameters*/ + [], /*type*/ + void 0, body); (generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 524288 /* AsyncFunctionBody */ | 1048576 /* ReuseTempVariableScope */; - return factory2.createCallExpression( - getUnscopedHelperName("__awaiter"), - /*typeArguments*/ - void 0, - [ - hasLexicalThis ? factory2.createThis() : factory2.createVoidZero(), - hasLexicalArguments ? factory2.createIdentifier("arguments") : factory2.createVoidZero(), - promiseConstructor ? createExpressionFromEntityName(factory2, promiseConstructor) : factory2.createVoidZero(), - generatorFunc - ] - ); + return factory2.createCallExpression(getUnscopedHelperName("__awaiter"), /*typeArguments*/ + void 0, [hasLexicalThis ? factory2.createThis() : factory2.createVoidZero(), hasLexicalArguments ? factory2.createIdentifier("arguments") : factory2.createVoidZero(), promiseConstructor ? createExpressionFromEntityName(factory2, promiseConstructor) : factory2.createVoidZero(), generatorFunc]); } function createExtendsHelper(name) { context.requestEmitHelper(extendsHelper); - return factory2.createCallExpression( - getUnscopedHelperName("__extends"), - /*typeArguments*/ - void 0, - [name, factory2.createUniqueName("_super", 16 /* Optimistic */ | 32 /* FileLevel */)] - ); + return factory2.createCallExpression(getUnscopedHelperName("__extends"), /*typeArguments*/ + void 0, [name, factory2.createUniqueName("_super", 16 /* Optimistic */ | 32 /* FileLevel */)]); } + function createTemplateObjectHelper(cooked, raw) { context.requestEmitHelper(templateObjectHelper); - return factory2.createCallExpression( - getUnscopedHelperName("__makeTemplateObject"), - /*typeArguments*/ - void 0, - [cooked, raw] - ); + return factory2.createCallExpression(getUnscopedHelperName("__makeTemplateObject"), /*typeArguments*/ + void 0, [cooked, raw]); } function createSpreadArrayHelper(to, from, packFrom) { context.requestEmitHelper(spreadArrayHelper); - return factory2.createCallExpression( - getUnscopedHelperName("__spreadArray"), - /*typeArguments*/ - void 0, - [to, from, packFrom ? immutableTrue() : immutableFalse()] - ); + return factory2.createCallExpression(getUnscopedHelperName("__spreadArray"), /*typeArguments*/ + void 0, [to, from, packFrom ? immutableTrue() : immutableFalse()]); } function createPropKeyHelper(expr) { context.requestEmitHelper(propKeyHelper); - return factory2.createCallExpression( - getUnscopedHelperName("__propKey"), - /*typeArguments*/ - void 0, - [expr] - ); + return factory2.createCallExpression(getUnscopedHelperName("__propKey"), /*typeArguments*/ + void 0, [expr]); } function createSetFunctionNameHelper(f, name, prefix) { context.requestEmitHelper(setFunctionNameHelper); - return context.factory.createCallExpression( - getUnscopedHelperName("__setFunctionName"), - /*typeArguments*/ - void 0, - prefix ? [f, name, context.factory.createStringLiteral(prefix)] : [f, name] - ); + return context.factory.createCallExpression(getUnscopedHelperName("__setFunctionName"), /*typeArguments*/ + void 0, prefix ? [f, name, context.factory.createStringLiteral(prefix)] : [f, name]); } function createValuesHelper(expression) { context.requestEmitHelper(valuesHelper); - return factory2.createCallExpression( - getUnscopedHelperName("__values"), - /*typeArguments*/ - void 0, - [expression] - ); + return factory2.createCallExpression(getUnscopedHelperName("__values"), /*typeArguments*/ + void 0, [expression]); } function createReadHelper(iteratorRecord, count) { context.requestEmitHelper(readHelper); - return factory2.createCallExpression( - getUnscopedHelperName("__read"), - /*typeArguments*/ - void 0, - count !== void 0 ? [iteratorRecord, factory2.createNumericLiteral(count + "")] : [iteratorRecord] - ); + return factory2.createCallExpression(getUnscopedHelperName("__read"), /*typeArguments*/ + void 0, count !== void 0 ? [iteratorRecord, factory2.createNumericLiteral(count + "")] : [iteratorRecord]); } function createGeneratorHelper(body) { context.requestEmitHelper(generatorHelper); - return factory2.createCallExpression( - getUnscopedHelperName("__generator"), - /*typeArguments*/ - void 0, - [factory2.createThis(), body] - ); + return factory2.createCallExpression(getUnscopedHelperName("__generator"), /*typeArguments*/ + void 0, [factory2.createThis(), body]); } function createCreateBindingHelper(module2, inputName, outputName) { context.requestEmitHelper(createBindingHelper); - return factory2.createCallExpression( - getUnscopedHelperName("__createBinding"), - /*typeArguments*/ - void 0, - [factory2.createIdentifier("exports"), module2, inputName, ...outputName ? [outputName] : []] - ); + return factory2.createCallExpression(getUnscopedHelperName("__createBinding"), /*typeArguments*/ + void 0, [factory2.createIdentifier("exports"), module2, inputName, ...(outputName ? [outputName] : [])]); } function createImportStarHelper(expression) { context.requestEmitHelper(importStarHelper); - return factory2.createCallExpression( - getUnscopedHelperName("__importStar"), - /*typeArguments*/ - void 0, - [expression] - ); + return factory2.createCallExpression(getUnscopedHelperName("__importStar"), /*typeArguments*/ + void 0, [expression]); } function createImportStarCallbackHelper() { context.requestEmitHelper(importStarHelper); @@ -25620,22 +24725,14 @@ ${lanes.join("\n")} } function createImportDefaultHelper(expression) { context.requestEmitHelper(importDefaultHelper); - return factory2.createCallExpression( - getUnscopedHelperName("__importDefault"), - /*typeArguments*/ - void 0, - [expression] - ); + return factory2.createCallExpression(getUnscopedHelperName("__importDefault"), /*typeArguments*/ + void 0, [expression]); } function createExportStarHelper(moduleExpression, exportsExpression = factory2.createIdentifier("exports")) { context.requestEmitHelper(exportStarHelper); context.requestEmitHelper(createBindingHelper); - return factory2.createCallExpression( - getUnscopedHelperName("__exportStar"), - /*typeArguments*/ - void 0, - [moduleExpression, exportsExpression] - ); + return factory2.createCallExpression(getUnscopedHelperName("__exportStar"), /*typeArguments*/ + void 0, [moduleExpression, exportsExpression]); } function createClassPrivateFieldGetHelper(receiver, state, kind, f) { context.requestEmitHelper(classPrivateFieldGetHelper); @@ -25645,12 +24742,8 @@ ${lanes.join("\n")} } else { args = [receiver, state, factory2.createStringLiteral(kind), f]; } - return factory2.createCallExpression( - getUnscopedHelperName("__classPrivateFieldGet"), - /*typeArguments*/ - void 0, - args - ); + return factory2.createCallExpression(getUnscopedHelperName("__classPrivateFieldGet"), /*typeArguments*/ + void 0, args); } function createClassPrivateFieldSetHelper(receiver, state, value, kind, f) { context.requestEmitHelper(classPrivateFieldSetHelper); @@ -25660,54 +24753,34 @@ ${lanes.join("\n")} } else { args = [receiver, state, value, factory2.createStringLiteral(kind), f]; } - return factory2.createCallExpression( - getUnscopedHelperName("__classPrivateFieldSet"), - /*typeArguments*/ - void 0, - args - ); + return factory2.createCallExpression(getUnscopedHelperName("__classPrivateFieldSet"), /*typeArguments*/ + void 0, args); } function createClassPrivateFieldInHelper(state, receiver) { context.requestEmitHelper(classPrivateFieldInHelper); - return factory2.createCallExpression( - getUnscopedHelperName("__classPrivateFieldIn"), - /*typeArguments*/ - void 0, - [state, receiver] - ); + return factory2.createCallExpression(getUnscopedHelperName("__classPrivateFieldIn"), /*typeArguments*/ + void 0, [state, receiver]); } function createAddDisposableResourceHelper(envBinding, value, async) { context.requestEmitHelper(addDisposableResourceHelper); - return factory2.createCallExpression( - getUnscopedHelperName("__addDisposableResource"), - /*typeArguments*/ - void 0, - [envBinding, value, async ? factory2.createTrue() : factory2.createFalse()] - ); + return factory2.createCallExpression(getUnscopedHelperName("__addDisposableResource"), /*typeArguments*/ + void 0, [envBinding, value, async ? factory2.createTrue() : factory2.createFalse()]); } function createDisposeResourcesHelper(envBinding) { context.requestEmitHelper(disposeResourcesHelper); - return factory2.createCallExpression( - getUnscopedHelperName("__disposeResources"), - /*typeArguments*/ - void 0, - [envBinding] - ); + return factory2.createCallExpression(getUnscopedHelperName("__disposeResources"), /*typeArguments*/ + void 0, [envBinding]); } } 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) { - return (uniqueName) => { + return uniqueName => { let result = ""; for (let i = 0; i < args.length; i++) { result += input[i]; @@ -25718,38 +24791,7 @@ ${lanes.join("\n")} }; } function getAllUnscopedEmitHelpers() { - return allUnscopedEmitHelpers || (allUnscopedEmitHelpers = arrayToMap([ - decorateHelper, - metadataHelper, - paramHelper, - esDecorateHelper, - runInitializersHelper, - assignHelper, - awaitHelper, - asyncGeneratorHelper, - asyncDelegator, - asyncValues, - restHelper, - awaiterHelper, - extendsHelper, - templateObjectHelper, - spreadArrayHelper, - valuesHelper, - readHelper, - propKeyHelper, - setFunctionNameHelper, - generatorHelper, - importStarHelper, - importDefaultHelper, - exportStarHelper, - classPrivateFieldGetHelper, - classPrivateFieldSetHelper, - classPrivateFieldInHelper, - createBindingHelper, - setModuleDefaultHelper, - addDisposableResourceHelper, - disposeResourcesHelper - ], (helper) => helper.name)); + return allUnscopedEmitHelpers || (allUnscopedEmitHelpers = arrayToMap([decorateHelper, metadataHelper, paramHelper, esDecorateHelper, runInitializersHelper, assignHelper, awaitHelper, asyncGeneratorHelper, asyncDelegator, asyncValues, restHelper, awaiterHelper, extendsHelper, templateObjectHelper, spreadArrayHelper, valuesHelper, readHelper, propKeyHelper, setFunctionNameHelper, generatorHelper, importStarHelper, importDefaultHelper, exportStarHelper, classPrivateFieldGetHelper, classPrivateFieldSetHelper, classPrivateFieldInHelper, createBindingHelper, setModuleDefaultHelper, addDisposableResourceHelper, disposeResourcesHelper], helper => helper.name)); } function isCallToHelper(firstSegment, helperName) { return isCallExpression(firstSegment) && isIdentifier(firstSegment.expression) && (getEmitFlags(firstSegment.expression) & 8192 /* HelperName */) !== 0 && firstSegment.expression.escapedText === helperName; @@ -25758,8 +24800,9 @@ ${lanes.join("\n")} var init_emitHelpers = __esm({ "src/compiler/factory/emitHelpers.ts"() { "use strict"; + init_ts2(); - PrivateIdentifierKind = /* @__PURE__ */ ((PrivateIdentifierKind2) => { + PrivateIdentifierKind = /* @__PURE__ */(PrivateIdentifierKind2 => { PrivateIdentifierKind2["Field"] = "f"; PrivateIdentifierKind2["Method"] = "m"; PrivateIdentifierKind2["Accessor"] = "a"; @@ -26266,711 +25309,931 @@ ${lanes.join("\n")} function isNumericLiteral(node) { return node.kind === 9 /* NumericLiteral */; } + function isBigIntLiteral(node) { return node.kind === 10 /* BigIntLiteral */; } + function isStringLiteral(node) { return node.kind === 11 /* StringLiteral */; } + function isJsxText(node) { return node.kind === 12 /* JsxText */; } + function isRegularExpressionLiteral(node) { return node.kind === 14 /* RegularExpressionLiteral */; } + function isNoSubstitutionTemplateLiteral(node) { return node.kind === 15 /* NoSubstitutionTemplateLiteral */; } + function isTemplateHead(node) { return node.kind === 16 /* TemplateHead */; } + function isTemplateMiddle(node) { return node.kind === 17 /* TemplateMiddle */; } + function isTemplateTail(node) { return node.kind === 18 /* TemplateTail */; } + function isDotDotDotToken(node) { return node.kind === 26 /* DotDotDotToken */; } + function isCommaToken(node) { return node.kind === 28 /* CommaToken */; } + function isPlusToken(node) { return node.kind === 40 /* PlusToken */; } + function isMinusToken(node) { return node.kind === 41 /* MinusToken */; } + function isAsteriskToken(node) { return node.kind === 42 /* AsteriskToken */; } + function isExclamationToken(node) { return node.kind === 54 /* ExclamationToken */; } + function isQuestionToken(node) { return node.kind === 58 /* QuestionToken */; } + function isColonToken(node) { return node.kind === 59 /* ColonToken */; } + function isQuestionDotToken(node) { return node.kind === 29 /* QuestionDotToken */; } + function isEqualsGreaterThanToken(node) { return node.kind === 39 /* EqualsGreaterThanToken */; } + function isIdentifier(node) { return node.kind === 80 /* Identifier */; } + function isPrivateIdentifier(node) { return node.kind === 81 /* PrivateIdentifier */; } + function isExportModifier(node) { return node.kind === 95 /* ExportKeyword */; } + function isDefaultModifier(node) { return node.kind === 90 /* DefaultKeyword */; } + function isAsyncModifier(node) { return node.kind === 134 /* AsyncKeyword */; } + function isAssertsKeyword(node) { return node.kind === 131 /* AssertsKeyword */; } + function isAwaitKeyword(node) { return node.kind === 135 /* AwaitKeyword */; } + function isReadonlyKeyword(node) { return node.kind === 148 /* ReadonlyKeyword */; } + function isStaticModifier(node) { return node.kind === 126 /* StaticKeyword */; } + function isAbstractModifier(node) { return node.kind === 128 /* AbstractKeyword */; } + function isOverrideModifier(node) { return node.kind === 164 /* OverrideKeyword */; } + function isAccessorModifier(node) { return node.kind === 129 /* AccessorKeyword */; } + function isSuperKeyword(node) { return node.kind === 108 /* SuperKeyword */; } + function isImportKeyword(node) { return node.kind === 102 /* ImportKeyword */; } + function isCaseKeyword(node) { return node.kind === 84 /* CaseKeyword */; } + function isQualifiedName(node) { return node.kind === 166 /* QualifiedName */; } + function isComputedPropertyName(node) { return node.kind === 167 /* ComputedPropertyName */; } + function isTypeParameterDeclaration(node) { return node.kind === 168 /* TypeParameter */; } + function isParameter(node) { return node.kind === 169 /* Parameter */; } + function isDecorator(node) { return node.kind === 170 /* Decorator */; } + function isPropertySignature(node) { return node.kind === 171 /* PropertySignature */; } + function isPropertyDeclaration(node) { return node.kind === 172 /* PropertyDeclaration */; } + function isMethodSignature(node) { return node.kind === 173 /* MethodSignature */; } + function isMethodDeclaration(node) { return node.kind === 174 /* MethodDeclaration */; } + function isClassStaticBlockDeclaration(node) { return node.kind === 175 /* ClassStaticBlockDeclaration */; } + function isConstructorDeclaration(node) { return node.kind === 176 /* Constructor */; } + function isGetAccessorDeclaration(node) { return node.kind === 177 /* GetAccessor */; } + function isSetAccessorDeclaration(node) { return node.kind === 178 /* SetAccessor */; } + function isCallSignatureDeclaration(node) { return node.kind === 179 /* CallSignature */; } + function isConstructSignatureDeclaration(node) { return node.kind === 180 /* ConstructSignature */; } + function isIndexSignatureDeclaration(node) { return node.kind === 181 /* IndexSignature */; } + function isTypePredicateNode(node) { return node.kind === 182 /* TypePredicate */; } + function isTypeReferenceNode(node) { return node.kind === 183 /* TypeReference */; } + function isFunctionTypeNode(node) { return node.kind === 184 /* FunctionType */; } + function isConstructorTypeNode(node) { return node.kind === 185 /* ConstructorType */; } + function isTypeQueryNode(node) { return node.kind === 186 /* TypeQuery */; } + function isTypeLiteralNode(node) { return node.kind === 187 /* TypeLiteral */; } + function isArrayTypeNode(node) { return node.kind === 188 /* ArrayType */; } + function isTupleTypeNode(node) { return node.kind === 189 /* TupleType */; } + function isNamedTupleMember(node) { return node.kind === 202 /* NamedTupleMember */; } + function isOptionalTypeNode(node) { return node.kind === 190 /* OptionalType */; } + function isRestTypeNode(node) { return node.kind === 191 /* RestType */; } + function isUnionTypeNode(node) { return node.kind === 192 /* UnionType */; } + function isIntersectionTypeNode(node) { return node.kind === 193 /* IntersectionType */; } + function isConditionalTypeNode(node) { return node.kind === 194 /* ConditionalType */; } + function isInferTypeNode(node) { return node.kind === 195 /* InferType */; } + function isParenthesizedTypeNode(node) { return node.kind === 196 /* ParenthesizedType */; } + function isThisTypeNode(node) { return node.kind === 197 /* ThisType */; } + function isTypeOperatorNode(node) { return node.kind === 198 /* TypeOperator */; } + function isIndexedAccessTypeNode(node) { return node.kind === 199 /* IndexedAccessType */; } + function isMappedTypeNode(node) { return node.kind === 200 /* MappedType */; } + function isLiteralTypeNode(node) { return node.kind === 201 /* LiteralType */; } + function isImportTypeNode(node) { return node.kind === 205 /* ImportType */; } + function isTemplateLiteralTypeSpan(node) { return node.kind === 204 /* TemplateLiteralTypeSpan */; } + function isTemplateLiteralTypeNode(node) { return node.kind === 203 /* TemplateLiteralType */; } + function isObjectBindingPattern(node) { return node.kind === 206 /* ObjectBindingPattern */; } + function isArrayBindingPattern(node) { return node.kind === 207 /* ArrayBindingPattern */; } + function isBindingElement(node) { return node.kind === 208 /* BindingElement */; } + function isArrayLiteralExpression(node) { return node.kind === 209 /* ArrayLiteralExpression */; } + function isObjectLiteralExpression(node) { return node.kind === 210 /* ObjectLiteralExpression */; } + function isPropertyAccessExpression(node) { return node.kind === 211 /* PropertyAccessExpression */; } + function isElementAccessExpression(node) { return node.kind === 212 /* ElementAccessExpression */; } + function isCallExpression(node) { return node.kind === 213 /* CallExpression */; } + function isNewExpression(node) { return node.kind === 214 /* NewExpression */; } + function isTaggedTemplateExpression(node) { return node.kind === 215 /* TaggedTemplateExpression */; } + function isTypeAssertionExpression(node) { return node.kind === 216 /* TypeAssertionExpression */; } + function isParenthesizedExpression(node) { return node.kind === 217 /* ParenthesizedExpression */; } + function isFunctionExpression(node) { return node.kind === 218 /* FunctionExpression */; } + function isArrowFunction(node) { return node.kind === 219 /* ArrowFunction */; } + function isDeleteExpression(node) { return node.kind === 220 /* DeleteExpression */; } + function isTypeOfExpression(node) { return node.kind === 221 /* TypeOfExpression */; } + function isVoidExpression(node) { return node.kind === 222 /* VoidExpression */; } + function isAwaitExpression(node) { return node.kind === 223 /* AwaitExpression */; } + function isPrefixUnaryExpression(node) { return node.kind === 224 /* PrefixUnaryExpression */; } + function isPostfixUnaryExpression(node) { return node.kind === 225 /* PostfixUnaryExpression */; } + function isBinaryExpression(node) { return node.kind === 226 /* BinaryExpression */; } + function isConditionalExpression(node) { return node.kind === 227 /* ConditionalExpression */; } + function isTemplateExpression(node) { return node.kind === 228 /* TemplateExpression */; } + function isYieldExpression(node) { return node.kind === 229 /* YieldExpression */; } + function isSpreadElement(node) { return node.kind === 230 /* SpreadElement */; } + function isClassExpression(node) { return node.kind === 231 /* ClassExpression */; } + function isOmittedExpression(node) { return node.kind === 232 /* OmittedExpression */; } + function isExpressionWithTypeArguments(node) { return node.kind === 233 /* ExpressionWithTypeArguments */; } + function isAsExpression(node) { return node.kind === 234 /* AsExpression */; } + function isSatisfiesExpression(node) { return node.kind === 238 /* SatisfiesExpression */; } + function isNonNullExpression(node) { return node.kind === 235 /* NonNullExpression */; } + function isMetaProperty(node) { return node.kind === 236 /* MetaProperty */; } + function isSyntheticExpression(node) { return node.kind === 237 /* SyntheticExpression */; } + function isPartiallyEmittedExpression(node) { return node.kind === 360 /* PartiallyEmittedExpression */; } + function isCommaListExpression(node) { return node.kind === 361 /* CommaListExpression */; } + function isTemplateSpan(node) { return node.kind === 239 /* TemplateSpan */; } + function isSemicolonClassElement(node) { return node.kind === 240 /* SemicolonClassElement */; } + function isBlock(node) { return node.kind === 241 /* Block */; } + function isVariableStatement(node) { return node.kind === 243 /* VariableStatement */; } + function isEmptyStatement(node) { return node.kind === 242 /* EmptyStatement */; } + function isExpressionStatement(node) { return node.kind === 244 /* ExpressionStatement */; } + function isIfStatement(node) { return node.kind === 245 /* IfStatement */; } + function isDoStatement(node) { return node.kind === 246 /* DoStatement */; } + function isWhileStatement(node) { return node.kind === 247 /* WhileStatement */; } + function isForStatement(node) { return node.kind === 248 /* ForStatement */; } + function isForInStatement(node) { return node.kind === 249 /* ForInStatement */; } + function isForOfStatement(node) { return node.kind === 250 /* ForOfStatement */; } + function isContinueStatement(node) { return node.kind === 251 /* ContinueStatement */; } + function isBreakStatement(node) { return node.kind === 252 /* BreakStatement */; } + function isReturnStatement(node) { return node.kind === 253 /* ReturnStatement */; } + function isWithStatement(node) { return node.kind === 254 /* WithStatement */; } + function isSwitchStatement(node) { return node.kind === 255 /* SwitchStatement */; } + function isLabeledStatement(node) { return node.kind === 256 /* LabeledStatement */; } + function isThrowStatement(node) { return node.kind === 257 /* ThrowStatement */; } + function isTryStatement(node) { return node.kind === 258 /* TryStatement */; } + function isDebuggerStatement(node) { return node.kind === 259 /* DebuggerStatement */; } + function isVariableDeclaration(node) { return node.kind === 260 /* VariableDeclaration */; } + function isVariableDeclarationList(node) { return node.kind === 261 /* VariableDeclarationList */; } + function isFunctionDeclaration(node) { return node.kind === 262 /* FunctionDeclaration */; } + function isClassDeclaration(node) { return node.kind === 263 /* ClassDeclaration */; } + function isInterfaceDeclaration(node) { return node.kind === 264 /* InterfaceDeclaration */; } + function isTypeAliasDeclaration(node) { return node.kind === 265 /* TypeAliasDeclaration */; } + function isEnumDeclaration(node) { return node.kind === 266 /* EnumDeclaration */; } + function isModuleDeclaration(node) { return node.kind === 267 /* ModuleDeclaration */; } + function isModuleBlock(node) { return node.kind === 268 /* ModuleBlock */; } + function isCaseBlock(node) { return node.kind === 269 /* CaseBlock */; } + function isNamespaceExportDeclaration(node) { return node.kind === 270 /* NamespaceExportDeclaration */; } + function isImportEqualsDeclaration(node) { return node.kind === 271 /* ImportEqualsDeclaration */; } + function isImportDeclaration(node) { return node.kind === 272 /* ImportDeclaration */; } + function isImportClause(node) { return node.kind === 273 /* ImportClause */; } + function isImportTypeAssertionContainer(node) { return node.kind === 302 /* ImportTypeAssertionContainer */; } + function isAssertClause(node) { return node.kind === 300 /* AssertClause */; } + function isAssertEntry(node) { return node.kind === 301 /* AssertEntry */; } + function isImportAttributes(node) { return node.kind === 300 /* ImportAttributes */; } + function isImportAttribute(node) { return node.kind === 301 /* ImportAttribute */; } + function isNamespaceImport(node) { return node.kind === 274 /* NamespaceImport */; } + function isNamespaceExport(node) { return node.kind === 280 /* NamespaceExport */; } + function isNamedImports(node) { return node.kind === 275 /* NamedImports */; } + function isImportSpecifier(node) { return node.kind === 276 /* ImportSpecifier */; } + function isExportAssignment(node) { return node.kind === 277 /* ExportAssignment */; } + function isExportDeclaration(node) { return node.kind === 278 /* ExportDeclaration */; } + function isNamedExports(node) { return node.kind === 279 /* NamedExports */; } + function isExportSpecifier(node) { return node.kind === 281 /* ExportSpecifier */; } + function isMissingDeclaration(node) { return node.kind === 282 /* MissingDeclaration */; } + function isNotEmittedStatement(node) { return node.kind === 359 /* NotEmittedStatement */; } + function isSyntheticReference(node) { return node.kind === 362 /* SyntheticReferenceExpression */; } + function isExternalModuleReference(node) { return node.kind === 283 /* ExternalModuleReference */; } + function isJsxElement(node) { return node.kind === 284 /* JsxElement */; } + function isJsxSelfClosingElement(node) { return node.kind === 285 /* JsxSelfClosingElement */; } + function isJsxOpeningElement(node) { return node.kind === 286 /* JsxOpeningElement */; } + function isJsxClosingElement(node) { return node.kind === 287 /* JsxClosingElement */; } + function isJsxFragment(node) { return node.kind === 288 /* JsxFragment */; } + function isJsxOpeningFragment(node) { return node.kind === 289 /* JsxOpeningFragment */; } + function isJsxClosingFragment(node) { return node.kind === 290 /* JsxClosingFragment */; } + function isJsxAttribute(node) { return node.kind === 291 /* JsxAttribute */; } + function isJsxAttributes(node) { return node.kind === 292 /* JsxAttributes */; } + function isJsxSpreadAttribute(node) { return node.kind === 293 /* JsxSpreadAttribute */; } + function isJsxExpression(node) { return node.kind === 294 /* JsxExpression */; } + function isJsxNamespacedName(node) { return node.kind === 295 /* JsxNamespacedName */; } + function isCaseClause(node) { return node.kind === 296 /* CaseClause */; } + function isDefaultClause(node) { return node.kind === 297 /* DefaultClause */; } + function isHeritageClause(node) { return node.kind === 298 /* HeritageClause */; } + function isCatchClause(node) { return node.kind === 299 /* CatchClause */; } + function isPropertyAssignment(node) { return node.kind === 303 /* PropertyAssignment */; } + function isShorthandPropertyAssignment(node) { return node.kind === 304 /* ShorthandPropertyAssignment */; } + function isSpreadAssignment(node) { return node.kind === 305 /* SpreadAssignment */; } + function isEnumMember(node) { return node.kind === 306 /* EnumMember */; } + function isUnparsedPrepend(node) { return node.kind === 308 /* UnparsedPrepend */; } + function isSourceFile(node) { return node.kind === 312 /* SourceFile */; } + function isBundle(node) { return node.kind === 313 /* Bundle */; } + function isUnparsedSource(node) { return node.kind === 314 /* UnparsedSource */; } + function isJSDocTypeExpression(node) { return node.kind === 316 /* JSDocTypeExpression */; } + function isJSDocNameReference(node) { return node.kind === 317 /* JSDocNameReference */; } + function isJSDocMemberName(node) { return node.kind === 318 /* JSDocMemberName */; } + function isJSDocLink(node) { return node.kind === 331 /* JSDocLink */; } + function isJSDocLinkCode(node) { return node.kind === 332 /* JSDocLinkCode */; } + function isJSDocLinkPlain(node) { return node.kind === 333 /* JSDocLinkPlain */; } + function isJSDocAllType(node) { return node.kind === 319 /* JSDocAllType */; } + function isJSDocUnknownType(node) { return node.kind === 320 /* JSDocUnknownType */; } + function isJSDocNullableType(node) { return node.kind === 321 /* JSDocNullableType */; } + function isJSDocNonNullableType(node) { return node.kind === 322 /* JSDocNonNullableType */; } + function isJSDocOptionalType(node) { return node.kind === 323 /* JSDocOptionalType */; } + function isJSDocFunctionType(node) { return node.kind === 324 /* JSDocFunctionType */; } + function isJSDocVariadicType(node) { return node.kind === 325 /* JSDocVariadicType */; } + function isJSDocNamepathType(node) { return node.kind === 326 /* JSDocNamepathType */; } + function isJSDoc(node) { return node.kind === 327 /* JSDoc */; } + function isJSDocTypeLiteral(node) { return node.kind === 329 /* JSDocTypeLiteral */; } + function isJSDocSignature(node) { return node.kind === 330 /* JSDocSignature */; } + function isJSDocAugmentsTag(node) { return node.kind === 335 /* JSDocAugmentsTag */; } + function isJSDocAuthorTag(node) { return node.kind === 337 /* JSDocAuthorTag */; } + function isJSDocClassTag(node) { return node.kind === 339 /* JSDocClassTag */; } + function isJSDocCallbackTag(node) { return node.kind === 345 /* JSDocCallbackTag */; } + function isJSDocPublicTag(node) { return node.kind === 340 /* JSDocPublicTag */; } + function isJSDocPrivateTag(node) { return node.kind === 341 /* JSDocPrivateTag */; } + function isJSDocProtectedTag(node) { return node.kind === 342 /* JSDocProtectedTag */; } + function isJSDocReadonlyTag(node) { return node.kind === 343 /* JSDocReadonlyTag */; } + function isJSDocOverrideTag(node) { return node.kind === 344 /* JSDocOverrideTag */; } + function isJSDocOverloadTag(node) { return node.kind === 346 /* JSDocOverloadTag */; } + function isJSDocDeprecatedTag(node) { return node.kind === 338 /* JSDocDeprecatedTag */; } + function isJSDocSeeTag(node) { return node.kind === 354 /* JSDocSeeTag */; } + function isJSDocEnumTag(node) { return node.kind === 347 /* JSDocEnumTag */; } + function isJSDocParameterTag(node) { return node.kind === 348 /* JSDocParameterTag */; } + function isJSDocReturnTag(node) { return node.kind === 349 /* JSDocReturnTag */; } + function isJSDocThisTag(node) { return node.kind === 350 /* JSDocThisTag */; } + function isJSDocTypeTag(node) { return node.kind === 351 /* JSDocTypeTag */; } + function isJSDocTemplateTag(node) { return node.kind === 352 /* JSDocTemplateTag */; } + function isJSDocTypedefTag(node) { return node.kind === 353 /* JSDocTypedefTag */; } + function isJSDocUnknownTag(node) { return node.kind === 334 /* JSDocTag */; } + function isJSDocPropertyTag(node) { return node.kind === 355 /* JSDocPropertyTag */; } + function isJSDocImplementsTag(node) { return node.kind === 336 /* JSDocImplementsTag */; } + function isJSDocSatisfiesTag(node) { return node.kind === 357 /* JSDocSatisfiesTag */; } + function isJSDocThrowsTag(node) { return node.kind === 356 /* JSDocThrowsTag */; } + function isSyntaxList(n) { return n.kind === 358 /* SyntaxList */; } + var init_nodeTests = __esm({ "src/compiler/factory/nodeTests.ts"() { "use strict"; + init_ts2(); } }); // src/compiler/factory/utilities.ts function createEmptyExports(factory2) { - return factory2.createExportDeclaration( - /*modifiers*/ - void 0, - /*isTypeOnly*/ - false, - factory2.createNamedExports([]), - /*moduleSpecifier*/ - void 0 - ); + return factory2.createExportDeclaration( /*modifiers*/ + void 0, /*isTypeOnly*/ + false, factory2.createNamedExports([]), /*moduleSpecifier*/ + void 0); } function createMemberAccessForPropertyName(factory2, target, memberName, location) { if (isComputedPropertyName(memberName)) { return setTextRange(factory2.createElementAccessExpression(target, memberName.expression), location); } else { - const expression = setTextRange( - isMemberName(memberName) ? factory2.createPropertyAccessExpression(target, memberName) : factory2.createElementAccessExpression(target, memberName), - memberName - ); + const expression = setTextRange(isMemberName(memberName) ? factory2.createPropertyAccessExpression(target, memberName) : factory2.createElementAccessExpression(target, memberName), memberName); addEmitFlags(expression, 128 /* NoNestedSourceMaps */); return expression; } @@ -26991,16 +26254,10 @@ ${lanes.join("\n")} } } function createJsxFactoryExpression(factory2, jsxFactoryEntity, reactNamespace, parent2) { - return jsxFactoryEntity ? createJsxFactoryExpressionFromEntityName(factory2, jsxFactoryEntity, parent2) : factory2.createPropertyAccessExpression( - createReactNamespace(reactNamespace, parent2), - "createElement" - ); + return jsxFactoryEntity ? createJsxFactoryExpressionFromEntityName(factory2, jsxFactoryEntity, parent2) : factory2.createPropertyAccessExpression(createReactNamespace(reactNamespace, parent2), "createElement"); } function createJsxFragmentFactoryExpression(factory2, jsxFragmentFactoryEntity, reactNamespace, parent2) { - return jsxFragmentFactoryEntity ? createJsxFactoryExpressionFromEntityName(factory2, jsxFragmentFactoryEntity, parent2) : factory2.createPropertyAccessExpression( - createReactNamespace(reactNamespace, parent2), - "Fragment" - ); + return jsxFragmentFactoryEntity ? createJsxFactoryExpressionFromEntityName(factory2, jsxFragmentFactoryEntity, parent2) : factory2.createPropertyAccessExpression(createReactNamespace(reactNamespace, parent2), "Fragment"); } function createExpressionForJsxElement(factory2, callee, tagName, props, children, location) { const argumentsList = [tagName]; @@ -27020,15 +26277,8 @@ ${lanes.join("\n")} argumentsList.push(children[0]); } } - return setTextRange( - factory2.createCallExpression( - callee, - /*typeArguments*/ - void 0, - argumentsList - ), - location - ); + return setTextRange(factory2.createCallExpression(callee, /*typeArguments*/ + void 0, argumentsList), location); } function createExpressionForJsxFragment(factory2, jsxFactoryEntity, jsxFragmentFactoryEntity, reactNamespace, children, parentElement, location) { const tagName = createJsxFragmentFactoryExpression(factory2, jsxFragmentFactoryEntity, reactNamespace, parentElement); @@ -27043,59 +26293,31 @@ ${lanes.join("\n")} argumentsList.push(children[0]); } } - return setTextRange( - factory2.createCallExpression( - createJsxFactoryExpression(factory2, jsxFactoryEntity, reactNamespace, parentElement), - /*typeArguments*/ - void 0, - argumentsList - ), - location - ); + return setTextRange(factory2.createCallExpression(createJsxFactoryExpression(factory2, jsxFactoryEntity, reactNamespace, parentElement), /*typeArguments*/ + void 0, argumentsList), location); } function createForOfBindingStatement(factory2, node, boundValue) { if (isVariableDeclarationList(node)) { const firstDeclaration = first(node.declarations); - const updatedDeclaration = factory2.updateVariableDeclaration( - firstDeclaration, - firstDeclaration.name, - /*exclamationToken*/ - void 0, - /*type*/ - void 0, - boundValue - ); - return setTextRange( - factory2.createVariableStatement( - /*modifiers*/ - void 0, - factory2.updateVariableDeclarationList(node, [updatedDeclaration]) - ), - /*location*/ - node - ); + const updatedDeclaration = factory2.updateVariableDeclaration(firstDeclaration, firstDeclaration.name, /*exclamationToken*/ + void 0, /*type*/ + void 0, boundValue); + return setTextRange(factory2.createVariableStatement( /*modifiers*/ + void 0, factory2.updateVariableDeclarationList(node, [updatedDeclaration])), /*location*/ + node); } else { - const updatedExpression = setTextRange( - factory2.createAssignment(node, boundValue), - /*location*/ - node - ); - return setTextRange( - factory2.createExpressionStatement(updatedExpression), - /*location*/ - node - ); + const updatedExpression = setTextRange(factory2.createAssignment(node, boundValue), /*location*/ + node); + return setTextRange(factory2.createExpressionStatement(updatedExpression), /*location*/ + node); } } function insertLeadingStatement(factory2, dest, source) { if (isBlock(dest)) { return factory2.updateBlock(dest, setTextRange(factory2.createNodeArray([source, ...dest.statements]), dest.statements)); } else { - return factory2.createBlock( - factory2.createNodeArray([dest, source]), - /*multiLine*/ - true - ); + return factory2.createBlock(factory2.createNodeArray([dest, source]), /*multiLine*/ + true); } } function createExpressionFromEntityName(factory2, node) { @@ -27117,139 +26339,55 @@ ${lanes.join("\n")} } } function createExpressionForAccessorDeclaration(factory2, properties, property, receiver, multiLine) { - const { firstAccessor, getAccessor, setAccessor } = getAllAccessorDeclarations(properties, property); + const { + firstAccessor, + getAccessor, + setAccessor + } = getAllAccessorDeclarations(properties, property); if (property === firstAccessor) { - return setTextRange( - factory2.createObjectDefinePropertyCall( - receiver, - createExpressionForPropertyName(factory2, property.name), - factory2.createPropertyDescriptor({ - enumerable: factory2.createFalse(), - configurable: true, - get: getAccessor && setTextRange( - setOriginalNode( - factory2.createFunctionExpression( - getModifiers(getAccessor), - /*asteriskToken*/ - void 0, - /*name*/ - void 0, - /*typeParameters*/ - void 0, - getAccessor.parameters, - /*type*/ - void 0, - getAccessor.body - // TODO: GH#18217 - ), - getAccessor - ), - getAccessor - ), - set: setAccessor && setTextRange( - setOriginalNode( - factory2.createFunctionExpression( - getModifiers(setAccessor), - /*asteriskToken*/ - void 0, - /*name*/ - void 0, - /*typeParameters*/ - void 0, - setAccessor.parameters, - /*type*/ - void 0, - setAccessor.body - // TODO: GH#18217 - ), - setAccessor - ), - setAccessor - ) - }, !multiLine) - ), - firstAccessor - ); + return setTextRange(factory2.createObjectDefinePropertyCall(receiver, createExpressionForPropertyName(factory2, property.name), factory2.createPropertyDescriptor({ + enumerable: factory2.createFalse(), + configurable: true, + get: getAccessor && setTextRange(setOriginalNode(factory2.createFunctionExpression(getModifiers(getAccessor), /*asteriskToken*/ + void 0, /*name*/ + void 0, /*typeParameters*/ + void 0, getAccessor.parameters, /*type*/ + void 0, getAccessor.body + // TODO: GH#18217 + ), getAccessor), getAccessor), + set: setAccessor && setTextRange(setOriginalNode(factory2.createFunctionExpression(getModifiers(setAccessor), /*asteriskToken*/ + void 0, /*name*/ + void 0, /*typeParameters*/ + void 0, setAccessor.parameters, /*type*/ + void 0, setAccessor.body + // TODO: GH#18217 + ), setAccessor), setAccessor) + }, !multiLine)), firstAccessor); } return void 0; } function createExpressionForPropertyAssignment(factory2, property, receiver) { - return setOriginalNode( - setTextRange( - factory2.createAssignment( - createMemberAccessForPropertyName( - factory2, - receiver, - property.name, - /*location*/ - property.name - ), - property.initializer - ), - property - ), - property - ); + return setOriginalNode(setTextRange(factory2.createAssignment(createMemberAccessForPropertyName(factory2, receiver, property.name, /*location*/ + property.name), property.initializer), property), property); } function createExpressionForShorthandPropertyAssignment(factory2, property, receiver) { - return setOriginalNode( - setTextRange( - factory2.createAssignment( - createMemberAccessForPropertyName( - factory2, - receiver, - property.name, - /*location*/ - property.name - ), - factory2.cloneNode(property.name) - ), - /*location*/ - property - ), - /*original*/ - property - ); + return setOriginalNode(setTextRange(factory2.createAssignment(createMemberAccessForPropertyName(factory2, receiver, property.name, /*location*/ + property.name), factory2.cloneNode(property.name)), /*location*/ + property), /*original*/ + property); } function createExpressionForMethodDeclaration(factory2, method, receiver) { - return setOriginalNode( - setTextRange( - factory2.createAssignment( - createMemberAccessForPropertyName( - factory2, - receiver, - method.name, - /*location*/ - method.name - ), - setOriginalNode( - setTextRange( - factory2.createFunctionExpression( - getModifiers(method), - method.asteriskToken, - /*name*/ - void 0, - /*typeParameters*/ - void 0, - method.parameters, - /*type*/ - void 0, - method.body - // TODO: GH#18217 - ), - /*location*/ - method - ), - /*original*/ - method - ) - ), - /*location*/ - method - ), - /*original*/ - method - ); + return setOriginalNode(setTextRange(factory2.createAssignment(createMemberAccessForPropertyName(factory2, receiver, method.name, /*location*/ + method.name), setOriginalNode(setTextRange(factory2.createFunctionExpression(getModifiers(method), method.asteriskToken, /*name*/ + void 0, /*typeParameters*/ + void 0, method.parameters, /*type*/ + void 0, method.body + // TODO: GH#18217 + ), /*location*/ + method), /*original*/ + method)), /*location*/ + method), /*original*/ + method); } function createExpressionForObjectLiteralElementLike(factory2, node, property, receiver) { if (property.name && isPrivateIdentifier(property.name)) { @@ -27318,6 +26456,7 @@ ${lanes.join("\n")} function isCommaExpression(node) { return node.kind === 226 /* BinaryExpression */ && node.operatorToken.kind === 28 /* CommaToken */; } + function isCommaSequence(node) { return isCommaExpression(node) || isCommaListExpression(node); } @@ -27365,12 +26504,10 @@ ${lanes.join("\n")} function skipAssertions(node) { return skipOuterExpressions(node, 6 /* Assertions */); } + function startOnNewLine(node) { - return setStartsOnNewLine( - node, - /*newLine*/ - true - ); + return setStartsOnNewLine(node, /*newLine*/ + true); } function getExternalHelpersModuleName(node) { const parseNode = getOriginalNode(node, isSourceFile); @@ -27400,20 +26537,10 @@ ${lanes.join("\n")} } if (some(helperNames)) { helperNames.sort(compareStringsCaseSensitive); - namedBindings = nodeFactory.createNamedImports( - map(helperNames, (name) => isFileLevelUniqueName(sourceFile, name) ? nodeFactory.createImportSpecifier( - /*isTypeOnly*/ - false, - /*propertyName*/ - void 0, - nodeFactory.createIdentifier(name) - ) : nodeFactory.createImportSpecifier( - /*isTypeOnly*/ - false, - nodeFactory.createIdentifier(name), - helperFactory.getUnscopedHelperName(name) - )) - ); + namedBindings = nodeFactory.createNamedImports(map(helperNames, name => isFileLevelUniqueName(sourceFile, name) ? nodeFactory.createImportSpecifier( /*isTypeOnly*/ + false, /*propertyName*/ + void 0, nodeFactory.createIdentifier(name)) : nodeFactory.createImportSpecifier( /*isTypeOnly*/ + false, nodeFactory.createIdentifier(name), helperFactory.getUnscopedHelperName(name)))); const parseNode = getOriginalNode(sourceFile, isSourceFile); const emitNode = getOrCreateEmitNode(parseNode); emitNode.externalHelpers = true; @@ -27426,20 +26553,11 @@ ${lanes.join("\n")} } } if (namedBindings) { - const externalHelpersImportDeclaration = nodeFactory.createImportDeclaration( - /*modifiers*/ - void 0, - nodeFactory.createImportClause( - /*isTypeOnly*/ - false, - /*name*/ - void 0, - namedBindings - ), - nodeFactory.createStringLiteral(externalHelpersModuleNameText), - /*attributes*/ - void 0 - ); + const externalHelpersImportDeclaration = nodeFactory.createImportDeclaration( /*modifiers*/ + void 0, nodeFactory.createImportClause( /*isTypeOnly*/ + false, /*name*/ + void 0, namedBindings), nodeFactory.createStringLiteral(externalHelpersModuleNameText), /*attributes*/ + void 0); addInternalEmitFlags(externalHelpersImportDeclaration, 2 /* NeverApplyImportHelper */); return externalHelpersImportDeclaration; } @@ -27517,20 +26635,14 @@ ${lanes.join("\n")} } if (isPropertyAssignment(bindingElement)) { const initializer = bindingElement.initializer; - return isAssignmentExpression( - initializer, - /*excludeCompoundAssignment*/ - true - ) ? initializer.right : void 0; + return isAssignmentExpression(initializer, /*excludeCompoundAssignment*/ + true) ? initializer.right : void 0; } if (isShorthandPropertyAssignment(bindingElement)) { return bindingElement.objectAssignmentInitializer; } - if (isAssignmentExpression( - bindingElement, - /*excludeCompoundAssignment*/ - true - )) { + if (isAssignmentExpression(bindingElement, /*excludeCompoundAssignment*/ + true)) { return bindingElement.right; } if (isSpreadElement(bindingElement)) { @@ -27552,11 +26664,8 @@ ${lanes.join("\n")} } return void 0; } - if (isAssignmentExpression( - bindingElement, - /*excludeCompoundAssignment*/ - true - )) { + if (isAssignmentExpression(bindingElement, /*excludeCompoundAssignment*/ + true)) { return getTargetOfBindingOrAssignmentElement(bindingElement.left); } if (isSpreadElement(bindingElement)) { @@ -27615,6 +26724,7 @@ ${lanes.join("\n")} const kind = node.kind; return kind === 11 /* StringLiteral */ || kind === 9 /* NumericLiteral */; } + function getElementsOfBindingOrAssignmentPattern(name) { switch (name.kind) { case 206 /* ObjectBindingPattern */: @@ -27640,18 +26750,22 @@ ${lanes.join("\n")} const kind = node.kind; return kind === 176 /* Constructor */ || kind === 178 /* SetAccessor */; } + function canHaveIllegalTypeParameters(node) { const kind = node.kind; return kind === 176 /* Constructor */ || kind === 177 /* GetAccessor */ || kind === 178 /* SetAccessor */; } + function canHaveIllegalDecorators(node) { const kind = node.kind; return kind === 303 /* PropertyAssignment */ || kind === 304 /* ShorthandPropertyAssignment */ || kind === 262 /* FunctionDeclaration */ || kind === 176 /* Constructor */ || kind === 181 /* IndexSignature */ || kind === 175 /* ClassStaticBlockDeclaration */ || kind === 282 /* MissingDeclaration */ || kind === 243 /* VariableStatement */ || kind === 264 /* InterfaceDeclaration */ || kind === 265 /* TypeAliasDeclaration */ || kind === 266 /* EnumDeclaration */ || kind === 267 /* ModuleDeclaration */ || kind === 271 /* ImportEqualsDeclaration */ || kind === 272 /* ImportDeclaration */ || kind === 270 /* NamespaceExportDeclaration */ || kind === 278 /* ExportDeclaration */ || kind === 277 /* ExportAssignment */; } + function canHaveIllegalModifiers(node) { const kind = node.kind; return kind === 175 /* ClassStaticBlockDeclaration */ || kind === 303 /* PropertyAssignment */ || kind === 304 /* ShorthandPropertyAssignment */ || kind === 282 /* MissingDeclaration */ || kind === 270 /* NamespaceExportDeclaration */; } + function isQuestionOrExclamationToken(node) { return isQuestionToken(node) || isExclamationToken(node); } @@ -27674,45 +26788,53 @@ ${lanes.join("\n")} function isExponentiationOperator(kind) { return kind === 43 /* AsteriskAsteriskToken */; } + function isMultiplicativeOperator(kind) { return kind === 42 /* AsteriskToken */ || kind === 44 /* SlashToken */ || kind === 45 /* PercentToken */; } + function isMultiplicativeOperatorOrHigher(kind) { return isExponentiationOperator(kind) || isMultiplicativeOperator(kind); } function isAdditiveOperator(kind) { return kind === 40 /* PlusToken */ || kind === 41 /* MinusToken */; } + function isAdditiveOperatorOrHigher(kind) { return isAdditiveOperator(kind) || isMultiplicativeOperatorOrHigher(kind); } function isShiftOperator(kind) { return kind === 48 /* LessThanLessThanToken */ || kind === 49 /* GreaterThanGreaterThanToken */ || kind === 50 /* GreaterThanGreaterThanGreaterThanToken */; } + function isShiftOperatorOrHigher(kind) { return isShiftOperator(kind) || isAdditiveOperatorOrHigher(kind); } function isRelationalOperator(kind) { return kind === 30 /* LessThanToken */ || kind === 33 /* LessThanEqualsToken */ || kind === 32 /* GreaterThanToken */ || kind === 34 /* GreaterThanEqualsToken */ || kind === 104 /* InstanceOfKeyword */ || kind === 103 /* InKeyword */; } + function isRelationalOperatorOrHigher(kind) { return isRelationalOperator(kind) || isShiftOperatorOrHigher(kind); } function isEqualityOperator(kind) { return kind === 35 /* EqualsEqualsToken */ || kind === 37 /* EqualsEqualsEqualsToken */ || kind === 36 /* ExclamationEqualsToken */ || kind === 38 /* ExclamationEqualsEqualsToken */; } + function isEqualityOperatorOrHigher(kind) { return isEqualityOperator(kind) || isRelationalOperatorOrHigher(kind); } function isBitwiseOperator(kind) { return kind === 51 /* AmpersandToken */ || kind === 52 /* BarToken */ || kind === 53 /* CaretToken */; } + function isBitwiseOperatorOrHigher(kind) { return isBitwiseOperator(kind) || isEqualityOperatorOrHigher(kind); } function isLogicalOperator2(kind) { return kind === 56 /* AmpersandAmpersandToken */ || kind === 57 /* BarBarToken */; } + function isLogicalOperatorOrHigher(kind) { return isLogicalOperator2(kind) || isBitwiseOperatorOrHigher(kind); } @@ -27722,6 +26844,7 @@ ${lanes.join("\n")} function isBinaryOperator(kind) { return isAssignmentOperatorOrHigher(kind) || kind === 28 /* CommaToken */; } + function isBinaryOperatorToken(node) { return isBinaryOperator(node.kind); } @@ -27729,7 +26852,9 @@ ${lanes.join("\n")} const machine = new BinaryExpressionStateMachine(onEnter, onLeft, onOperator, onRight, onExit, foldState); return trampoline; function trampoline(node, outerState) { - const resultHolder = { value: void 0 }; + const resultHolder = { + value: void 0 + }; const stateStack = [BinaryExpressionState.enter]; const nodeStack = [node]; const userStateStack = [void 0]; @@ -27744,6 +26869,7 @@ ${lanes.join("\n")} function isExportOrDefaultKeywordKind(kind) { return kind === 95 /* ExportKeyword */ || kind === 90 /* DefaultKeyword */; } + function isExportOrDefaultModifier(node) { const kind = node.kind; return isExportOrDefaultKeywordKind(kind); @@ -27753,10 +26879,8 @@ ${lanes.join("\n")} 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) { @@ -27779,14 +26903,8 @@ ${lanes.join("\n")} return name; } function formatGeneratedNamePart(part, generateName) { - return typeof part === "object" ? formatGeneratedName( - /*privateName*/ - false, - part.prefix, - part.node, - part.suffix, - generateName - ) : typeof part === "string" ? part.length > 0 && part.charCodeAt(0) === 35 /* hash */ ? part.slice(1) : part : ""; + return typeof part === "object" ? formatGeneratedName( /*privateName*/ + false, part.prefix, part.node, part.suffix, generateName) : typeof part === "string" ? part.length > 0 && part.charCodeAt(0) === 35 /* hash */ ? part.slice(1) : part : ""; } function formatIdentifier(name, generateName) { return typeof name === "string" ? name : formatIdentifierWorker(name, Debug.checkDefined(generateName)); @@ -27801,72 +26919,21 @@ ${lanes.join("\n")} return `${privateName ? "#" : ""}${prefix}${baseName}${suffix}`; } function createAccessorPropertyBackingField(factory2, node, modifiers, initializer) { - return factory2.updatePropertyDeclaration( - node, - modifiers, - factory2.getGeneratedPrivateNameForNode( - node.name, - /*prefix*/ - void 0, - "_accessor_storage" - ), - /*questionOrExclamationToken*/ - void 0, - /*type*/ - void 0, - initializer - ); + return factory2.updatePropertyDeclaration(node, modifiers, factory2.getGeneratedPrivateNameForNode(node.name, /*prefix*/ + void 0, "_accessor_storage"), /*questionOrExclamationToken*/ + void 0, /*type*/ + void 0, initializer); } function createAccessorPropertyGetRedirector(factory2, node, modifiers, name, receiver = factory2.createThis()) { - return factory2.createGetAccessorDeclaration( - modifiers, - name, - [], - /*type*/ - void 0, - factory2.createBlock([ - factory2.createReturnStatement( - factory2.createPropertyAccessExpression( - receiver, - factory2.getGeneratedPrivateNameForNode( - node.name, - /*prefix*/ - void 0, - "_accessor_storage" - ) - ) - ) - ]) - ); + return factory2.createGetAccessorDeclaration(modifiers, name, [], /*type*/ + void 0, factory2.createBlock([factory2.createReturnStatement(factory2.createPropertyAccessExpression(receiver, factory2.getGeneratedPrivateNameForNode(node.name, /*prefix*/ + void 0, "_accessor_storage")))])); } function createAccessorPropertySetRedirector(factory2, node, modifiers, name, receiver = factory2.createThis()) { - return factory2.createSetAccessorDeclaration( - modifiers, - name, - [factory2.createParameterDeclaration( - /*modifiers*/ - void 0, - /*dotDotDotToken*/ - void 0, - "value" - )], - factory2.createBlock([ - factory2.createExpressionStatement( - factory2.createAssignment( - factory2.createPropertyAccessExpression( - receiver, - factory2.getGeneratedPrivateNameForNode( - node.name, - /*prefix*/ - void 0, - "_accessor_storage" - ) - ), - factory2.createIdentifier("value") - ) - ) - ]) - ); + return factory2.createSetAccessorDeclaration(modifiers, name, [factory2.createParameterDeclaration( /*modifiers*/ + void 0, /*dotDotDotToken*/ + void 0, "value")], factory2.createBlock([factory2.createExpressionStatement(factory2.createAssignment(factory2.createPropertyAccessExpression(receiver, factory2.getGeneratedPrivateNameForNode(node.name, /*prefix*/ + void 0, "_accessor_storage")), factory2.createIdentifier("value")))])); } function findComputedPropertyNameCacheAssignment(name) { let node = name.expression; @@ -27880,11 +26947,8 @@ ${lanes.join("\n")} node = node.right; continue; } - if (isAssignmentExpression( - node, - /*excludeCompoundAssignment*/ - true - ) && isGeneratedIdentifier(node.left)) { + if (isAssignmentExpression(node, /*excludeCompoundAssignment*/ + true) && isGeneratedIdentifier(node.left)) { return node; } break; @@ -27913,8 +26977,7 @@ ${lanes.join("\n")} 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); @@ -27923,8 +26986,7 @@ ${lanes.join("\n")} return true; } if (target.transformFlags & 128 /* ContainsES2018 */) { - if (containsObjectRestOrSpread(target)) - return true; + if (containsObjectRestOrSpread(target)) return true; } } } @@ -27935,8 +26997,9 @@ ${lanes.join("\n")} var init_utilities2 = __esm({ "src/compiler/factory/utilities.ts"() { "use strict"; + init_ts2(); - ((BinaryExpressionState2) => { + (BinaryExpressionState2 => { function enter(machine, stackIndex, stateStack, nodeStack, userStateStack, _resultHolder, outerState) { const prevUserState = stackIndex > 0 ? userStateStack[stackIndex - 1] : void 0; Debug.assertEqual(stateStack[stackIndex], enter); @@ -28001,14 +27064,11 @@ ${lanes.join("\n")} 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: @@ -28057,13 +27117,16 @@ ${lanes.join("\n")} const kind = node.kind; return kind === 168 /* TypeParameter */ || kind === 169 /* Parameter */ || kind === 171 /* PropertySignature */ || kind === 172 /* PropertyDeclaration */ || kind === 173 /* MethodSignature */ || kind === 174 /* MethodDeclaration */ || kind === 176 /* Constructor */ || kind === 177 /* GetAccessor */ || kind === 178 /* SetAccessor */ || kind === 181 /* IndexSignature */ || kind === 185 /* ConstructorType */ || kind === 218 /* FunctionExpression */ || kind === 219 /* ArrowFunction */ || kind === 231 /* ClassExpression */ || kind === 243 /* VariableStatement */ || kind === 262 /* FunctionDeclaration */ || kind === 263 /* ClassDeclaration */ || kind === 264 /* InterfaceDeclaration */ || kind === 265 /* TypeAliasDeclaration */ || kind === 266 /* EnumDeclaration */ || kind === 267 /* ModuleDeclaration */ || kind === 271 /* ImportEqualsDeclaration */ || kind === 272 /* ImportDeclaration */ || kind === 277 /* ExportAssignment */ || kind === 278 /* ExportDeclaration */; } + function canHaveDecorators(node) { const kind = node.kind; return kind === 169 /* Parameter */ || kind === 172 /* PropertyDeclaration */ || kind === 174 /* MethodDeclaration */ || kind === 177 /* GetAccessor */ || kind === 178 /* SetAccessor */ || kind === 231 /* ClassExpression */ || kind === 263 /* ClassDeclaration */; } + var init_utilitiesPublic2 = __esm({ "src/compiler/factory/utilitiesPublic.ts"() { "use strict"; + init_ts2(); } }); @@ -28088,6 +27151,7 @@ ${lanes.join("\n")} function isJSDocLikeText(text, start) { return text.charCodeAt(start + 1) === 42 /* asterisk */ && text.charCodeAt(start + 2) === 42 /* asterisk */ && text.charCodeAt(start + 3) !== 47 /* slash */; } + function isFileProbablyExternalModule(sourceFile) { return forEach(sourceFile.statements, isAnExternalModuleIndicatorNode) || getImportMetaIfNecessary(sourceFile); } @@ -28101,7 +27165,7 @@ ${lanes.join("\n")} return isImportMeta2(node) ? node : forEachChild(node, walkTreeForImportMeta); } function hasModifierOfKind(node, kind) { - return some(node.modifiers, (m) => m.kind === kind); + return some(node.modifiers, m => m.kind === kind); } function isImportMeta2(node) { return isMetaProperty(node) && node.keywordToken === 102 /* ImportKeyword */ && node.name.escapedText === "meta"; @@ -28119,7 +27183,8 @@ ${lanes.join("\n")} return visitNodes(cbNode, cbNodes, node.elements); } function forEachChildInCallOrNewExpression(node, cbNode, cbNodes) { - return visitNode2(cbNode, node.expression) || // TODO: should we separate these branches out? + return visitNode2(cbNode, node.expression) || + // TODO: should we separate these branches out? visitNode2(cbNode, node.questionDotToken) || visitNodes(cbNode, cbNodes, node.typeArguments) || visitNodes(cbNode, cbNodes, node.arguments); } function forEachChildInBlock(node, cbNode, cbNodes) { @@ -28178,8 +27243,7 @@ ${lanes.join("\n")} if (cbNodes) { const res = cbNodes(current, parent2); if (res) { - if (res === "skip") - continue; + if (res === "skip") continue; return res; } } @@ -28190,8 +27254,7 @@ ${lanes.join("\n")} } else { const res = cbNode(current, parent2); if (res) { - if (res === "skip") - continue; + if (res === "skip") continue; return res; } if (current.kind >= 166 /* FirstNode */) { @@ -28216,13 +27279,10 @@ ${lanes.join("\n")} } function createSourceFile(fileName, sourceText, languageVersionOrOptions, setParentNodes = false, scriptKind) { var _a, _b, _c, _d; - (_a = tracing) == null ? void 0 : _a.push( - tracing.Phase.Parse, - "createSourceFile", - { path: fileName }, - /*separateBeginAndEnd*/ - true - ); + (_a = tracing) == null ? void 0 : _a.push(tracing.Phase.Parse, "createSourceFile", { + path: fileName + }, /*separateBeginAndEnd*/ + true); mark("beforeParse"); let result; (_b = perfLogger) == null ? void 0 : _b.logStartParseSourceFile(fileName); @@ -28231,35 +27291,19 @@ ${lanes.join("\n")} setExternalModuleIndicator: overrideSetExternalModuleIndicator, impliedNodeFormat: format, jsDocParsingMode - } = typeof languageVersionOrOptions === "object" ? languageVersionOrOptions : { languageVersion: languageVersionOrOptions }; + } = typeof languageVersionOrOptions === "object" ? languageVersionOrOptions : { + languageVersion: languageVersionOrOptions + }; if (languageVersion === 100 /* JSON */) { - result = Parser.parseSourceFile( - fileName, - sourceText, - languageVersion, - /*syntaxCursor*/ - void 0, - setParentNodes, - 6 /* JSON */, - noop, - jsDocParsingMode - ); + result = Parser.parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ + void 0, setParentNodes, 6 /* JSON */, noop, jsDocParsingMode); } else { - const setIndicator = format === void 0 ? overrideSetExternalModuleIndicator : (file) => { + const setIndicator = format === void 0 ? overrideSetExternalModuleIndicator : file => { file.impliedNodeFormat = format; return (overrideSetExternalModuleIndicator || setExternalModuleIndicator)(file); }; - result = Parser.parseSourceFile( - fileName, - sourceText, - languageVersion, - /*syntaxCursor*/ - void 0, - setParentNodes, - scriptKind, - setIndicator, - jsDocParsingMode - ); + result = Parser.parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ + void 0, setParentNodes, scriptKind, setIndicator, jsDocParsingMode); } (_c = perfLogger) == null ? void 0 : _c.logStopParseSourceFile(); mark("afterParse"); @@ -28301,9 +27345,11 @@ ${lanes.join("\n")} if (mode === "import") { return 99 /* ESNext */; } + if (mode === "require") { return 1 /* CommonJS */; } + reportDiagnostic(pos, end - pos, Diagnostics.resolution_mode_should_be_either_require_or_import); return void 0; } @@ -28313,7 +27359,7 @@ ${lanes.join("\n")} const comment = sourceText.substring(range.pos, range.end); extractPragmas(pragmas, range, comment); } - context.pragmas = /* @__PURE__ */ new Map(); + context.pragmas = /* @__PURE__ */new Map(); for (const pragma of pragmas) { if (context.pragmas.has(pragma.name)) { const currentValue = context.pragmas.get(pragma.name); @@ -28336,60 +27382,84 @@ ${lanes.join("\n")} context.hasNoDefaultLib = false; context.pragmas.forEach((entryOrList, key) => { switch (key) { - case "reference": { - const referencedFiles = context.referencedFiles; - const typeReferenceDirectives = context.typeReferenceDirectives; - const libReferenceDirectives = context.libReferenceDirectives; - forEach(toArray(entryOrList), (arg) => { - const { types, lib, path, ["resolution-mode"]: res } = arg.arguments; - if (arg.arguments["no-default-lib"]) { - context.hasNoDefaultLib = true; - } else if (types) { - const parsed = parseResolutionMode(res, types.pos, types.end, reportDiagnostic); - typeReferenceDirectives.push({ pos: types.pos, end: types.end, fileName: types.value, ...parsed ? { resolutionMode: parsed } : {} }); - } else if (lib) { - libReferenceDirectives.push({ pos: lib.pos, end: lib.end, fileName: lib.value }); - } else if (path) { - referencedFiles.push({ pos: path.pos, end: path.end, fileName: path.value }); - } else { - reportDiagnostic(arg.range.pos, arg.range.end - arg.range.pos, Diagnostics.Invalid_reference_directive_syntax); - } - }); - break; - } - case "amd-dependency": { - context.amdDependencies = map( - toArray(entryOrList), - (x) => ({ name: x.arguments.name, path: x.arguments.path }) - ); - break; - } - case "amd-module": { - if (entryOrList instanceof Array) { - for (const entry of entryOrList) { - if (context.moduleName) { - reportDiagnostic(entry.range.pos, entry.range.end - entry.range.pos, Diagnostics.An_AMD_module_cannot_have_multiple_name_assignments); + case "reference": + { + const referencedFiles = context.referencedFiles; + const typeReferenceDirectives = context.typeReferenceDirectives; + const libReferenceDirectives = context.libReferenceDirectives; + forEach(toArray(entryOrList), arg => { + const { + types, + lib, + path, + ["resolution-mode"]: res + } = arg.arguments; + if (arg.arguments["no-default-lib"]) { + context.hasNoDefaultLib = true; + } else if (types) { + const parsed = parseResolutionMode(res, types.pos, types.end, reportDiagnostic); + typeReferenceDirectives.push({ + pos: types.pos, + end: types.end, + fileName: types.value, + ...(parsed ? { + resolutionMode: parsed + } : {}) + }); + } else if (lib) { + libReferenceDirectives.push({ + pos: lib.pos, + end: lib.end, + fileName: lib.value + }); + } else if (path) { + referencedFiles.push({ + pos: path.pos, + end: path.end, + fileName: path.value + }); + } else { + reportDiagnostic(arg.range.pos, arg.range.end - arg.range.pos, Diagnostics.Invalid_reference_directive_syntax); } - context.moduleName = entry.arguments.name; - } - } else { - context.moduleName = entryOrList.arguments.name; + }); + break; } - break; - } - case "ts-nocheck": - case "ts-check": { - forEach(toArray(entryOrList), (entry) => { - if (!context.checkJsDirective || entry.range.pos > context.checkJsDirective.pos) { - context.checkJsDirective = { - enabled: key === "ts-check", - end: entry.range.end, - pos: entry.range.pos - }; + case "amd-dependency": + { + context.amdDependencies = map(toArray(entryOrList), x => ({ + name: x.arguments.name, + path: x.arguments.path + })); + break; + } + case "amd-module": + { + if (entryOrList instanceof Array) { + for (const entry of entryOrList) { + if (context.moduleName) { + reportDiagnostic(entry.range.pos, entry.range.end - entry.range.pos, Diagnostics.An_AMD_module_cannot_have_multiple_name_assignments); + } + context.moduleName = entry.arguments.name; + } + } else { + context.moduleName = entryOrList.arguments.name; } - }); - break; - } + break; + } + case "ts-nocheck": + case "ts-check": + { + forEach(toArray(entryOrList), entry => { + if (!context.checkJsDirective || entry.range.pos > context.checkJsDirective.pos) { + context.checkJsDirective = { + enabled: key === "ts-check", + end: entry.range.end, + pos: entry.range.pos + }; + } + }); + break; + } case "jsx": case "jsxfrag": case "jsximportsource": @@ -28437,9 +27507,21 @@ ${lanes.join("\n")} } } } - pragmas.push({ name, args: { arguments: argument, range } }); + pragmas.push({ + name, + args: { + arguments: argument, + range + } + }); } else { - pragmas.push({ name, args: { arguments: {}, range } }); + pragmas.push({ + name, + args: { + arguments: {}, + range + } + }); } return; } @@ -28456,8 +27538,7 @@ ${lanes.join("\n")} } } 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)) { @@ -28465,16 +27546,19 @@ ${lanes.join("\n")} } const args = match[2]; const argument = getNamedPragmaArguments(pragma, args); - if (argument === "fail") - return; - pragmas.push({ name, args: { arguments: argument, range } }); + 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++) { @@ -28508,14 +27592,15 @@ ${lanes.join("\n")} var init_parser = __esm({ "src/compiler/parser.ts"() { "use strict"; + init_ts2(); init_ts_performance(); parseBaseNodeFactory = { - createBaseSourceFileNode: (kind) => new (SourceFileConstructor || (SourceFileConstructor = objectAllocator.getSourceFileConstructor()))(kind, -1, -1), - createBaseIdentifierNode: (kind) => new (IdentifierConstructor || (IdentifierConstructor = objectAllocator.getIdentifierConstructor()))(kind, -1, -1), - createBasePrivateIdentifierNode: (kind) => new (PrivateIdentifierConstructor || (PrivateIdentifierConstructor = objectAllocator.getPrivateIdentifierConstructor()))(kind, -1, -1), - createBaseTokenNode: (kind) => new (TokenConstructor || (TokenConstructor = objectAllocator.getTokenConstructor()))(kind, -1, -1), - createBaseNode: (kind) => new (NodeConstructor || (NodeConstructor = objectAllocator.getNodeConstructor()))(kind, -1, -1) + createBaseSourceFileNode: kind => new (SourceFileConstructor || (SourceFileConstructor = objectAllocator.getSourceFileConstructor()))(kind, -1, -1), + createBaseIdentifierNode: kind => new (IdentifierConstructor || (IdentifierConstructor = objectAllocator.getIdentifierConstructor()))(kind, -1, -1), + createBasePrivateIdentifierNode: kind => new (PrivateIdentifierConstructor || (PrivateIdentifierConstructor = objectAllocator.getPrivateIdentifierConstructor()))(kind, -1, -1), + createBaseTokenNode: kind => new (TokenConstructor || (TokenConstructor = objectAllocator.getTokenConstructor()))(kind, -1, -1), + createBaseNode: kind => new (NodeConstructor || (NodeConstructor = objectAllocator.getNodeConstructor()))(kind, -1, -1) }; parseNodeFactory = createNodeFactory(1 /* NoParenthesizerRules */, parseBaseNodeFactory); forEachChildTable = { @@ -28942,12 +28027,9 @@ ${lanes.join("\n")} [344 /* JSDocOverrideTag */]: forEachChildInJSDocTag, [360 /* PartiallyEmittedExpression */]: forEachChildInPartiallyEmittedExpression }; - ((Parser2) => { - var scanner2 = createScanner( - 99 /* Latest */, - /*skipTrivia*/ - true - ); + (Parser2 => { + var scanner2 = createScanner(99 /* Latest */, /*skipTrivia*/ + true); var disallowInAndDecoratorContext = 8192 /* DisallowInContext */ | 32768 /* DecoratorContext */; var NodeConstructor2; var TokenConstructor2; @@ -28959,41 +28041,21 @@ ${lanes.join("\n")} return node; } var baseNodeFactory = { - createBaseSourceFileNode: (kind) => countNode(new SourceFileConstructor2( - kind, - /*pos*/ - 0, - /*end*/ - 0 - )), - createBaseIdentifierNode: (kind) => countNode(new IdentifierConstructor2( - kind, - /*pos*/ - 0, - /*end*/ - 0 - )), - createBasePrivateIdentifierNode: (kind) => countNode(new PrivateIdentifierConstructor2( - kind, - /*pos*/ - 0, - /*end*/ - 0 - )), - createBaseTokenNode: (kind) => countNode(new TokenConstructor2( - kind, - /*pos*/ - 0, - /*end*/ - 0 - )), - createBaseNode: (kind) => countNode(new NodeConstructor2( - kind, - /*pos*/ - 0, - /*end*/ - 0 - )) + createBaseSourceFileNode: kind => countNode(new SourceFileConstructor2(kind, /*pos*/ + 0, /*end*/ + 0)), + createBaseIdentifierNode: kind => countNode(new IdentifierConstructor2(kind, /*pos*/ + 0, /*end*/ + 0)), + createBasePrivateIdentifierNode: kind => countNode(new PrivateIdentifierConstructor2(kind, /*pos*/ + 0, /*end*/ + 0)), + createBaseTokenNode: kind => countNode(new TokenConstructor2(kind, /*pos*/ + 0, /*end*/ + 0)), + createBaseNode: kind => countNode(new NodeConstructor2(kind, /*pos*/ + 0, /*end*/ + 0)) }; var factory2 = createNodeFactory(1 /* NoParenthesizerRules */ | 2 /* NoNodeConverters */ | 8 /* NoOriginalNode */, baseNodeFactory); var { @@ -29047,15 +28109,9 @@ ${lanes.join("\n")} scriptKind2 = ensureScriptKind(fileName2, scriptKind2); if (scriptKind2 === 6 /* JSON */) { const result2 = parseJsonText2(fileName2, sourceText2, languageVersion2, syntaxCursor2, setParentNodes); - convertToJson( - result2, - (_a = result2.statements[0]) == null ? void 0 : _a.expression, - result2.parseDiagnostics, - /*returnValue*/ - false, - /*jsonConversionNotifier*/ - void 0 - ); + convertToJson(result2, (_a = result2.statements[0]) == null ? void 0 : _a.expression, result2.parseDiagnostics, /*returnValue*/ + false, /*jsonConversionNotifier*/ + void 0); result2.referencedFiles = emptyArray; result2.typeReferenceDirectives = emptyArray; result2.libReferenceDirectives = emptyArray; @@ -29071,20 +28127,12 @@ ${lanes.join("\n")} } Parser2.parseSourceFile = parseSourceFile; function parseIsolatedEntityName2(content, languageVersion2) { - initializeState( - "", - content, - languageVersion2, - /*syntaxCursor*/ - void 0, - 1 /* JS */, - 0 /* ParseAll */ - ); + initializeState("", content, languageVersion2, /*syntaxCursor*/ + void 0, 1 /* JS */, 0 /* ParseAll */); + nextToken(); - const entityName = parseEntityName( - /*allowReservedWords*/ - true - ); + const entityName = parseEntityName( /*allowReservedWords*/ + true); const isValid = token() === 1 /* EndOfFileToken */ && !parseDiagnostics.length; clearState(); return isValid ? entityName : void 0; @@ -29146,17 +28194,8 @@ ${lanes.join("\n")} statements = createNodeArray([statement], pos); endOfFileToken = parseExpectedToken(1 /* EndOfFileToken */, Diagnostics.Unexpected_token); } - const sourceFile = createSourceFile2( - fileName2, - 2 /* ES2015 */, - 6 /* JSON */, - /*isDeclarationFile*/ - false, - statements, - endOfFileToken, - sourceFlags, - noop - ); + const sourceFile = createSourceFile2(fileName2, 2 /* ES2015 */, 6 /* JSON */, /*isDeclarationFile*/ + false, statements, endOfFileToken, sourceFlags, noop); if (setParentNodes) { fixupParentReferences(sourceFile); } @@ -29186,7 +28225,7 @@ ${lanes.join("\n")} languageVariant = getLanguageVariant(_scriptKind); parseDiagnostics = []; parsingContext = 0; - identifiers = /* @__PURE__ */ new Map(); + identifiers = /* @__PURE__ */new Map(); identifierCount = 0; nodeCount = 0; sourceFlags = 0; @@ -29235,6 +28274,7 @@ ${lanes.join("\n")} if (isDeclarationFile) { contextFlags |= 33554432 /* Ambient */; } + sourceFlags = contextFlags; nextToken(); const statements = parseList(0 /* SourceElements */, parseStatement); @@ -29267,19 +28307,21 @@ ${lanes.join("\n")} return node; } Debug.assert(!node.jsDoc); - const jsDoc = mapDefined(getJSDocCommentRanges(node, sourceText), (comment) => JSDocParser.parseJSDocComment(node, comment.pos, comment.end - comment.pos)); - if (jsDoc.length) - node.jsDoc = jsDoc; + const jsDoc = mapDefined(getJSDocCommentRanges(node, sourceText), comment => JSDocParser.parseJSDocComment(node, comment.pos, comment.end - comment.pos)); + if (jsDoc.length) node.jsDoc = jsDoc; if (hasDeprecatedTag) { hasDeprecatedTag = false; node.flags |= 536870912 /* Deprecated */; } + return node; } function reparseTopLevelAwait(sourceFile) { const savedSyntaxCursor = syntaxCursor; const baseSyntaxCursor = IncrementalParser.createSyntaxCursor(sourceFile); - syntaxCursor = { currentNode: currentNode2 }; + syntaxCursor = { + currentNode: currentNode2 + }; const statements = []; const savedParseDiagnostics = parseDiagnostics; parseDiagnostics = []; @@ -29290,8 +28332,8 @@ ${lanes.join("\n")} const nextStatement = sourceFile.statements[start]; addRange(statements, sourceFile.statements, pos, start); pos = findNextStatementWithoutAwait(sourceFile.statements, start); - const diagnosticStart = findIndex(savedParseDiagnostics, (diagnostic) => diagnostic.start >= prevStatement.pos); - const diagnosticEnd = diagnosticStart >= 0 ? findIndex(savedParseDiagnostics, (diagnostic) => diagnostic.start >= nextStatement.pos, diagnosticStart) : -1; + const diagnosticStart = findIndex(savedParseDiagnostics, diagnostic => diagnostic.start >= prevStatement.pos); + const diagnosticEnd = diagnosticStart >= 0 ? findIndex(savedParseDiagnostics, diagnostic => diagnostic.start >= nextStatement.pos, diagnosticStart) : -1; if (diagnosticStart >= 0) { addRange(parseDiagnostics, savedParseDiagnostics, diagnosticStart, diagnosticEnd >= 0 ? diagnosticEnd : void 0); } @@ -29324,7 +28366,7 @@ ${lanes.join("\n")} if (pos >= 0) { const prevStatement = sourceFile.statements[pos]; addRange(statements, sourceFile.statements, pos); - const diagnosticStart = findIndex(savedParseDiagnostics, (diagnostic) => diagnostic.start >= prevStatement.pos); + const diagnosticStart = findIndex(savedParseDiagnostics, diagnostic => diagnostic.start >= prevStatement.pos); if (diagnosticStart >= 0) { addRange(parseDiagnostics, savedParseDiagnostics, diagnosticStart); } @@ -29334,6 +28376,7 @@ ${lanes.join("\n")} function containsPossibleTopLevelAwait(node) { return !(node.flags & 65536 /* AwaitContext */) && !!(node.transformFlags & 67108864 /* ContainsPossibleTopLevelAwait */); } + function findNextStatementWithAwait(statements2, start2) { for (let i = start2; i < statements2.length; i++) { if (containsPossibleTopLevelAwait(statements2[i])) { @@ -29359,11 +28402,8 @@ ${lanes.join("\n")} } } function fixupParentReferences(rootNode) { - setParentRecursive( - rootNode, - /*incremental*/ - true - ); + setParentRecursive(rootNode, /*incremental*/ + true); } Parser2.fixupParentReferences = fixupParentReferences; function createSourceFile2(fileName2, languageVersion2, scriptKind2, isDeclarationFile, statements, endOfFileToken, flags, setExternalModuleIndicator2) { @@ -29398,29 +28438,27 @@ ${lanes.join("\n")} function setDisallowInContext(val) { setContextFlag(val, 8192 /* DisallowInContext */); } + function setYieldContext(val) { setContextFlag(val, 16384 /* YieldContext */); } + function setDecoratorContext(val) { setContextFlag(val, 32768 /* DecoratorContext */); } + function setAwaitContext(val) { setContextFlag(val, 65536 /* AwaitContext */); } + function doOutsideOfContext(context, func) { const contextFlagsToClear = context & contextFlags; if (contextFlagsToClear) { - setContextFlag( - /*val*/ - false, - contextFlagsToClear - ); + setContextFlag( /*val*/ + false, contextFlagsToClear); const result = func(); - setContextFlag( - /*val*/ - true, - contextFlagsToClear - ); + setContextFlag( /*val*/ + true, contextFlagsToClear); return result; } return func(); @@ -29428,17 +28466,11 @@ ${lanes.join("\n")} function doInsideOfContext(context, func) { const contextFlagsToSet = context & ~contextFlags; if (contextFlagsToSet) { - setContextFlag( - /*val*/ - true, - contextFlagsToSet - ); + setContextFlag( /*val*/ + true, contextFlagsToSet); const result = func(); - setContextFlag( - /*val*/ - false, - contextFlagsToSet - ); + setContextFlag( /*val*/ + false, contextFlagsToSet); return result; } return func(); @@ -29479,18 +28511,23 @@ ${lanes.join("\n")} function inYieldContext() { return inContext(16384 /* YieldContext */); } + function inDisallowInContext() { return inContext(8192 /* DisallowInContext */); } + function inDisallowConditionalTypesContext() { return inContext(131072 /* DisallowConditionalTypesContext */); } + function inDecoratorContext() { return inContext(32768 /* DecoratorContext */); } + function inAwaitContext() { return inContext(65536 /* AwaitContext */); } + function parseErrorAtCurrentToken(message, ...args) { return parseErrorAt(scanner2.getTokenStart(), scanner2.getTokenEnd(), message, ...args); } @@ -29584,15 +28621,18 @@ ${lanes.join("\n")} function lookAhead(callback) { return speculationHelper(callback, 1 /* Lookahead */); } + function tryParse(callback) { return speculationHelper(callback, 0 /* TryParse */); } + function isBindingIdentifier() { if (token() === 80 /* Identifier */) { return true; } return token() > 118 /* LastReservedWord */; } + function isIdentifier2() { if (token() === 80 /* Identifier */) { return true; @@ -29605,6 +28645,7 @@ ${lanes.join("\n")} } return token() > 118 /* LastReservedWord */; } + function parseExpected(kind, diagnosticMessage, shouldAdvance = true) { if (token() === kind) { if (shouldAdvance) { @@ -29619,8 +28660,9 @@ ${lanes.join("\n")} } return false; } - const viableKeywordSuggestions = Object.keys(textToKeywordObj).filter((keyword) => keyword.length > 2); + const viableKeywordSuggestions = Object.keys(textToKeywordObj).filter(keyword => keyword.length > 2); function parseErrorForMissingSemicolonAfter(node) { + var _getSpellingSuggestio; if (isTaggedTemplateExpression(node)) { parseErrorAt(skipTrivia(sourceText, node.template.pos), node.template.end, Diagnostics.Module_declaration_names_may_only_use_or_quoted_strings); return; @@ -29653,7 +28695,7 @@ ${lanes.join("\n")} parseErrorForInvalidName(Diagnostics.Type_alias_name_cannot_be_0, Diagnostics.Type_alias_must_be_given_a_name, 64 /* EqualsToken */); return; } - const suggestion = getSpellingSuggestion(expressionText, viableKeywordSuggestions, (n) => n) ?? getSpaceSuggestion(expressionText); + const suggestion = (_getSpellingSuggestio = getSpellingSuggestion(expressionText, viableKeywordSuggestions, n => n)) !== null && _getSpellingSuggestio !== void 0 ? _getSpellingSuggestio : getSpaceSuggestion(expressionText); if (suggestion) { parseErrorAt(pos, node.end, Diagnostics.Unknown_keyword_or_identifier_Did_you_mean_0, suggestion); return; @@ -29724,10 +28766,7 @@ ${lanes.join("\n")} return; } if (lastError) { - addRelatedInfo( - lastError, - createDetachedDiagnostic(fileName, sourceText, openPosition, 1, Diagnostics.The_parser_expected_to_find_a_1_to_match_the_0_token_here, tokenToString(openKind), tokenToString(closeKind)) - ); + addRelatedInfo(lastError, createDetachedDiagnostic(fileName, sourceText, openPosition, 1, Diagnostics.The_parser_expected_to_find_a_1_to_match_the_0_token_here, tokenToString(openKind), tokenToString(closeKind))); } } function parseOptional(t) { @@ -29750,26 +28789,15 @@ ${lanes.join("\n")} return void 0; } function parseExpectedToken(t, diagnosticMessage, arg0) { - return parseOptionalToken(t) || createMissingNode( - t, - /*reportAtCurrentPosition*/ - false, - diagnosticMessage || Diagnostics._0_expected, - arg0 || tokenToString(t) - ); + return parseOptionalToken(t) || createMissingNode(t, /*reportAtCurrentPosition*/ + false, diagnosticMessage || Diagnostics._0_expected, arg0 || tokenToString(t)); } function parseExpectedTokenJSDoc(t) { const optional = parseOptionalTokenJSDoc(t); - if (optional) - return optional; + if (optional) return optional; Debug.assert(isKeywordOrPunctuation(t)); - return createMissingNode( - t, - /*reportAtCurrentPosition*/ - false, - Diagnostics._0_expected, - tokenToString(t) - ); + return createMissingNode(t, /*reportAtCurrentPosition*/ + false, Diagnostics._0_expected, tokenToString(t)); } function parseTokenNode() { const pos = getNodePos(); @@ -29801,13 +28829,14 @@ ${lanes.join("\n")} function parseSemicolon() { return tryParseSemicolon() || parseExpected(27 /* SemicolonToken */); } + function createNodeArray(elements, pos, end, hasTrailingComma) { const array = factoryCreateNodeArray(elements, hasTrailingComma); - setTextRangePosEnd(array, pos, end ?? scanner2.getTokenFullStart()); + setTextRangePosEnd(array, pos, end !== null && end !== void 0 ? end : scanner2.getTokenFullStart()); return array; } function finishNode(node, pos, end) { - setTextRangePosEnd(node, pos, end ?? scanner2.getTokenFullStart()); + setTextRangePosEnd(node, pos, end !== null && end !== void 0 ? end : scanner2.getTokenFullStart()); if (contextFlags) { node.flags |= contextFlags; } @@ -29815,6 +28844,7 @@ ${lanes.join("\n")} parseErrorBeforeNextFinishedNode = false; node.flags |= 262144 /* ThisNodeHasError */; } + return node; } function createMissingNode(kind, reportAtCurrentPosition, diagnosticMessage, ...args) { @@ -29824,25 +28854,11 @@ ${lanes.join("\n")} parseErrorAtCurrentToken(diagnosticMessage, ...args); } const pos = getNodePos(); - const result = kind === 80 /* Identifier */ ? factoryCreateIdentifier( - "", - /*originalKeywordKind*/ - void 0 - ) : isTemplateLiteralKind(kind) ? factory2.createTemplateLiteralLikeNode( - kind, - "", - "", - /*templateFlags*/ - void 0 - ) : kind === 9 /* NumericLiteral */ ? factoryCreateNumericLiteral( - "", - /*numericLiteralFlags*/ - void 0 - ) : kind === 11 /* StringLiteral */ ? factoryCreateStringLiteral( - "", - /*isSingleQuote*/ - void 0 - ) : kind === 282 /* MissingDeclaration */ ? factory2.createMissingDeclaration() : factoryCreateToken(kind); + const result = kind === 80 /* Identifier */ ? factoryCreateIdentifier("", /*originalKeywordKind*/ + void 0) : isTemplateLiteralKind(kind) ? factory2.createTemplateLiteralLikeNode(kind, "", "", /*templateFlags*/ + void 0) : kind === 9 /* NumericLiteral */ ? factoryCreateNumericLiteral("", /*numericLiteralFlags*/ + void 0) : kind === 11 /* StringLiteral */ ? factoryCreateStringLiteral("", /*isSingleQuote*/ + void 0) : kind === 282 /* MissingDeclaration */ ? factory2.createMissingDeclaration() : factoryCreateToken(kind); return finishNode(result, pos); } function internIdentifier(text) { @@ -29864,16 +28880,12 @@ ${lanes.join("\n")} } if (token() === 81 /* PrivateIdentifier */) { parseErrorAtCurrentToken(privateIdentifierDiagnosticMessage || Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies); - return createIdentifier( - /*isIdentifier*/ - true - ); + return createIdentifier( /*isIdentifier*/ + true); } if (token() === 0 /* Unknown */ && scanner2.tryScan(() => scanner2.reScanInvalidIdentifier() === 80 /* Identifier */)) { - return createIdentifier( - /*isIdentifier*/ - true - ); + return createIdentifier( /*isIdentifier*/ + true); } identifierCount++; const reportAtCurrentPosition = token() === 1 /* EndOfFileToken */; @@ -29883,12 +28895,8 @@ ${lanes.join("\n")} return createMissingNode(80 /* Identifier */, reportAtCurrentPosition, diagnosticMessage || defaultMessage, msgArg); } function parseBindingIdentifier(privateIdentifierDiagnosticMessage) { - return createIdentifier( - isBindingIdentifier(), - /*diagnosticMessage*/ - void 0, - privateIdentifierDiagnosticMessage - ); + return createIdentifier(isBindingIdentifier(), /*diagnosticMessage*/ + void 0, privateIdentifierDiagnosticMessage); } function parseIdentifier(diagnosticMessage, privateIdentifierDiagnosticMessage) { return createIdentifier(isIdentifier2(), diagnosticMessage, privateIdentifierDiagnosticMessage); @@ -29905,9 +28913,11 @@ ${lanes.join("\n")} function isLiteralPropertyName() { return tokenIsIdentifierOrKeyword(token()) || token() === 11 /* StringLiteral */ || token() === 9 /* NumericLiteral */; } + function isImportAttributeName2() { return tokenIsIdentifierOrKeyword(token()) || token() === 11 /* StringLiteral */; } + function parsePropertyNameWorker(allowComputedPropertyNames) { if (token() === 11 /* StringLiteral */ || token() === 9 /* NumericLiteral */) { const node = parseLiteralNode(); @@ -29923,10 +28933,8 @@ ${lanes.join("\n")} return parseIdentifierName(); } function parsePropertyName() { - return parsePropertyNameWorker( - /*allowComputedPropertyNames*/ - true - ); + return parsePropertyNameWorker( /*allowComputedPropertyNames*/ + true); } function parseComputedPropertyName() { const pos = getNodePos(); @@ -30050,15 +29058,11 @@ ${lanes.join("\n")} case 11 /* ArgumentExpressions */: return token() === 26 /* DotDotDotToken */ || isStartOfExpression(); case 16 /* Parameters */: - return isStartOfParameter( - /*isJSDocParameter*/ - false - ); + return isStartOfParameter( /*isJSDocParameter*/ + false); case 17 /* JSDocParameters */: - return isStartOfParameter( - /*isJSDocParameter*/ - true - ); + return isStartOfParameter( /*isJSDocParameter*/ + true); case 20 /* TypeArguments */: case 21 /* TupleElementTypes */: return token() === 28 /* CommaToken */ || isStartOfType(); @@ -30087,6 +29091,7 @@ ${lanes.join("\n")} const next = nextToken(); return next === 28 /* CommaToken */ || next === 19 /* OpenBraceToken */ || next === 96 /* ExtendsKeyword */ || next === 119 /* ImplementsKeyword */; } + return true; } function nextTokenIsIdentifier() { @@ -30176,11 +29181,8 @@ ${lanes.join("\n")} Debug.assert(parsingContext, "Missing parsing context"); for (let kind = 0; kind < 26 /* Count */; kind++) { if (parsingContext & 1 << kind) { - if (isListElement2( - kind, - /*inErrorRecovery*/ - true - ) || isListTerminator(kind)) { + if (isListElement2(kind, /*inErrorRecovery*/ + true) || isListTerminator(kind)) { return true; } } @@ -30193,11 +29195,8 @@ ${lanes.join("\n")} const list = []; const listPos = getNodePos(); while (!isListTerminator(kind)) { - if (isListElement2( - kind, - /*inErrorRecovery*/ - false - )) { + if (isListElement2(kind, /*inErrorRecovery*/ + false)) { list.push(parseListElement(kind, parseElement)); continue; } @@ -30220,7 +29219,7 @@ ${lanes.join("\n")} if (!syntaxCursor || !isReusableParsingContext(parsingContext2) || parseErrorBeforeNextFinishedNode) { return void 0; } - const node = syntaxCursor.currentNode(pos ?? scanner2.getTokenFullStart()); + const node = syntaxCursor.currentNode(pos !== null && pos !== void 0 ? pos : scanner2.getTokenFullStart()); if (nodeIsMissing(node) || node.intersectsChange || containsParseError(node)) { return void 0; } @@ -30347,6 +29346,7 @@ ${lanes.join("\n")} function isReusableEnumMember(node) { return node.kind === 306 /* EnumMember */; } + function isReusableTypeMember(node) { if (node) { switch (node.kind) { @@ -30451,11 +29451,8 @@ ${lanes.join("\n")} const listPos = getNodePos(); let commaStart = -1; while (true) { - if (isListElement2( - kind, - /*inErrorRecovery*/ - false - )) { + if (isListElement2(kind, /*inErrorRecovery*/ + false)) { const startPos = scanner2.getTokenFullStart(); const result = parseListElement(kind, parseElement); if (!result) { @@ -30488,13 +29485,8 @@ ${lanes.join("\n")} } } parsingContext = saveParsingContext; - return createNodeArray( - list, - listPos, - /*end*/ - void 0, - commaStart >= 0 - ); + return createNodeArray(list, listPos, /*end*/ + void 0, commaStart >= 0); } function getExpectedCommaDiagnostic(kind) { return kind === 6 /* EnumMembers */ ? Diagnostics.An_enum_member_name_must_be_followed_by_a_or : void 0; @@ -30522,19 +29514,9 @@ ${lanes.join("\n")} if (token() === 30 /* LessThanToken */) { break; } - entity = finishNode( - factory2.createQualifiedName( - entity, - parseRightSideOfDot( - allowReservedWords, - /*allowPrivateIdentifiers*/ - false, - /*allowUnicodeEscapeSequenceInIdentifierName*/ - true - ) - ), - pos - ); + entity = finishNode(factory2.createQualifiedName(entity, parseRightSideOfDot(allowReservedWords, /*allowPrivateIdentifiers*/ + false, /*allowUnicodeEscapeSequenceInIdentifierName*/ + true)), pos); } return entity; } @@ -30545,22 +29527,14 @@ ${lanes.join("\n")} if (scanner2.hasPrecedingLineBreak() && tokenIsIdentifierOrKeyword(token())) { const matchesPattern = lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine); if (matchesPattern) { - return createMissingNode( - 80 /* Identifier */, - /*reportAtCurrentPosition*/ - true, - Diagnostics.Identifier_expected - ); + return createMissingNode(80 /* Identifier */, /*reportAtCurrentPosition*/ + true, Diagnostics.Identifier_expected); } } if (token() === 81 /* PrivateIdentifier */) { const node = parsePrivateIdentifier(); - return allowPrivateIdentifiers ? node : createMissingNode( - 80 /* Identifier */, - /*reportAtCurrentPosition*/ - true, - Diagnostics.Identifier_expected - ); + return allowPrivateIdentifiers ? node : createMissingNode(80 /* Identifier */, /*reportAtCurrentPosition*/ + true, Diagnostics.Identifier_expected); } if (allowIdentifierNames) { return allowUnicodeEscapeSequenceInIdentifierName ? parseIdentifierName() : parseIdentifierNameErrorOnUnicodeEscapeSequence(); @@ -30579,26 +29553,12 @@ ${lanes.join("\n")} } function parseTemplateExpression(isTaggedTemplate) { const pos = getNodePos(); - return finishNode( - factory2.createTemplateExpression( - parseTemplateHead(isTaggedTemplate), - parseTemplateSpans(isTaggedTemplate) - ), - pos - ); + return finishNode(factory2.createTemplateExpression(parseTemplateHead(isTaggedTemplate), parseTemplateSpans(isTaggedTemplate)), pos); } function parseTemplateType() { const pos = getNodePos(); - return finishNode( - factory2.createTemplateLiteralType( - parseTemplateHead( - /*isTaggedTemplate*/ - false - ), - parseTemplateTypeSpans() - ), - pos - ); + return finishNode(factory2.createTemplateLiteralType(parseTemplateHead( /*isTaggedTemplate*/ + false), parseTemplateTypeSpans()), pos); } function parseTemplateTypeSpans() { const pos = getNodePos(); @@ -30612,16 +29572,8 @@ ${lanes.join("\n")} } function parseTemplateTypeSpan() { const pos = getNodePos(); - return finishNode( - factory2.createTemplateLiteralTypeSpan( - parseType(), - parseLiteralOfTemplateSpan( - /*isTaggedTemplate*/ - false - ) - ), - pos - ); + return finishNode(factory2.createTemplateLiteralTypeSpan(parseType(), parseLiteralOfTemplateSpan( /*isTaggedTemplate*/ + false)), pos); } function parseLiteralOfTemplateSpan(isTaggedTemplate) { if (token() === 20 /* CloseBraceToken */) { @@ -30631,25 +29583,18 @@ ${lanes.join("\n")} return parseExpectedToken(18 /* TemplateTail */, Diagnostics._0_expected, tokenToString(20 /* CloseBraceToken */)); } } + function parseTemplateSpan(isTaggedTemplate) { const pos = getNodePos(); - return finishNode( - factory2.createTemplateSpan( - allowInAnd(parseExpression), - parseLiteralOfTemplateSpan(isTaggedTemplate) - ), - pos - ); + return finishNode(factory2.createTemplateSpan(allowInAnd(parseExpression), parseLiteralOfTemplateSpan(isTaggedTemplate)), pos); } function parseLiteralNode() { return parseLiteralLikeNode(token()); } function parseTemplateHead(isTaggedTemplate) { if (!isTaggedTemplate && scanner2.getTokenFlags() & 26656 /* IsInvalid */) { - reScanTemplateToken( - /*isTaggedTemplate*/ - false - ); + reScanTemplateToken( /*isTaggedTemplate*/ + false); } const fragment = parseLiteralLikeNode(token()); Debug.assert(fragment.kind === 16 /* TemplateHead */, "Template head has wrong token kind"); @@ -30667,19 +29612,14 @@ ${lanes.join("\n")} } function parseLiteralLikeNode(kind) { const pos = getNodePos(); - const node = isTemplateLiteralKind(kind) ? factory2.createTemplateLiteralLikeNode(kind, scanner2.getTokenValue(), getTemplateLiteralRawText(kind), scanner2.getTokenFlags() & 7176 /* TemplateLiteralLikeFlags */) : ( - // Note that theoretically the following condition would hold true literals like 009, - // which is not octal. But because of how the scanner separates the tokens, we would - // never get a token like this. Instead, we would get 00 and 9 as two separate tokens. - // We also do not need to check for negatives because any prefix operator would be part of a - // parent unary expression. - kind === 9 /* NumericLiteral */ ? factoryCreateNumericLiteral(scanner2.getTokenValue(), scanner2.getNumericLiteralFlags()) : kind === 11 /* StringLiteral */ ? factoryCreateStringLiteral( - scanner2.getTokenValue(), - /*isSingleQuote*/ - void 0, - scanner2.hasExtendedUnicodeEscape() - ) : isLiteralKind(kind) ? factoryCreateLiteralLikeNode(kind, scanner2.getTokenValue()) : Debug.fail() - ); + const node = isTemplateLiteralKind(kind) ? factory2.createTemplateLiteralLikeNode(kind, scanner2.getTokenValue(), getTemplateLiteralRawText(kind), scanner2.getTokenFlags() & 7176 /* TemplateLiteralLikeFlags */) : + // Note that theoretically the following condition would hold true literals like 009, + // which is not octal. But because of how the scanner separates the tokens, we would + // never get a token like this. Instead, we would get 00 and 9 as two separate tokens. + // We also do not need to check for negatives because any prefix operator would be part of a + // parent unary expression. + kind === 9 /* NumericLiteral */ ? factoryCreateNumericLiteral(scanner2.getTokenValue(), scanner2.getNumericLiteralFlags()) : kind === 11 /* StringLiteral */ ? factoryCreateStringLiteral(scanner2.getTokenValue(), /*isSingleQuote*/ + void 0, scanner2.hasExtendedUnicodeEscape()) : isLiteralKind(kind) ? factoryCreateLiteralLikeNode(kind, scanner2.getTokenValue()) : Debug.fail(); if (scanner2.hasExtendedUnicodeEscape()) { node.hasExtendedUnicodeEscape = true; } @@ -30690,36 +29630,32 @@ ${lanes.join("\n")} return finishNode(node, pos); } function parseEntityNameOfTypeReference() { - return parseEntityName( - /*allowReservedWords*/ - true, - Diagnostics.Type_expected - ); + return parseEntityName( /*allowReservedWords*/ + true, Diagnostics.Type_expected); } function parseTypeArgumentsOfTypeReference() { if (!scanner2.hasPrecedingLineBreak() && reScanLessThanToken() === 30 /* LessThanToken */) { return parseBracketedList(20 /* TypeArguments */, parseType, 30 /* LessThanToken */, 32 /* GreaterThanToken */); } } + function parseTypeReference() { const pos = getNodePos(); - return finishNode( - factory2.createTypeReferenceNode( - parseEntityNameOfTypeReference(), - parseTypeArgumentsOfTypeReference() - ), - pos - ); + return finishNode(factory2.createTypeReferenceNode(parseEntityNameOfTypeReference(), parseTypeArgumentsOfTypeReference()), pos); } function typeHasArrowFunctionBlockingParseError(node) { switch (node.kind) { case 183 /* TypeReference */: return nodeIsMissing(node.typeName); case 184 /* FunctionType */: - case 185 /* ConstructorType */: { - const { parameters, type } = node; - return isMissingList(parameters) || typeHasArrowFunctionBlockingParseError(type); - } + case 185 /* ConstructorType */: + { + const { + parameters, + type + } = node; + return isMissingList(parameters) || typeHasArrowFunctionBlockingParseError(type); + } case 196 /* ParenthesizedType */: return typeHasArrowFunctionBlockingParseError(node.type); default: @@ -30728,12 +29664,8 @@ ${lanes.join("\n")} } function parseThisTypePredicate(lhs) { nextToken(); - return finishNode(factory2.createTypePredicateNode( - /*assertsModifier*/ - void 0, - lhs, - parseType() - ), lhs.pos); + return finishNode(factory2.createTypePredicateNode( /*assertsModifier*/ + void 0, lhs, parseType()), lhs.pos); } function parseThisTypeNode() { const pos = getNodePos(); @@ -30748,11 +29680,8 @@ ${lanes.join("\n")} function parseJSDocNonNullableType() { const pos = getNodePos(); nextToken(); - return finishNode(factory2.createJSDocNonNullableType( - parseNonArrayType(), - /*postfix*/ - false - ), pos); + return finishNode(factory2.createJSDocNonNullableType(parseNonArrayType(), /*postfix*/ + false), pos); } function parseJSDocUnknownOrNullableType() { const pos = getNodePos(); @@ -30760,11 +29689,8 @@ ${lanes.join("\n")} if (token() === 28 /* CommaToken */ || token() === 20 /* CloseBraceToken */ || token() === 22 /* CloseParenToken */ || token() === 32 /* GreaterThanToken */ || token() === 64 /* EqualsToken */ || token() === 52 /* BarToken */) { return finishNode(factory2.createJSDocUnknownType(), pos); } else { - return finishNode(factory2.createJSDocNullableType( - parseType(), - /*postfix*/ - false - ), pos); + return finishNode(factory2.createJSDocNullableType(parseType(), /*postfix*/ + false), pos); } } function parseJSDocFunctionType() { @@ -30773,18 +29699,12 @@ ${lanes.join("\n")} if (lookAhead(nextTokenIsOpenParen)) { nextToken(); const parameters = parseParameters(4 /* Type */ | 32 /* JSDoc */); - const type = parseReturnType( - 59 /* ColonToken */, - /*isType*/ - false - ); + const type = parseReturnType(59 /* ColonToken */, /*isType*/ + false); return withJSDoc(finishNode(factory2.createJSDocFunctionType(parameters, type), pos), hasJSDoc); } - return finishNode(factory2.createTypeReferenceNode( - parseIdentifierName(), - /*typeArguments*/ - void 0 - ), pos); + return finishNode(factory2.createTypeReferenceNode(parseIdentifierName(), /*typeArguments*/ + void 0), pos); } function parseJSDocParameter() { const pos = getNodePos(); @@ -30793,43 +29713,32 @@ ${lanes.join("\n")} name = parseIdentifierName(); parseExpected(59 /* ColonToken */); } - return finishNode( - factory2.createParameterDeclaration( - /*modifiers*/ - void 0, - /*dotDotDotToken*/ - void 0, - // TODO(rbuckton): JSDoc parameters don't have names (except `this`/`new`), should we manufacture an empty identifier? - name, - /*questionToken*/ - void 0, - parseJSDocType(), - /*initializer*/ - void 0 - ), - pos - ); + + return finishNode(factory2.createParameterDeclaration( /*modifiers*/ + void 0, /*dotDotDotToken*/ + void 0, + // TODO(rbuckton): JSDoc parameters don't have names (except `this`/`new`), should we manufacture an empty identifier? + name, /*questionToken*/ + void 0, parseJSDocType(), /*initializer*/ + void 0), pos); } function parseJSDocType() { scanner2.setInJSDocType(true); const pos = getNodePos(); if (parseOptional(144 /* ModuleKeyword */)) { - const moduleTag = factory2.createJSDocNamepathType( - /*type*/ - void 0 - ); - terminate: - while (true) { - switch (token()) { - case 20 /* CloseBraceToken */: - case 1 /* EndOfFileToken */: - case 28 /* CommaToken */: - case 5 /* WhitespaceTrivia */: - break terminate; - default: - nextTokenJSDoc(); - } + const moduleTag = factory2.createJSDocNamepathType( /*type*/ + void 0); + terminate: while (true) { + switch (token()) { + case 20 /* CloseBraceToken */: + case 1 /* EndOfFileToken */: + case 28 /* CommaToken */: + case 5 /* WhitespaceTrivia */: + break terminate; + default: + nextTokenJSDoc(); } + } scanner2.setInJSDocType(false); return finishNode(moduleTag, pos); } @@ -30848,21 +29757,16 @@ ${lanes.join("\n")} function parseTypeQuery() { const pos = getNodePos(); parseExpected(114 /* TypeOfKeyword */); - const entityName = parseEntityName( - /*allowReservedWords*/ - true - ); + const entityName = parseEntityName( /*allowReservedWords*/ + true); const typeArguments = !scanner2.hasPrecedingLineBreak() ? tryParseTypeArguments() : void 0; return finishNode(factory2.createTypeQueryNode(entityName, typeArguments), pos); } function parseTypeParameter() { const pos = getNodePos(); - const modifiers = parseModifiers( - /*allowDecorators*/ - false, - /*permitConstAsModifier*/ - true - ); + const modifiers = parseModifiers( /*allowDecorators*/ + false, /*permitConstAsModifier*/ + true); const name = parseIdentifier(); let constraint; let expression; @@ -30883,11 +29787,10 @@ ${lanes.join("\n")} return parseBracketedList(19 /* TypeParameters */, parseTypeParameter, 30 /* LessThanToken */, 32 /* GreaterThanToken */); } } + function isStartOfParameter(isJSDocParameter) { - return token() === 26 /* DotDotDotToken */ || isBindingIdentifierOrPrivateIdentifierOrPattern() || isModifierKind(token()) || token() === 60 /* AtToken */ || isStartOfType( - /*inStartOfParameter*/ - !isJSDocParameter - ); + return token() === 26 /* DotDotDotToken */ || isBindingIdentifierOrPrivateIdentifierOrPattern() || isModifierKind(token()) || token() === 60 /* AtToken */ || isStartOfType( /*inStartOfParameter*/ + !isJSDocParameter); } function parseNameOfParameter(modifiers) { const name = parseIdentifierOrPattern(Diagnostics.Private_identifiers_cannot_be_used_as_parameters); @@ -30899,41 +29802,26 @@ ${lanes.join("\n")} function isParameterNameStart() { return isBindingIdentifier() || token() === 23 /* OpenBracketToken */ || token() === 19 /* OpenBraceToken */; } + function parseParameter(inOuterAwaitContext) { return parseParameterWorker(inOuterAwaitContext); } function parseParameterForSpeculation(inOuterAwaitContext) { - return parseParameterWorker( - inOuterAwaitContext, - /*allowAmbiguity*/ - false - ); + return parseParameterWorker(inOuterAwaitContext, /*allowAmbiguity*/ + false); } function parseParameterWorker(inOuterAwaitContext, allowAmbiguity = true) { const pos = getNodePos(); const hasJSDoc = hasPrecedingJSDocComment(); - const modifiers = inOuterAwaitContext ? doInAwaitContext(() => parseModifiers( - /*allowDecorators*/ - true - )) : doOutsideOfAwaitContext(() => parseModifiers( - /*allowDecorators*/ - true - )); + const modifiers = inOuterAwaitContext ? doInAwaitContext(() => parseModifiers( /*allowDecorators*/ + true)) : doOutsideOfAwaitContext(() => parseModifiers( /*allowDecorators*/ + true)); if (token() === 110 /* ThisKeyword */) { - const node2 = factory2.createParameterDeclaration( - modifiers, - /*dotDotDotToken*/ - void 0, - createIdentifier( - /*isIdentifier*/ - true - ), - /*questionToken*/ - void 0, - parseTypeAnnotation(), - /*initializer*/ - void 0 - ); + const node2 = factory2.createParameterDeclaration(modifiers, /*dotDotDotToken*/ + void 0, createIdentifier( /*isIdentifier*/ + true), /*questionToken*/ + void 0, parseTypeAnnotation(), /*initializer*/ + void 0); const modifier = firstOrUndefined(modifiers); if (modifier) { parseErrorAtRange(modifier, Diagnostics.Neither_decorators_nor_modifiers_may_be_applied_to_this_parameters); @@ -30946,20 +29834,7 @@ ${lanes.join("\n")} if (!allowAmbiguity && !isParameterNameStart()) { return void 0; } - const node = withJSDoc( - finishNode( - factory2.createParameterDeclaration( - modifiers, - dotDotDotToken, - parseNameOfParameter(modifiers), - parseOptionalToken(58 /* QuestionToken */), - parseTypeAnnotation(), - parseInitializer() - ), - pos - ), - hasJSDoc - ); + const node = withJSDoc(finishNode(factory2.createParameterDeclaration(modifiers, dotDotDotToken, parseNameOfParameter(modifiers), parseOptionalToken(58 /* QuestionToken */), parseTypeAnnotation(), parseInitializer()), pos), hasJSDoc); topLevel = savedTopLevel; return node; } @@ -30995,11 +29870,8 @@ ${lanes.join("\n")} if (!parseExpected(21 /* OpenParenToken */)) { return createMissingList(); } - const parameters = parseParametersWorker( - flags, - /*allowAmbiguity*/ - true - ); + const parameters = parseParametersWorker(flags, /*allowAmbiguity*/ + true); parseExpected(22 /* CloseParenToken */); return parameters; } @@ -31015,13 +29887,11 @@ ${lanes.join("\n")} if (kind === 180 /* ConstructSignature */) { parseExpected(105 /* NewKeyword */); } + const typeParameters = parseTypeParameters(); const parameters = parseParameters(4 /* Type */); - const type = parseReturnType( - 59 /* ColonToken */, - /*isType*/ - true - ); + const type = parseReturnType(59 /* ColonToken */, /*isType*/ + true); parseTypeMemberSemicolon(); const node = kind === 179 /* CallSignature */ ? factory2.createCallSignature(typeParameters, parameters, type) : factory2.createConstructSignature(typeParameters, parameters, type); return withJSDoc(finishNode(node, pos), hasJSDoc); @@ -31053,11 +29923,10 @@ ${lanes.join("\n")} nextToken(); return token() === 59 /* ColonToken */ || token() === 28 /* CommaToken */ || token() === 24 /* CloseBracketToken */; } + function parseIndexSignatureDeclaration(pos, hasJSDoc, modifiers) { - const parameters = parseBracketedList(16 /* Parameters */, () => parseParameter( - /*inOuterAwaitContext*/ - false - ), 23 /* OpenBracketToken */, 24 /* CloseBracketToken */); + const parameters = parseBracketedList(16 /* Parameters */, () => parseParameter( /*inOuterAwaitContext*/ + false), 23 /* OpenBracketToken */, 24 /* CloseBracketToken */); const type = parseTypeAnnotation(); parseTypeMemberSemicolon(); const node = factory2.createIndexSignature(modifiers, parameters, type); @@ -31070,17 +29939,13 @@ ${lanes.join("\n")} if (token() === 21 /* OpenParenToken */ || token() === 30 /* LessThanToken */) { const typeParameters = parseTypeParameters(); const parameters = parseParameters(4 /* Type */); - const type = parseReturnType( - 59 /* ColonToken */, - /*isType*/ - true - ); + const type = parseReturnType(59 /* ColonToken */, /*isType*/ + true); node = factory2.createMethodSignature(modifiers, name, questionToken, typeParameters, parameters, type); } else { const type = parseTypeAnnotation(); node = factory2.createPropertySignature(modifiers, name, questionToken, type); - if (token() === 64 /* EqualsToken */) - node.initializer = parseInitializer(); + if (token() === 64 /* EqualsToken */) node.initializer = parseInitializer(); } parseTypeMemberSemicolon(); return withJSDoc(finishNode(node, pos), hasJSDoc); @@ -31110,21 +29975,23 @@ ${lanes.join("\n")} if (token() === 21 /* OpenParenToken */ || token() === 30 /* LessThanToken */) { return parseSignatureMember(179 /* CallSignature */); } + if (token() === 105 /* NewKeyword */ && lookAhead(nextTokenIsOpenParenOrLessThan)) { return parseSignatureMember(180 /* ConstructSignature */); } + const pos = getNodePos(); const hasJSDoc = hasPrecedingJSDocComment(); - const modifiers = parseModifiers( - /*allowDecorators*/ - false - ); + const modifiers = parseModifiers( /*allowDecorators*/ + false); if (parseContextualModifier(139 /* GetKeyword */)) { return parseAccessorDeclaration(pos, hasJSDoc, modifiers, 177 /* GetAccessor */, 4 /* Type */); } + if (parseContextualModifier(153 /* SetKeyword */)) { return parseAccessorDeclaration(pos, hasJSDoc, modifiers, 178 /* SetAccessor */, 4 /* Type */); } + if (isIndexSignature()) { return parseIndexSignatureDeclaration(pos, hasJSDoc, modifiers); } @@ -31134,9 +30001,11 @@ ${lanes.join("\n")} nextToken(); return token() === 21 /* OpenParenToken */ || token() === 30 /* LessThanToken */; } + function nextTokenIsDot() { return nextToken() === 25 /* DotToken */; } + function nextTokenIsOpenParenOrLessThanOrDot() { switch (nextToken()) { case 21 /* OpenParenToken */: @@ -31165,24 +30034,21 @@ ${lanes.join("\n")} if (token() === 40 /* PlusToken */ || token() === 41 /* MinusToken */) { return nextToken() === 148 /* ReadonlyKeyword */; } + if (token() === 148 /* ReadonlyKeyword */) { nextToken(); } return token() === 23 /* OpenBracketToken */ && nextTokenIsIdentifier() && nextToken() === 103 /* InKeyword */; } + function parseMappedTypeParameter() { const pos = getNodePos(); const name = parseIdentifierName(); parseExpected(103 /* InKeyword */); const type = parseType(); - return finishNode(factory2.createTypeParameterDeclaration( - /*modifiers*/ - void 0, - name, - type, - /*defaultType*/ - void 0 - ), pos); + return finishNode(factory2.createTypeParameterDeclaration( /*modifiers*/ + void 0, name, type, /*defaultType*/ + void 0), pos); } function parseMappedType() { const pos = getNodePos(); @@ -31194,6 +30060,7 @@ ${lanes.join("\n")} parseExpected(148 /* ReadonlyKeyword */); } } + parseExpected(23 /* OpenBracketToken */); const typeParameter = parseMappedTypeParameter(); const nameType = parseOptional(130 /* AsKeyword */) ? parseType() : void 0; @@ -31205,6 +30072,7 @@ ${lanes.join("\n")} parseExpected(58 /* QuestionToken */); } } + const type = parseTypeAnnotation(); parseSemicolon(); const members = parseList(4 /* TypeMembers */, parseTypeMember); @@ -31228,6 +30096,7 @@ ${lanes.join("\n")} function isNextTokenColonOrQuestionColon() { return nextToken() === 59 /* ColonToken */ || token() === 58 /* QuestionToken */ && nextToken() === 59 /* ColonToken */; } + function isTupleElementName() { if (token() === 26 /* DotDotDotToken */) { return tokenIsIdentifierOrKeyword(nextToken()) && isNextTokenColonOrQuestionColon(); @@ -31250,12 +30119,7 @@ ${lanes.join("\n")} } function parseTupleType() { const pos = getNodePos(); - return finishNode( - factory2.createTupleTypeNode( - parseBracketedList(21 /* TupleElementTypes */, parseTupleElementNameOrTupleElementType, 23 /* OpenBracketToken */, 24 /* CloseBracketToken */) - ), - pos - ); + return finishNode(factory2.createTupleTypeNode(parseBracketedList(21 /* TupleElementTypes */, parseTupleElementNameOrTupleElementType, 23 /* OpenBracketToken */, 24 /* CloseBracketToken */)), pos); } function parseParenthesizedType() { const pos = getNodePos(); @@ -31282,11 +30146,8 @@ ${lanes.join("\n")} Debug.assert(!modifiers || isConstructorType, "Per isStartOfFunctionOrConstructorType, a function type cannot have modifiers."); const typeParameters = parseTypeParameters(); const parameters = parseParameters(4 /* Type */); - const type = parseReturnType( - 39 /* EqualsGreaterThanToken */, - /*isType*/ - false - ); + const type = parseReturnType(39 /* EqualsGreaterThanToken */, /*isType*/ + false); const node = isConstructorType ? factory2.createConstructorTypeNode(modifiers, typeParameters, parameters, type) : factory2.createFunctionTypeNode(typeParameters, parameters, type); return withJSDoc(finishNode(node, pos), hasJSDoc); } @@ -31309,6 +30170,7 @@ ${lanes.join("\n")} nextToken(); return token() === 102 /* ImportKeyword */; } + function parseImportType() { sourceFlags |= 4194304 /* PossiblyContainsDynamicImport */; const pos = getNodePos(); @@ -31326,19 +30188,14 @@ ${lanes.join("\n")} } else { parseErrorAtCurrentToken(Diagnostics._0_expected, tokenToString(118 /* WithKeyword */)); } + parseExpected(59 /* ColonToken */); - attributes = parseImportAttributes( - currentToken2, - /*skipKeyword*/ - true - ); + attributes = parseImportAttributes(currentToken2, /*skipKeyword*/ + true); if (!parseExpected(20 /* CloseBraceToken */)) { const lastError = lastOrUndefined(parseDiagnostics); if (lastError && lastError.code === Diagnostics._0_expected.code) { - addRelatedInfo( - lastError, - createDetachedDiagnostic(fileName, sourceText, openBracePosition, 1, Diagnostics.The_parser_expected_to_find_a_1_to_match_the_0_token_here, "{", "}") - ); + addRelatedInfo(lastError, createDetachedDiagnostic(fileName, sourceText, openBracePosition, 1, Diagnostics.The_parser_expected_to_find_a_1_to_match_the_0_token_here, "{", "}")); } } } @@ -31351,6 +30208,7 @@ ${lanes.join("\n")} nextToken(); return token() === 9 /* NumericLiteral */ || token() === 10 /* BigIntLiteral */; } + function parseNonArrayType() { switch (token()) { case 133 /* AnyKeyword */: @@ -31385,20 +30243,19 @@ ${lanes.join("\n")} case 106 /* NullKeyword */: return parseLiteralTypeNode(); case 41 /* MinusToken */: - return lookAhead(nextTokenIsNumericOrBigIntLiteral) ? parseLiteralTypeNode( - /*negative*/ - true - ) : parseTypeReference(); + return lookAhead(nextTokenIsNumericOrBigIntLiteral) ? parseLiteralTypeNode( /*negative*/ + true) : parseTypeReference(); case 116 /* VoidKeyword */: return parseTokenNode(); - case 110 /* ThisKeyword */: { - const thisKeyword = parseThisTypeNode(); - if (token() === 142 /* IsKeyword */ && !scanner2.hasPrecedingLineBreak()) { - return parseThisTypePredicate(thisKeyword); - } else { - return thisKeyword; + case 110 /* ThisKeyword */: + { + const thisKeyword = parseThisTypeNode(); + if (token() === 142 /* IsKeyword */ && !scanner2.hasPrecedingLineBreak()) { + return parseThisTypePredicate(thisKeyword); + } else { + return thisKeyword; + } } - } case 114 /* TypeOfKeyword */: return lookAhead(isStartOfTypeOfImportType) ? parseImportType() : parseTypeQuery(); case 19 /* OpenBraceToken */: @@ -31468,10 +30325,8 @@ ${lanes.join("\n")} } function isStartOfParenthesizedOrFunctionType() { nextToken(); - return token() === 22 /* CloseParenToken */ || isStartOfParameter( - /*isJSDocParameter*/ - false - ) || isStartOfType(); + return token() === 22 /* CloseParenToken */ || isStartOfParameter( /*isJSDocParameter*/ + false) || isStartOfType(); } function parsePostfixTypeOrHigher() { const pos = getNodePos(); @@ -31480,22 +30335,16 @@ ${lanes.join("\n")} switch (token()) { case 54 /* ExclamationToken */: nextToken(); - type = finishNode(factory2.createJSDocNonNullableType( - type, - /*postfix*/ - true - ), pos); + type = finishNode(factory2.createJSDocNonNullableType(type, /*postfix*/ + true), pos); break; case 58 /* QuestionToken */: if (lookAhead(nextTokenIsStartOfType)) { return type; } nextToken(); - type = finishNode(factory2.createJSDocNullableType( - type, - /*postfix*/ - true - ), pos); + type = finishNode(factory2.createJSDocNullableType(type, /*postfix*/ + true), pos); break; case 23 /* OpenBracketToken */: parseExpected(23 /* OpenBracketToken */); @@ -31531,12 +30380,8 @@ ${lanes.join("\n")} const pos = getNodePos(); const name = parseIdentifier(); const constraint = tryParse(tryParseConstraintOfInferType); - const node = factory2.createTypeParameterDeclaration( - /*modifiers*/ - void 0, - name, - constraint - ); + const node = factory2.createTypeParameterDeclaration( /*modifiers*/ + void 0, name, constraint); return finishNode(node, pos); } function parseInferType() { @@ -31594,6 +30439,7 @@ ${lanes.join("\n")} nextToken(); return token() === 105 /* NewKeyword */; } + function isStartOfFunctionTypeOrConstructorType() { if (token() === 30 /* LessThanToken */) { return true; @@ -31605,10 +30451,8 @@ ${lanes.join("\n")} } function skipParameterStart() { if (isModifierKind(token())) { - parseModifiers( - /*allowDecorators*/ - false - ); + parseModifiers( /*allowDecorators*/ + false); } if (isIdentifier2() || token() === 110 /* ThisKeyword */) { nextToken(); @@ -31644,12 +30488,8 @@ ${lanes.join("\n")} const typePredicateVariable = isIdentifier2() && tryParse(parseTypePredicatePrefix); const type = parseType(); if (typePredicateVariable) { - return finishNode(factory2.createTypePredicateNode( - /*assertsModifier*/ - void 0, - typePredicateVariable, - type - ), pos); + return finishNode(factory2.createTypePredicateNode( /*assertsModifier*/ + void 0, typePredicateVariable, type), pos); } else { return type; } @@ -31751,36 +30591,26 @@ ${lanes.join("\n")} function parseExpression() { const saveDecoratorContext = inDecoratorContext(); if (saveDecoratorContext) { - setDecoratorContext( - /*val*/ - false - ); + setDecoratorContext( /*val*/ + false); } const pos = getNodePos(); - let expr = parseAssignmentExpressionOrHigher( - /*allowReturnTypeInArrowFunction*/ - true - ); + let expr = parseAssignmentExpressionOrHigher( /*allowReturnTypeInArrowFunction*/ + true); let operatorToken; while (operatorToken = parseOptionalToken(28 /* CommaToken */)) { - expr = makeBinaryExpression(expr, operatorToken, parseAssignmentExpressionOrHigher( - /*allowReturnTypeInArrowFunction*/ - true - ), pos); + expr = makeBinaryExpression(expr, operatorToken, parseAssignmentExpressionOrHigher( /*allowReturnTypeInArrowFunction*/ + true), pos); } if (saveDecoratorContext) { - setDecoratorContext( - /*val*/ - true - ); + setDecoratorContext( /*val*/ + true); } return expr; } function parseInitializer() { - return parseOptional(64 /* EqualsToken */) ? parseAssignmentExpressionOrHigher( - /*allowReturnTypeInArrowFunction*/ - true - ) : void 0; + return parseOptional(64 /* EqualsToken */) ? parseAssignmentExpressionOrHigher( /*allowReturnTypeInArrowFunction*/ + true) : void 0; } function parseAssignmentExpressionOrHigher(allowReturnTypeInArrowFunction) { if (isYieldExpression2()) { @@ -31794,14 +30624,8 @@ ${lanes.join("\n")} const hasJSDoc = hasPrecedingJSDocComment(); const expr = parseBinaryExpressionOrHigher(0 /* Lowest */); if (expr.kind === 80 /* Identifier */ && token() === 39 /* EqualsGreaterThanToken */) { - return parseSimpleArrowFunctionExpression( - pos, - expr, - allowReturnTypeInArrowFunction, - hasJSDoc, - /*asyncModifier*/ - void 0 - ); + return parseSimpleArrowFunctionExpression(pos, expr, allowReturnTypeInArrowFunction, hasJSDoc, /*asyncModifier*/ + void 0); } if (isLeftHandSideExpression(expr) && isAssignmentOperator(reScanGreaterToken())) { return makeBinaryExpression(expr, parseTokenNode(), parseAssignmentExpressionOrHigher(allowReturnTypeInArrowFunction), pos); @@ -31825,58 +30649,30 @@ ${lanes.join("\n")} const pos = getNodePos(); nextToken(); if (!scanner2.hasPrecedingLineBreak() && (token() === 42 /* AsteriskToken */ || isStartOfExpression())) { - return finishNode( - factory2.createYieldExpression( - parseOptionalToken(42 /* AsteriskToken */), - parseAssignmentExpressionOrHigher( - /*allowReturnTypeInArrowFunction*/ - true - ) - ), - pos - ); + return finishNode(factory2.createYieldExpression(parseOptionalToken(42 /* AsteriskToken */), parseAssignmentExpressionOrHigher( /*allowReturnTypeInArrowFunction*/ + true)), pos); } else { - return finishNode(factory2.createYieldExpression( - /*asteriskToken*/ - void 0, - /*expression*/ - void 0 - ), pos); + return finishNode(factory2.createYieldExpression( /*asteriskToken*/ + void 0, /*expression*/ + void 0), pos); } } function parseSimpleArrowFunctionExpression(pos, identifier, allowReturnTypeInArrowFunction, hasJSDoc, asyncModifier) { Debug.assert(token() === 39 /* EqualsGreaterThanToken */, "parseSimpleArrowFunctionExpression should only have been called if we had a =>"); - const parameter = factory2.createParameterDeclaration( - /*modifiers*/ - void 0, - /*dotDotDotToken*/ - void 0, - identifier, - /*questionToken*/ - void 0, - /*type*/ - void 0, - /*initializer*/ - void 0 - ); + const parameter = factory2.createParameterDeclaration( /*modifiers*/ + void 0, /*dotDotDotToken*/ + void 0, identifier, /*questionToken*/ + void 0, /*type*/ + void 0, /*initializer*/ + void 0); finishNode(parameter, identifier.pos); const parameters = createNodeArray([parameter], parameter.pos, parameter.end); const equalsGreaterThanToken = parseExpectedToken(39 /* EqualsGreaterThanToken */); - const body = parseArrowFunctionExpressionBody( - /*isAsync*/ - !!asyncModifier, - allowReturnTypeInArrowFunction - ); - const node = factory2.createArrowFunction( - asyncModifier, - /*typeParameters*/ - void 0, - parameters, - /*type*/ - void 0, - equalsGreaterThanToken, - body - ); + const body = parseArrowFunctionExpressionBody( /*isAsync*/ + !!asyncModifier, allowReturnTypeInArrowFunction); + const node = factory2.createArrowFunction(asyncModifier, /*typeParameters*/ + void 0, parameters, /*type*/ + void 0, equalsGreaterThanToken, body); return withJSDoc(finishNode(node, pos), hasJSDoc); } function tryParseParenthesizedArrowFunctionExpression(allowReturnTypeInArrowFunction) { @@ -31884,12 +30680,9 @@ ${lanes.join("\n")} if (triState === 0 /* False */) { return void 0; } - return triState === 1 /* True */ ? parseParenthesizedArrowFunctionExpression( - /*allowAmbiguity*/ - true, - /*allowReturnTypeInArrowFunction*/ - true - ) : tryParse(() => parsePossibleParenthesizedArrowFunctionExpression(allowReturnTypeInArrowFunction)); + return triState === 1 /* True */ ? parseParenthesizedArrowFunctionExpression( /*allowAmbiguity*/ + true, /*allowReturnTypeInArrowFunction*/ + true) : tryParse(() => parsePossibleParenthesizedArrowFunctionExpression(allowReturnTypeInArrowFunction)); } function isParenthesizedArrowFunctionExpression() { if (token() === 21 /* OpenParenToken */ || token() === 30 /* LessThanToken */ || token() === 134 /* AsyncKeyword */) { @@ -31898,18 +30691,22 @@ ${lanes.join("\n")} if (token() === 39 /* EqualsGreaterThanToken */) { return 1 /* True */; } + return 0 /* False */; } + function isParenthesizedArrowFunctionExpressionWorker() { if (token() === 134 /* AsyncKeyword */) { nextToken(); if (scanner2.hasPrecedingLineBreak()) { return 0 /* False */; } + if (token() !== 21 /* OpenParenToken */ && token() !== 30 /* LessThanToken */) { return 0 /* False */; } } + const first2 = token(); const second = nextToken(); if (first2 === 21 /* OpenParenToken */) { @@ -31924,21 +30721,27 @@ ${lanes.join("\n")} return 0 /* False */; } } + if (second === 23 /* OpenBracketToken */ || second === 19 /* OpenBraceToken */) { return 2 /* Unknown */; } + if (second === 26 /* DotDotDotToken */) { return 1 /* True */; } + if (isModifierKind(second) && second !== 134 /* AsyncKeyword */ && lookAhead(nextTokenIsIdentifier)) { if (nextToken() === 130 /* AsKeyword */) { return 0 /* False */; } + return 1 /* True */; } + if (!isIdentifier2() && second !== 110 /* ThisKeyword */) { return 0 /* False */; } + switch (nextToken()) { case 59 /* ColonToken */: return 1 /* True */; @@ -31947,18 +30750,21 @@ ${lanes.join("\n")} if (token() === 59 /* ColonToken */ || token() === 28 /* CommaToken */ || token() === 64 /* EqualsToken */ || token() === 22 /* CloseParenToken */) { return 1 /* True */; } + return 0 /* False */; case 28 /* CommaToken */: case 64 /* EqualsToken */: case 22 /* CloseParenToken */: return 2 /* Unknown */; } + return 0 /* False */; } else { Debug.assert(first2 === 30 /* LessThanToken */); if (!isIdentifier2() && token() !== 87 /* ConstKeyword */) { return 0 /* False */; } + if (languageVariant === 1 /* JSX */) { const isArrowFunctionInJsx = lookAhead(() => { parseOptional(87 /* ConstKeyword */); @@ -31981,23 +30787,23 @@ ${lanes.join("\n")} if (isArrowFunctionInJsx) { return 1 /* True */; } + return 0 /* False */; } + return 2 /* Unknown */; } } + function parsePossibleParenthesizedArrowFunctionExpression(allowReturnTypeInArrowFunction) { const tokenPos = scanner2.getTokenStart(); if (notParenthesizedArrow == null ? void 0 : notParenthesizedArrow.has(tokenPos)) { return void 0; } - const result = parseParenthesizedArrowFunctionExpression( - /*allowAmbiguity*/ - false, - allowReturnTypeInArrowFunction - ); + const result = parseParenthesizedArrowFunctionExpression( /*allowAmbiguity*/ + false, allowReturnTypeInArrowFunction); if (!result) { - (notParenthesizedArrow || (notParenthesizedArrow = /* @__PURE__ */ new Set())).add(tokenPos); + (notParenthesizedArrow || (notParenthesizedArrow = /* @__PURE__ */new Set())).add(tokenPos); } return result; } @@ -32019,13 +30825,16 @@ ${lanes.join("\n")} if (scanner2.hasPrecedingLineBreak() || token() === 39 /* EqualsGreaterThanToken */) { return 0 /* False */; } + const expr = parseBinaryExpressionOrHigher(0 /* Lowest */); if (!scanner2.hasPrecedingLineBreak() && expr.kind === 80 /* Identifier */ && token() === 39 /* EqualsGreaterThanToken */) { return 1 /* True */; } } + return 0 /* False */; } + function parseParenthesizedArrowFunctionExpression(allowAmbiguity, allowReturnTypeInArrowFunction) { const pos = getNodePos(); const hasJSDoc = hasPrecedingJSDocComment(); @@ -32053,11 +30862,8 @@ ${lanes.join("\n")} } } const hasReturnColon = token() === 59 /* ColonToken */; - const type = parseReturnType( - 59 /* ColonToken */, - /*isType*/ - false - ); + const type = parseReturnType(59 /* ColonToken */, /*isType*/ + false); if (type && !allowAmbiguity && typeHasArrowFunctionBlockingParseError(type)) { return void 0; } @@ -32084,9 +30890,11 @@ ${lanes.join("\n")} if (token() === 19 /* OpenBraceToken */) { return parseFunctionBlock(isAsync ? 2 /* Await */ : 0 /* None */); } + if (token() !== 27 /* SemicolonToken */ && token() !== 100 /* FunctionKeyword */ && token() !== 86 /* ClassKeyword */ && isStartOfStatement() && !isStartOfExpressionStatement()) { return parseFunctionBlock(16 /* IgnoreMissingOpenBrace */ | (isAsync ? 2 /* Await */ : 0 /* None */)); } + const savedTopLevel = topLevel; topLevel = false; const node = isAsync ? doInAwaitContext(() => parseAssignmentExpressionOrHigher(allowReturnTypeInArrowFunction)) : doOutsideOfAwaitContext(() => parseAssignmentExpressionOrHigher(allowReturnTypeInArrowFunction)); @@ -32099,25 +30907,9 @@ ${lanes.join("\n")} return leftOperand; } let colonToken; - return finishNode( - factory2.createConditionalExpression( - leftOperand, - questionToken, - doOutsideOfContext(disallowInAndDecoratorContext, () => parseAssignmentExpressionOrHigher( - /*allowReturnTypeInArrowFunction*/ - false - )), - colonToken = parseExpectedToken(59 /* ColonToken */), - nodeIsPresent(colonToken) ? parseAssignmentExpressionOrHigher(allowReturnTypeInArrowFunction) : createMissingNode( - 80 /* Identifier */, - /*reportAtCurrentPosition*/ - false, - Diagnostics._0_expected, - tokenToString(59 /* ColonToken */) - ) - ), - pos - ); + return finishNode(factory2.createConditionalExpression(leftOperand, questionToken, doOutsideOfContext(disallowInAndDecoratorContext, () => parseAssignmentExpressionOrHigher( /*allowReturnTypeInArrowFunction*/ + false)), colonToken = parseExpectedToken(59 /* ColonToken */), nodeIsPresent(colonToken) ? parseAssignmentExpressionOrHigher(allowReturnTypeInArrowFunction) : createMissingNode(80 /* Identifier */, /*reportAtCurrentPosition*/ + false, Diagnostics._0_expected, tokenToString(59 /* ColonToken */))), pos); } function parseBinaryExpressionOrHigher(precedence) { const pos = getNodePos(); @@ -32127,6 +30919,7 @@ ${lanes.join("\n")} function isInOrOfKeyword(t) { return t === 103 /* InKeyword */ || t === 165 /* OfKeyword */; } + function parseBinaryExpressionRest(precedence, leftOperand, pos) { while (true) { reScanGreaterToken(); @@ -32206,7 +30999,9 @@ ${lanes.join("\n")} const simpleUnaryExpression = parseSimpleUnaryExpression(); if (token() === 43 /* AsteriskAsteriskToken */) { const pos = skipTrivia(sourceText, simpleUnaryExpression.pos); - const { end } = simpleUnaryExpression; + const { + end + } = simpleUnaryExpression; if (simpleUnaryExpression.kind === 216 /* TypeAssertionExpression */) { parseErrorAt(pos, end, Diagnostics.A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses); } else { @@ -32231,16 +31026,11 @@ ${lanes.join("\n")} return parseVoidExpression(); case 30 /* LessThanToken */: if (languageVariant === 1 /* JSX */) { - return parseJsxElementOrSelfClosingElementOrFragment( - /*inExpressionContext*/ - true, - /*topInvalidNodePosition*/ - void 0, - /*openingTag*/ - void 0, - /*mustBeUnary*/ - true - ); + return parseJsxElementOrSelfClosingElementOrFragment( /*inExpressionContext*/ + true, /*topInvalidNodePosition*/ + void 0, /*openingTag*/ + void 0, /*mustBeUnary*/ + true); } return parseTypeAssertion(); case 135 /* AwaitKeyword */: @@ -32275,10 +31065,8 @@ ${lanes.join("\n")} const pos = getNodePos(); return finishNode(factory2.createPrefixUnaryExpression(token(), nextTokenAnd(parseLeftHandSideExpressionOrHigher)), pos); } else if (languageVariant === 1 /* JSX */ && token() === 30 /* LessThanToken */ && lookAhead(nextTokenIsIdentifierOrKeywordOrGreaterThan)) { - return parseJsxElementOrSelfClosingElementOrFragment( - /*inExpressionContext*/ - true - ); + return parseJsxElementOrSelfClosingElementOrFragment( /*inExpressionContext*/ + true); } const expression = parseLeftHandSideExpressionOrHigher(); Debug.assert(isLeftHandSideExpression(expression)); @@ -32312,12 +31100,8 @@ ${lanes.join("\n")} function parseMemberExpressionOrHigher() { const pos = getNodePos(); const expression = parsePrimaryExpression(); - return parseMemberExpressionRest( - pos, - expression, - /*allowOptionalChain*/ - true - ); + return parseMemberExpressionRest(pos, expression, /*allowOptionalChain*/ + true); } function parseSuperExpression() { const pos = getNodePos(); @@ -32336,14 +31120,10 @@ ${lanes.join("\n")} return expression; } parseExpectedToken(25 /* DotToken */, Diagnostics.super_must_be_followed_by_an_argument_list_or_member_access); - return finishNode(factoryCreatePropertyAccessExpression(expression, parseRightSideOfDot( - /*allowIdentifierNames*/ - true, - /*allowPrivateIdentifiers*/ - true, - /*allowUnicodeEscapeSequenceInIdentifierName*/ - true - )), pos); + return finishNode(factoryCreatePropertyAccessExpression(expression, parseRightSideOfDot( /*allowIdentifierNames*/ + true, /*allowPrivateIdentifiers*/ + true, /*allowUnicodeEscapeSequenceInIdentifierName*/ + true)), pos); } function parseJsxElementOrSelfClosingElementOrFragment(inExpressionContext, topInvalidNodePosition, openingTag, mustBeUnary = false) { const pos = getNodePos(); @@ -32355,15 +31135,7 @@ ${lanes.join("\n")} const lastChild = children[children.length - 1]; if ((lastChild == null ? void 0 : lastChild.kind) === 284 /* JsxElement */ && !tagNamesAreEquivalent(lastChild.openingElement.tagName, lastChild.closingElement.tagName) && tagNamesAreEquivalent(opening.tagName, lastChild.closingElement.tagName)) { const end = lastChild.children.end; - const newLast = finishNode( - factory2.createJsxElement( - lastChild.openingElement, - lastChild.children, - finishNode(factory2.createJsxClosingElement(finishNode(factoryCreateIdentifier(""), end, end)), end, end) - ), - lastChild.openingElement.pos, - end - ); + const newLast = finishNode(factory2.createJsxElement(lastChild.openingElement, lastChild.children, finishNode(factory2.createJsxClosingElement(finishNode(factoryCreateIdentifier(""), end, end)), end, end)), lastChild.openingElement.pos, end); children = createNodeArray([...children.slice(0, children.length - 1), newLast], children.pos, end); closingElement = lastChild.closingElement; } else { @@ -32385,17 +31157,11 @@ ${lanes.join("\n")} } if (!mustBeUnary && inExpressionContext && token() === 30 /* LessThanToken */) { const topBadPos = typeof topInvalidNodePosition === "undefined" ? result.pos : topInvalidNodePosition; - const invalidElement = tryParse(() => parseJsxElementOrSelfClosingElementOrFragment( - /*inExpressionContext*/ - true, - topBadPos - )); + const invalidElement = tryParse(() => parseJsxElementOrSelfClosingElementOrFragment( /*inExpressionContext*/ + true, topBadPos)); if (invalidElement) { - const operatorToken = createMissingNode( - 28 /* CommaToken */, - /*reportAtCurrentPosition*/ - false - ); + const operatorToken = createMissingNode(28 /* CommaToken */, /*reportAtCurrentPosition*/ + false); setTextRangePosWidth(operatorToken, invalidElement.pos, 0); parseErrorAt(skipTrivia(sourceText, topBadPos), invalidElement.end, Diagnostics.JSX_expressions_must_have_one_parent_element); return finishNode(factory2.createBinaryExpression(result, operatorToken, invalidElement), pos); @@ -32427,18 +31193,12 @@ ${lanes.join("\n")} case 13 /* JsxTextAllWhiteSpaces */: return parseJsxText(); case 19 /* OpenBraceToken */: - return parseJsxExpression( - /*inExpressionContext*/ - false - ); + return parseJsxExpression( /*inExpressionContext*/ + false); case 30 /* LessThanToken */: - return parseJsxElementOrSelfClosingElementOrFragment( - /*inExpressionContext*/ - false, - /*topInvalidNodePosition*/ - void 0, - openingTag - ); + return parseJsxElementOrSelfClosingElementOrFragment( /*inExpressionContext*/ + false, /*topInvalidNodePosition*/ + void 0, openingTag); default: return Debug.assertNever(token2); } @@ -32450,8 +31210,7 @@ ${lanes.join("\n")} 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; @@ -32480,13 +31239,9 @@ ${lanes.join("\n")} node = factory2.createJsxOpeningElement(tagName, typeArguments, attributes); } else { parseExpected(44 /* SlashToken */); - if (parseExpected( - 32 /* GreaterThanToken */, - /*diagnosticMessage*/ - void 0, - /*shouldAdvance*/ - false - )) { + if (parseExpected(32 /* GreaterThanToken */, /*diagnosticMessage*/ + void 0, /*shouldAdvance*/ + false)) { if (inExpressionContext) { nextToken(); } else { @@ -32505,14 +31260,10 @@ ${lanes.join("\n")} } let expression = initialExpression; while (parseOptional(25 /* DotToken */)) { - expression = finishNode(factoryCreatePropertyAccessExpression(expression, parseRightSideOfDot( - /*allowIdentifierNames*/ - true, - /*allowPrivateIdentifiers*/ - false, - /*allowUnicodeEscapeSequenceInIdentifierName*/ - false - )), pos); + expression = finishNode(factoryCreatePropertyAccessExpression(expression, parseRightSideOfDot( /*allowIdentifierNames*/ + true, /*allowPrivateIdentifiers*/ + false, /*allowUnicodeEscapeSequenceInIdentifierName*/ + false)), pos); } return expression; } @@ -32538,18 +31289,15 @@ ${lanes.join("\n")} if (!inExpressionContext) { dotDotDotToken = parseOptionalToken(26 /* DotDotDotToken */); } + expression = parseExpression(); } if (inExpressionContext) { parseExpected(20 /* CloseBraceToken */); } else { - if (parseExpected( - 20 /* CloseBraceToken */, - /*diagnosticMessage*/ - void 0, - /*shouldAdvance*/ - false - )) { + if (parseExpected(20 /* CloseBraceToken */, /*diagnosticMessage*/ + void 0, /*shouldAdvance*/ + false)) { scanJsxText(); } } @@ -32568,16 +31316,12 @@ ${lanes.join("\n")} return parseLiteralNode(); } if (token() === 19 /* OpenBraceToken */) { - return parseJsxExpression( - /*inExpressionContext*/ - true - ); + return parseJsxExpression( /*inExpressionContext*/ + true); } if (token() === 30 /* LessThanToken */) { - return parseJsxElementOrSelfClosingElementOrFragment( - /*inExpressionContext*/ - true - ); + return parseJsxElementOrSelfClosingElementOrFragment( /*inExpressionContext*/ + true); } parseErrorAtCurrentToken(Diagnostics.or_JSX_element_expected); } @@ -32605,13 +31349,9 @@ ${lanes.join("\n")} const pos = getNodePos(); parseExpected(31 /* LessThanSlashToken */); const tagName = parseJsxElementName(); - if (parseExpected( - 32 /* GreaterThanToken */, - /*diagnosticMessage*/ - void 0, - /*shouldAdvance*/ - false - )) { + if (parseExpected(32 /* GreaterThanToken */, /*diagnosticMessage*/ + void 0, /*shouldAdvance*/ + false)) { if (inExpressionContext || !tagNamesAreEquivalent(open.tagName, tagName)) { nextToken(); } else { @@ -32623,12 +31363,8 @@ ${lanes.join("\n")} function parseJsxClosingFragment(inExpressionContext) { const pos = getNodePos(); parseExpected(31 /* LessThanSlashToken */); - if (parseExpected( - 32 /* GreaterThanToken */, - Diagnostics.Expected_corresponding_closing_tag_for_JSX_fragment, - /*shouldAdvance*/ - false - )) { + if (parseExpected(32 /* GreaterThanToken */, Diagnostics.Expected_corresponding_closing_tag_for_JSX_fragment, /*shouldAdvance*/ + false)) { if (inExpressionContext) { nextToken(); } else { @@ -32673,14 +31409,10 @@ ${lanes.join("\n")} return false; } function parsePropertyAccessExpressionRest(pos, expression, questionDotToken) { - const name = parseRightSideOfDot( - /*allowIdentifierNames*/ - true, - /*allowPrivateIdentifiers*/ - true, - /*allowUnicodeEscapeSequenceInIdentifierName*/ - true - ); + const name = parseRightSideOfDot( /*allowIdentifierNames*/ + true, /*allowPrivateIdentifiers*/ + true, /*allowUnicodeEscapeSequenceInIdentifierName*/ + true); const isOptionalChain2 = questionDotToken || tryReparseOptionalChain(expression); const propertyAccess = isOptionalChain2 ? factoryCreatePropertyAccessChain(expression, questionDotToken, name) : factoryCreatePropertyAccessExpression(expression, name); if (isOptionalChain2 && isPrivateIdentifier(propertyAccess.name)) { @@ -32696,12 +31428,8 @@ ${lanes.join("\n")} function parseElementAccessExpressionRest(pos, expression, questionDotToken) { let argumentExpression; if (token() === 24 /* CloseBracketToken */) { - argumentExpression = createMissingNode( - 80 /* Identifier */, - /*reportAtCurrentPosition*/ - true, - Diagnostics.An_element_access_expression_should_take_an_argument - ); + argumentExpression = createMissingNode(80 /* Identifier */, /*reportAtCurrentPosition*/ + true, Diagnostics.An_element_access_expression_should_take_an_argument); } else { const argument = allowInAnd(parseExpression); if (isStringOrNumericLiteralLike(argument)) { @@ -32723,6 +31451,7 @@ ${lanes.join("\n")} } else { isPropertyAccess = parseOptional(25 /* DotToken */); } + if (isPropertyAccess) { expression = parsePropertyAccessExpressionRest(pos, expression, questionDotToken); continue; @@ -32732,13 +31461,8 @@ ${lanes.join("\n")} continue; } if (isTemplateStartOfTaggedTemplate()) { - expression = !questionDotToken && expression.kind === 233 /* ExpressionWithTypeArguments */ ? parseTaggedTemplateRest(pos, expression.expression, questionDotToken, expression.typeArguments) : parseTaggedTemplateRest( - pos, - expression, - questionDotToken, - /*typeArguments*/ - void 0 - ); + expression = !questionDotToken && expression.kind === 233 /* ExpressionWithTypeArguments */ ? parseTaggedTemplateRest(pos, expression.expression, questionDotToken, expression.typeArguments) : parseTaggedTemplateRest(pos, expression, questionDotToken, /*typeArguments*/ + void 0); continue; } if (!questionDotToken) { @@ -32759,32 +31483,22 @@ ${lanes.join("\n")} function isTemplateStartOfTaggedTemplate() { return token() === 15 /* NoSubstitutionTemplateLiteral */ || token() === 16 /* TemplateHead */; } + function parseTaggedTemplateRest(pos, tag, questionDotToken, typeArguments) { - const tagExpression = factory2.createTaggedTemplateExpression( - tag, - typeArguments, - token() === 15 /* NoSubstitutionTemplateLiteral */ ? (reScanTemplateToken( - /*isTaggedTemplate*/ - true - ), parseLiteralNode()) : parseTemplateExpression( - /*isTaggedTemplate*/ - true - ) - ); + const tagExpression = factory2.createTaggedTemplateExpression(tag, typeArguments, token() === 15 /* NoSubstitutionTemplateLiteral */ ? (reScanTemplateToken( /*isTaggedTemplate*/ + true), parseLiteralNode()) : parseTemplateExpression( /*isTaggedTemplate*/ + true)); if (questionDotToken || tag.flags & 64 /* OptionalChain */) { tagExpression.flags |= 64 /* OptionalChain */; } + tagExpression.questionDotToken = questionDotToken; return finishNode(tagExpression, pos); } function parseCallExpressionRest(pos, expression) { while (true) { - expression = parseMemberExpressionRest( - pos, - expression, - /*allowOptionalChain*/ - true - ); + expression = parseMemberExpressionRest(pos, expression, /*allowOptionalChain*/ + true); let typeArguments; const questionDotToken = parseOptionalToken(29 /* QuestionDotToken */); if (questionDotToken) { @@ -32805,12 +31519,8 @@ ${lanes.join("\n")} continue; } if (questionDotToken) { - const name = createMissingNode( - 80 /* Identifier */, - /*reportAtCurrentPosition*/ - false, - Diagnostics.Identifier_expected - ); + const name = createMissingNode(80 /* Identifier */, /*reportAtCurrentPosition*/ + false, Diagnostics.Identifier_expected); expression = finishNode(factoryCreatePropertyAccessChain(expression, questionDotToken, name), pos); } break; @@ -32856,10 +31566,8 @@ ${lanes.join("\n")} switch (token()) { case 15 /* NoSubstitutionTemplateLiteral */: if (scanner2.getTokenFlags() & 26656 /* IsInvalid */) { - reScanTemplateToken( - /*isTaggedTemplate*/ - false - ); + reScanTemplateToken( /*isTaggedTemplate*/ + false); } case 9 /* NumericLiteral */: case 10 /* BigIntLiteral */: @@ -32897,10 +31605,8 @@ ${lanes.join("\n")} } break; case 16 /* TemplateHead */: - return parseTemplateExpression( - /*isTaggedTemplate*/ - false - ); + return parseTemplateExpression( /*isTaggedTemplate*/ + false); case 81 /* PrivateIdentifier */: return parsePrivateIdentifier(); } @@ -32917,17 +31623,13 @@ ${lanes.join("\n")} function parseSpreadElement() { const pos = getNodePos(); parseExpected(26 /* DotDotDotToken */); - const expression = parseAssignmentExpressionOrHigher( - /*allowReturnTypeInArrowFunction*/ - true - ); + const expression = parseAssignmentExpressionOrHigher( /*allowReturnTypeInArrowFunction*/ + true); return finishNode(factory2.createSpreadElement(expression), pos); } function parseArgumentOrArrayLiteralElement() { - return token() === 26 /* DotDotDotToken */ ? parseSpreadElement() : token() === 28 /* CommaToken */ ? finishNode(factory2.createOmittedExpression(), getNodePos()) : parseAssignmentExpressionOrHigher( - /*allowReturnTypeInArrowFunction*/ - true - ); + return token() === 26 /* DotDotDotToken */ ? parseSpreadElement() : token() === 28 /* CommaToken */ ? finishNode(factory2.createOmittedExpression(), getNodePos()) : parseAssignmentExpressionOrHigher( /*allowReturnTypeInArrowFunction*/ + true); } function parseArgumentExpression() { return doOutsideOfContext(disallowInAndDecoratorContext, parseArgumentOrArrayLiteralElement); @@ -32945,22 +31647,20 @@ ${lanes.join("\n")} const pos = getNodePos(); const hasJSDoc = hasPrecedingJSDocComment(); if (parseOptionalToken(26 /* DotDotDotToken */)) { - const expression = parseAssignmentExpressionOrHigher( - /*allowReturnTypeInArrowFunction*/ - true - ); + const expression = parseAssignmentExpressionOrHigher( /*allowReturnTypeInArrowFunction*/ + true); return withJSDoc(finishNode(factory2.createSpreadAssignment(expression), pos), hasJSDoc); } - const modifiers = parseModifiers( - /*allowDecorators*/ - true - ); + const modifiers = parseModifiers( /*allowDecorators*/ + true); if (parseContextualModifier(139 /* GetKeyword */)) { return parseAccessorDeclaration(pos, hasJSDoc, modifiers, 177 /* GetAccessor */, 0 /* None */); } + if (parseContextualModifier(153 /* SetKeyword */)) { return parseAccessorDeclaration(pos, hasJSDoc, modifiers, 178 /* SetAccessor */, 0 /* None */); } + const asteriskToken = parseOptionalToken(42 /* AsteriskToken */); const tokenIsIdentifier = isIdentifier2(); const name = parsePropertyName(); @@ -32973,18 +31673,14 @@ ${lanes.join("\n")} const isShorthandPropertyAssignment2 = tokenIsIdentifier && token() !== 59 /* ColonToken */; if (isShorthandPropertyAssignment2) { const equalsToken = parseOptionalToken(64 /* EqualsToken */); - const objectAssignmentInitializer = equalsToken ? allowInAnd(() => parseAssignmentExpressionOrHigher( - /*allowReturnTypeInArrowFunction*/ - true - )) : void 0; + const objectAssignmentInitializer = equalsToken ? allowInAnd(() => parseAssignmentExpressionOrHigher( /*allowReturnTypeInArrowFunction*/ + true)) : void 0; node = factory2.createShorthandPropertyAssignment(name, objectAssignmentInitializer); node.equalsToken = equalsToken; } else { parseExpected(59 /* ColonToken */); - const initializer = allowInAnd(() => parseAssignmentExpressionOrHigher( - /*allowReturnTypeInArrowFunction*/ - true - )); + const initializer = allowInAnd(() => parseAssignmentExpressionOrHigher( /*allowReturnTypeInArrowFunction*/ + true)); node = factory2.createPropertyAssignment(name, initializer); } node.modifiers = modifiers; @@ -32997,27 +31693,19 @@ ${lanes.join("\n")} const openBracePosition = scanner2.getTokenStart(); const openBraceParsed = parseExpected(19 /* OpenBraceToken */); const multiLine = scanner2.hasPrecedingLineBreak(); - const properties = parseDelimitedList( - 12 /* ObjectLiteralMembers */, - parseObjectLiteralElement, - /*considerSemicolonAsDelimiter*/ - true - ); + const properties = parseDelimitedList(12 /* ObjectLiteralMembers */, parseObjectLiteralElement, /*considerSemicolonAsDelimiter*/ + true); parseExpectedMatchingBrackets(19 /* OpenBraceToken */, 20 /* CloseBraceToken */, openBraceParsed, openBracePosition); return finishNode(factoryCreateObjectLiteralExpression(properties, multiLine), pos); } function parseFunctionExpression() { const savedDecoratorContext = inDecoratorContext(); - setDecoratorContext( - /*val*/ - false - ); + setDecoratorContext( /*val*/ + false); const pos = getNodePos(); const hasJSDoc = hasPrecedingJSDocComment(); - const modifiers = parseModifiers( - /*allowDecorators*/ - false - ); + const modifiers = parseModifiers( /*allowDecorators*/ + false); parseExpected(100 /* FunctionKeyword */); const asteriskToken = parseOptionalToken(42 /* AsteriskToken */); const isGenerator = asteriskToken ? 1 /* Yield */ : 0 /* None */; @@ -33025,11 +31713,8 @@ ${lanes.join("\n")} const name = isGenerator && isAsync ? doInYieldAndAwaitContext(parseOptionalBindingIdentifier) : isGenerator ? doInYieldContext(parseOptionalBindingIdentifier) : isAsync ? doInAwaitContext(parseOptionalBindingIdentifier) : parseOptionalBindingIdentifier(); const typeParameters = parseTypeParameters(); const parameters = parseParameters(isGenerator | isAsync); - const type = parseReturnType( - 59 /* ColonToken */, - /*isType*/ - false - ); + const type = parseReturnType(59 /* ColonToken */, /*isType*/ + false); const body = parseFunctionBlock(isGenerator | isAsync); setDecoratorContext(savedDecoratorContext); const node = factory2.createFunctionExpression(modifiers, asteriskToken, name, typeParameters, parameters, type, body); @@ -33046,12 +31731,8 @@ ${lanes.join("\n")} return finishNode(factory2.createMetaProperty(105 /* NewKeyword */, name), pos); } const expressionPos = getNodePos(); - let expression = parseMemberExpressionRest( - expressionPos, - parsePrimaryExpression(), - /*allowOptionalChain*/ - false - ); + let expression = parseMemberExpressionRest(expressionPos, parsePrimaryExpression(), /*allowOptionalChain*/ + false); let typeArguments; if (expression.kind === 233 /* ExpressionWithTypeArguments */) { typeArguments = expression.typeArguments; @@ -33080,11 +31761,8 @@ ${lanes.join("\n")} return result; } else { const statements = createMissingList(); - return withJSDoc(finishNode(factoryCreateBlock( - statements, - /*multiLine*/ - void 0 - ), pos), hasJSDoc); + return withJSDoc(finishNode(factoryCreateBlock(statements, /*multiLine*/ + void 0), pos), hasJSDoc); } } function parseFunctionBlock(flags, diagnosticMessage) { @@ -33096,17 +31774,13 @@ ${lanes.join("\n")} topLevel = false; const saveDecoratorContext = inDecoratorContext(); if (saveDecoratorContext) { - setDecoratorContext( - /*val*/ - false - ); + setDecoratorContext( /*val*/ + false); } const block = parseBlock(!!(flags & 16 /* IgnoreMissingOpenBrace */), diagnosticMessage); if (saveDecoratorContext) { - setDecoratorContext( - /*val*/ - true - ); + setDecoratorContext( /*val*/ + true); } topLevel = savedTopLevel; setYieldContext(savedYieldContext); @@ -33163,22 +31837,19 @@ ${lanes.join("\n")} parseExpected(21 /* OpenParenToken */); let initializer; if (token() !== 27 /* SemicolonToken */) { - if (token() === 115 /* VarKeyword */ || token() === 121 /* LetKeyword */ || token() === 87 /* ConstKeyword */ || token() === 160 /* UsingKeyword */ && lookAhead(nextTokenIsBindingIdentifierOrStartOfDestructuringOnSameLineDisallowOf) || // this one is meant to allow of + if (token() === 115 /* VarKeyword */ || token() === 121 /* LetKeyword */ || token() === 87 /* ConstKeyword */ || token() === 160 /* UsingKeyword */ && lookAhead(nextTokenIsBindingIdentifierOrStartOfDestructuringOnSameLineDisallowOf) || + // this one is meant to allow of token() === 135 /* AwaitKeyword */ && lookAhead(nextTokenIsUsingKeywordThenBindingIdentifierOrStartOfObjectDestructuringOnSameLine)) { - initializer = parseVariableDeclarationList( - /*inForStatementInitializer*/ - true - ); + initializer = parseVariableDeclarationList( /*inForStatementInitializer*/ + true); } else { initializer = disallowInAnd(parseExpression); } } let node; if (awaitToken ? parseExpected(165 /* OfKeyword */) : parseOptional(165 /* OfKeyword */)) { - const expression = allowInAnd(() => parseAssignmentExpressionOrHigher( - /*allowReturnTypeInArrowFunction*/ - true - )); + const expression = allowInAnd(() => parseAssignmentExpressionOrHigher( /*allowReturnTypeInArrowFunction*/ + true)); parseExpected(22 /* CloseParenToken */); node = factoryCreateForOfStatement(awaitToken, initializer, expression, parseStatement()); } else if (parseOptional(103 /* InKeyword */)) { @@ -33277,18 +31948,14 @@ ${lanes.join("\n")} const pos = getNodePos(); const hasJSDoc = hasPrecedingJSDocComment(); parseExpected(113 /* TryKeyword */); - const tryBlock = parseBlock( - /*ignoreMissingOpenBrace*/ - false - ); + const tryBlock = parseBlock( /*ignoreMissingOpenBrace*/ + false); const catchClause = token() === 85 /* CatchKeyword */ ? parseCatchClause() : void 0; let finallyBlock; if (!catchClause || token() === 98 /* FinallyKeyword */) { parseExpected(98 /* FinallyKeyword */, Diagnostics.catch_or_finally_expected); - finallyBlock = parseBlock( - /*ignoreMissingOpenBrace*/ - false - ); + finallyBlock = parseBlock( /*ignoreMissingOpenBrace*/ + false); } return withJSDoc(finishNode(factory2.createTryStatement(tryBlock, catchClause, finallyBlock), pos), hasJSDoc); } @@ -33302,10 +31969,8 @@ ${lanes.join("\n")} } else { variableDeclaration = void 0; } - const block = parseBlock( - /*ignoreMissingOpenBrace*/ - false - ); + const block = parseBlock( /*ignoreMissingOpenBrace*/ + false); return finishNode(factory2.createCatchClause(variableDeclaration, block), pos); } function parseDebuggerStatement() { @@ -33467,19 +32132,17 @@ ${lanes.join("\n")} nextToken(); return isBindingIdentifier() || token() === 19 /* OpenBraceToken */ || token() === 23 /* OpenBracketToken */; } + function isLetDeclaration() { return lookAhead(nextTokenIsBindingIdentifierOrStartOfDestructuring); } function nextTokenIsBindingIdentifierOrStartOfDestructuringOnSameLineDisallowOf() { - return nextTokenIsBindingIdentifierOrStartOfDestructuringOnSameLine( - /*disallowOf*/ - true - ); + return nextTokenIsBindingIdentifierOrStartOfDestructuringOnSameLine( /*disallowOf*/ + true); } 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() { @@ -33499,61 +32162,35 @@ ${lanes.join("\n")} case 27 /* SemicolonToken */: return parseEmptyStatement(); case 19 /* OpenBraceToken */: - return parseBlock( - /*ignoreMissingOpenBrace*/ - false - ); + return parseBlock( /*ignoreMissingOpenBrace*/ + false); case 115 /* VarKeyword */: - return parseVariableStatement( - getNodePos(), - hasPrecedingJSDocComment(), - /*modifiers*/ - void 0 - ); + return parseVariableStatement(getNodePos(), hasPrecedingJSDocComment(), /*modifiers*/ + void 0); case 121 /* LetKeyword */: if (isLetDeclaration()) { - return parseVariableStatement( - getNodePos(), - hasPrecedingJSDocComment(), - /*modifiers*/ - void 0 - ); + return parseVariableStatement(getNodePos(), hasPrecedingJSDocComment(), /*modifiers*/ + void 0); } break; case 135 /* AwaitKeyword */: if (isAwaitUsingDeclaration()) { - return parseVariableStatement( - getNodePos(), - hasPrecedingJSDocComment(), - /*modifiers*/ - void 0 - ); + return parseVariableStatement(getNodePos(), hasPrecedingJSDocComment(), /*modifiers*/ + void 0); } break; case 160 /* UsingKeyword */: if (isUsingDeclaration()) { - return parseVariableStatement( - getNodePos(), - hasPrecedingJSDocComment(), - /*modifiers*/ - void 0 - ); + return parseVariableStatement(getNodePos(), hasPrecedingJSDocComment(), /*modifiers*/ + void 0); } break; case 100 /* FunctionKeyword */: - return parseFunctionDeclaration( - getNodePos(), - hasPrecedingJSDocComment(), - /*modifiers*/ - void 0 - ); + return parseFunctionDeclaration(getNodePos(), hasPrecedingJSDocComment(), /*modifiers*/ + void 0); case 86 /* ClassKeyword */: - return parseClassDeclaration( - getNodePos(), - hasPrecedingJSDocComment(), - /*modifiers*/ - void 0 - ); + return parseClassDeclaration(getNodePos(), hasPrecedingJSDocComment(), /*modifiers*/ + void 0); case 101 /* IfKeyword */: return parseIfStatement(); case 92 /* DoKeyword */: @@ -33610,13 +32247,12 @@ ${lanes.join("\n")} function isDeclareModifier(modifier) { return modifier.kind === 138 /* DeclareKeyword */; } + function parseDeclaration() { const pos = getNodePos(); const hasJSDoc = hasPrecedingJSDocComment(); - const modifiers = parseModifiers( - /*allowDecorators*/ - true - ); + const modifiers = parseModifiers( /*allowDecorators*/ + true); const isAmbient = some(modifiers, isDeclareModifier); if (isAmbient) { const node = tryReuseAmbientDeclaration(pos); @@ -33626,6 +32262,7 @@ ${lanes.join("\n")} for (const m of modifiers) { m.flags |= 33554432 /* Ambient */; } + return doInsideOfContext(33554432 /* Ambient */, () => parseDeclarationWorker(pos, hasJSDoc, modifiers)); } else { return parseDeclarationWorker(pos, hasJSDoc, modifiers); @@ -33676,12 +32313,8 @@ ${lanes.join("\n")} } default: if (modifiersIn) { - const missing = createMissingNode( - 282 /* MissingDeclaration */, - /*reportAtCurrentPosition*/ - true, - Diagnostics.Declaration_expected - ); + const missing = createMissingNode(282 /* MissingDeclaration */, /*reportAtCurrentPosition*/ + true, Diagnostics.Declaration_expected); setTextRangePos(missing, pos); missing.modifiers = modifiersIn; return missing; @@ -33692,10 +32325,12 @@ ${lanes.join("\n")} function nextTokenIsStringLiteral() { return nextToken() === 11 /* StringLiteral */; } + function nextTokenIsIdentifierOrStringLiteralOnSameLine() { nextToken(); return !scanner2.hasPrecedingLineBreak() && (isIdentifier2() || token() === 11 /* StringLiteral */); } + function parseFunctionBlockOrSemicolon(flags, diagnosticMessage) { if (token() !== 19 /* OpenBraceToken */) { if (flags & 4 /* Type */) { @@ -33717,13 +32352,8 @@ ${lanes.join("\n")} const dotDotDotToken = parseOptionalToken(26 /* DotDotDotToken */); const name = parseIdentifierOrPattern(); const initializer = parseInitializer(); - return finishNode(factory2.createBindingElement( - dotDotDotToken, - /*propertyName*/ - void 0, - name, - initializer - ), pos); + return finishNode(factory2.createBindingElement(dotDotDotToken, /*propertyName*/ + void 0, name, initializer), pos); } function parseObjectBindingElement() { const pos = getNodePos(); @@ -33768,10 +32398,8 @@ ${lanes.join("\n")} return parseBindingIdentifier(privateIdentifierDiagnosticMessage); } function parseVariableDeclarationAllowExclamation() { - return parseVariableDeclaration( - /*allowExclamation*/ - true - ); + return parseVariableDeclaration( /*allowExclamation*/ + true); } function parseVariableDeclaration(allowExclamation) { const pos = getNodePos(); @@ -33816,10 +32444,7 @@ ${lanes.join("\n")} } else { const savedDisallowIn = inDisallowInContext(); setDisallowInContext(inForStatementInitializer); - declarations = parseDelimitedList( - 8 /* VariableDeclarations */, - inForStatementInitializer ? parseVariableDeclaration : parseVariableDeclarationAllowExclamation - ); + declarations = parseDelimitedList(8 /* VariableDeclarations */, inForStatementInitializer ? parseVariableDeclaration : parseVariableDeclarationAllowExclamation); setDisallowInContext(savedDisallowIn); } return finishNode(factoryCreateVariableDeclarationList(declarations, flags), pos); @@ -33827,11 +32452,10 @@ ${lanes.join("\n")} function canFollowContextualOfKeyword() { return nextTokenIsIdentifier() && nextToken() === 22 /* CloseParenToken */; } + function parseVariableStatement(pos, hasJSDoc, modifiers) { - const declarationList = parseVariableDeclarationList( - /*inForStatementInitializer*/ - false - ); + const declarationList = parseVariableDeclarationList( /*inForStatementInitializer*/ + false); parseSemicolon(); const node = factoryCreateVariableStatement(modifiers, declarationList); return withJSDoc(finishNode(node, pos), hasJSDoc); @@ -33845,17 +32469,11 @@ ${lanes.join("\n")} 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 */, - /*isType*/ - false - ); + const type = parseReturnType(59 /* ColonToken */, /*isType*/ + false); const body = parseFunctionBlockOrSemicolon(isGenerator | isAsync, Diagnostics.or_expected); setAwaitContext(savedAwaitContext); const node = factory2.createFunctionDeclaration(modifiers, asteriskToken, name, typeParameters, parameters, type, body); @@ -33865,6 +32483,7 @@ ${lanes.join("\n")} if (token() === 137 /* ConstructorKeyword */) { return parseExpected(137 /* ConstructorKeyword */); } + if (token() === 11 /* StringLiteral */ && lookAhead(nextToken) === 21 /* OpenParenToken */) { return tryParse(() => { const literalNode = parseLiteralNode(); @@ -33877,11 +32496,8 @@ ${lanes.join("\n")} if (parseConstructorName()) { const typeParameters = parseTypeParameters(); const parameters = parseParameters(0 /* None */); - const type = parseReturnType( - 59 /* ColonToken */, - /*isType*/ - false - ); + const type = parseReturnType(59 /* ColonToken */, /*isType*/ + false); const body = parseFunctionBlockOrSemicolon(0 /* None */, Diagnostics.or_expected); const node = factory2.createConstructorDeclaration(modifiers, parameters, body); node.typeParameters = typeParameters; @@ -33895,22 +32511,10 @@ ${lanes.join("\n")} const isAsync = some(modifiers, isAsyncModifier) ? 2 /* Await */ : 0 /* None */; const typeParameters = parseTypeParameters(); const parameters = parseParameters(isGenerator | isAsync); - const type = parseReturnType( - 59 /* ColonToken */, - /*isType*/ - false - ); + const type = parseReturnType(59 /* ColonToken */, /*isType*/ + false); const body = parseFunctionBlockOrSemicolon(isGenerator | isAsync, diagnosticMessage); - const node = factory2.createMethodDeclaration( - modifiers, - asteriskToken, - name, - questionToken, - typeParameters, - parameters, - type, - body - ); + const node = factory2.createMethodDeclaration(modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body); node.exclamationToken = exclamationToken; return withJSDoc(finishNode(node, pos), hasJSDoc); } @@ -33919,13 +32523,7 @@ ${lanes.join("\n")} const type = parseTypeAnnotation(); const initializer = doOutsideOfContext(16384 /* YieldContext */ | 65536 /* AwaitContext */ | 8192 /* DisallowInContext */, parseInitializer); parseSemicolonAfterPropertyName(name, type, initializer); - const node = factory2.createPropertyDeclaration( - modifiers, - name, - questionToken || exclamationToken, - type, - initializer - ); + const node = factory2.createPropertyDeclaration(modifiers, name, questionToken || exclamationToken, type, initializer); return withJSDoc(finishNode(node, pos), hasJSDoc); } function parsePropertyOrMethodDeclaration(pos, hasJSDoc, modifiers) { @@ -33933,17 +32531,8 @@ ${lanes.join("\n")} const name = parsePropertyName(); const questionToken = parseOptionalToken(58 /* QuestionToken */); if (asteriskToken || token() === 21 /* OpenParenToken */ || token() === 30 /* LessThanToken */) { - return parseMethodDeclaration( - pos, - hasJSDoc, - modifiers, - asteriskToken, - name, - questionToken, - /*exclamationToken*/ - void 0, - Diagnostics.or_expected - ); + return parseMethodDeclaration(pos, hasJSDoc, modifiers, asteriskToken, name, questionToken, /*exclamationToken*/ + void 0, Diagnostics.or_expected); } return parsePropertyDeclaration(pos, hasJSDoc, modifiers, name, questionToken); } @@ -33951,16 +32540,12 @@ ${lanes.join("\n")} const name = parsePropertyName(); const typeParameters = parseTypeParameters(); const parameters = parseParameters(0 /* None */); - const type = parseReturnType( - 59 /* ColonToken */, - /*isType*/ - false - ); + const type = parseReturnType(59 /* ColonToken */, /*isType*/ + false); 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() { @@ -34015,10 +32600,8 @@ ${lanes.join("\n")} const savedAwaitContext = inAwaitContext(); setYieldContext(false); setAwaitContext(true); - const body = parseBlock( - /*ignoreMissingOpenBrace*/ - false - ); + const body = parseBlock( /*ignoreMissingOpenBrace*/ + false); setYieldContext(savedYieldContext); setAwaitContext(savedAwaitContext); return body; @@ -34028,12 +32611,8 @@ ${lanes.join("\n")} const pos = getNodePos(); const awaitExpression = parseIdentifier(Diagnostics.Expression_expected); nextToken(); - const memberExpression = parseMemberExpressionRest( - pos, - awaitExpression, - /*allowOptionalChain*/ - true - ); + const memberExpression = parseMemberExpressionRest(pos, awaitExpression, /*allowOptionalChain*/ + true); return parseCallExpressionRest(pos, memberExpression); } return parseLeftHandSideExpressionOrHigher(); @@ -34067,15 +32646,18 @@ ${lanes.join("\n")} function parseModifiers(allowDecorators, permitConstAsModifier, stopOnStartOfClassStaticBlock) { const pos = getNodePos(); let list; - let decorator, modifier, hasSeenStaticModifier = false, hasLeadingModifier = false, hasTrailingDecorator = false; + let decorator, + modifier, + hasSeenStaticModifier = false, + hasLeadingModifier = false, + hasTrailingDecorator = false; if (allowDecorators && token() === 60 /* AtToken */) { while (decorator = tryParseDecorator()) { list = append(list, decorator); } } 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; } @@ -34087,8 +32669,7 @@ ${lanes.join("\n")} } 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); } } @@ -34111,23 +32692,21 @@ ${lanes.join("\n")} nextToken(); return withJSDoc(finishNode(factory2.createSemicolonClassElement(), pos), hasJSDoc); } - const modifiers = parseModifiers( - /*allowDecorators*/ - true, - /*permitConstAsModifier*/ - true, - /*stopOnStartOfClassStaticBlock*/ - true - ); + const modifiers = parseModifiers( /*allowDecorators*/ + true, /*permitConstAsModifier*/ + true, /*stopOnStartOfClassStaticBlock*/ + true); if (token() === 126 /* StaticKeyword */ && lookAhead(nextTokenIsOpenBrace)) { return parseClassStaticBlockDeclaration(pos, hasJSDoc, modifiers); } if (parseContextualModifier(139 /* GetKeyword */)) { return parseAccessorDeclaration(pos, hasJSDoc, modifiers, 177 /* GetAccessor */, 0 /* None */); } + if (parseContextualModifier(153 /* SetKeyword */)) { return parseAccessorDeclaration(pos, hasJSDoc, modifiers, 178 /* SetAccessor */, 0 /* None */); } + if (token() === 137 /* ConstructorKeyword */ || token() === 11 /* StringLiteral */) { const constructorDeclaration = tryParseConstructorDeclaration(pos, hasJSDoc, modifiers); if (constructorDeclaration) { @@ -34143,71 +32722,51 @@ ${lanes.join("\n")} for (const m of modifiers) { m.flags |= 33554432 /* Ambient */; } + return doInsideOfContext(33554432 /* Ambient */, () => parsePropertyOrMethodDeclaration(pos, hasJSDoc, modifiers)); } else { return parsePropertyOrMethodDeclaration(pos, hasJSDoc, modifiers); } } if (modifiers) { - const name = createMissingNode( - 80 /* Identifier */, - /*reportAtCurrentPosition*/ - true, - Diagnostics.Declaration_expected - ); - return parsePropertyDeclaration( - pos, - hasJSDoc, - modifiers, - name, - /*questionToken*/ - void 0 - ); + const name = createMissingNode(80 /* Identifier */, /*reportAtCurrentPosition*/ + true, Diagnostics.Declaration_expected); + return parsePropertyDeclaration(pos, hasJSDoc, modifiers, name, /*questionToken*/ + void 0); } return Debug.fail("Should not have attempted to parse class member declaration."); } function parseDecoratedExpression() { const pos = getNodePos(); const hasJSDoc = hasPrecedingJSDocComment(); - const modifiers = parseModifiers( - /*allowDecorators*/ - true - ); + const modifiers = parseModifiers( /*allowDecorators*/ + true); if (token() === 86 /* ClassKeyword */) { return parseClassDeclarationOrExpression(pos, hasJSDoc, modifiers, 231 /* ClassExpression */); } - const missing = createMissingNode( - 282 /* MissingDeclaration */, - /*reportAtCurrentPosition*/ - true, - Diagnostics.Expression_expected - ); + + const missing = createMissingNode(282 /* MissingDeclaration */, /*reportAtCurrentPosition*/ + true, Diagnostics.Expression_expected); setTextRangePos(missing, pos); missing.modifiers = modifiers; return missing; } function parseClassExpression() { - return parseClassDeclarationOrExpression( - getNodePos(), - hasPrecedingJSDocComment(), - /*modifiers*/ - void 0, - 231 /* ClassExpression */ - ); + return parseClassDeclarationOrExpression(getNodePos(), hasPrecedingJSDocComment(), /*modifiers*/ + void 0, 231 /* ClassExpression */); } + function parseClassDeclaration(pos, hasJSDoc, modifiers) { return parseClassDeclarationOrExpression(pos, hasJSDoc, modifiers, 263 /* ClassDeclaration */); } + function parseClassDeclarationOrExpression(pos, hasJSDoc, modifiers, kind) { const savedAwaitContext = inAwaitContext(); 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 */)) { @@ -34255,6 +32814,7 @@ ${lanes.join("\n")} function isHeritageClause2() { return token() === 96 /* ExtendsKeyword */ || token() === 119 /* ImplementsKeyword */; } + function parseClassMembers() { return parseList(5 /* ClassMembers */, parseClassElement); } @@ -34314,14 +32874,9 @@ ${lanes.join("\n")} function parseModuleOrNamespaceDeclaration(pos, hasJSDoc, modifiers, flags) { const namespaceFlag = flags & 32 /* Namespace */; const name = flags & 8 /* NestedNamespace */ ? parseIdentifierName() : parseIdentifier(); - const body = parseOptional(25 /* DotToken */) ? parseModuleOrNamespaceDeclaration( - getNodePos(), - /*hasJSDoc*/ - false, - /*modifiers*/ - void 0, - 8 /* NestedNamespace */ | namespaceFlag - ) : parseModuleBlock(); + const body = parseOptional(25 /* DotToken */) ? parseModuleOrNamespaceDeclaration(getNodePos(), /*hasJSDoc*/ + false, /*modifiers*/ + void 0, 8 /* NestedNamespace */ | namespaceFlag) : parseModuleBlock(); const node = factory2.createModuleDeclaration(modifiers, name, body, flags); return withJSDoc(finishNode(node, pos), hasJSDoc); } @@ -34364,12 +32919,15 @@ ${lanes.join("\n")} function nextTokenIsOpenParen() { return nextToken() === 21 /* OpenParenToken */; } + function nextTokenIsOpenBrace() { return nextToken() === 19 /* OpenBraceToken */; } + function nextTokenIsSlash() { return nextToken() === 44 /* SlashToken */; } + function parseNamespaceExportDeclaration(pos, hasJSDoc, modifiers) { parseExpected(130 /* AsKeyword */); parseExpected(145 /* NamespaceKeyword */); @@ -34395,12 +32953,15 @@ ${lanes.join("\n")} return parseImportEqualsDeclaration(pos, hasJSDoc, modifiers, identifier, isTypeOnly); } let importClause; - if (identifier || // import id - token() === 42 /* AsteriskToken */ || // import * + if (identifier || + // import id + token() === 42 /* AsteriskToken */ || + // import * token() === 19 /* OpenBraceToken */) { importClause = parseImportClause(identifier, afterImportPos, isTypeOnly); parseExpected(161 /* FromKeyword */); } + const moduleSpecifier = parseModuleSpecifier(); const currentToken2 = token(); let attributes; @@ -34415,10 +32976,8 @@ ${lanes.join("\n")} const pos = getNodePos(); const name = tokenIsIdentifierOrKeyword(token()) ? parseIdentifierName() : parseLiteralLikeNode(11 /* StringLiteral */); parseExpected(59 /* ColonToken */); - const value = parseAssignmentExpressionOrHigher( - /*allowReturnTypeInArrowFunction*/ - true - ); + const value = parseAssignmentExpressionOrHigher( /*allowReturnTypeInArrowFunction*/ + true); return finishNode(factory2.createImportAttribute(name, value), pos); } function parseImportAttributes(token2, skipKeyword) { @@ -34429,45 +32988,31 @@ ${lanes.join("\n")} const openBracePosition = scanner2.getTokenStart(); if (parseExpected(19 /* OpenBraceToken */)) { const multiLine = scanner2.hasPrecedingLineBreak(); - const elements = parseDelimitedList( - 24 /* ImportAttributes */, - parseImportAttribute, - /*considerSemicolonAsDelimiter*/ - true - ); + const elements = parseDelimitedList(24 /* ImportAttributes */, parseImportAttribute, /*considerSemicolonAsDelimiter*/ + true); if (!parseExpected(20 /* CloseBraceToken */)) { const lastError = lastOrUndefined(parseDiagnostics); if (lastError && lastError.code === Diagnostics._0_expected.code) { - addRelatedInfo( - lastError, - createDetachedDiagnostic(fileName, sourceText, openBracePosition, 1, Diagnostics.The_parser_expected_to_find_a_1_to_match_the_0_token_here, "{", "}") - ); + addRelatedInfo(lastError, createDetachedDiagnostic(fileName, sourceText, openBracePosition, 1, Diagnostics.The_parser_expected_to_find_a_1_to_match_the_0_token_here, "{", "}")); } } return finishNode(factory2.createImportAttributes(elements, multiLine, token2), pos); } else { - const elements = createNodeArray( - [], - getNodePos(), - /*end*/ - void 0, - /*hasTrailingComma*/ - false - ); - return finishNode(factory2.createImportAttributes( - elements, - /*multiLine*/ - false, - token2 - ), pos); + const elements = createNodeArray([], getNodePos(), /*end*/ + void 0, /*hasTrailingComma*/ + false); + return finishNode(factory2.createImportAttributes(elements, /*multiLine*/ + false, token2), pos); } } function tokenAfterImportDefinitelyProducesImportDeclaration() { return token() === 42 /* AsteriskToken */ || token() === 19 /* OpenBraceToken */; } + function tokenAfterImportedIdentifierDefinitelyProducesImportDeclaration() { return token() === 28 /* CommaToken */ || token() === 161 /* FromKeyword */; } + function parseImportEqualsDeclaration(pos, hasJSDoc, modifiers, identifier, isTypeOnly) { parseExpected(64 /* EqualsToken */); const moduleReference = parseModuleReference(); @@ -34481,13 +33026,12 @@ ${lanes.join("\n")} if (!identifier || parseOptional(28 /* CommaToken */)) { namedBindings = token() === 42 /* AsteriskToken */ ? parseNamespaceImport() : parseNamedImportsOrExports(275 /* NamedImports */); } + return finishNode(factory2.createImportClause(isTypeOnly, identifier, namedBindings), pos); } function parseModuleReference() { - return isExternalModuleReference2() ? parseExternalModuleReference() : parseEntityName( - /*allowReservedWords*/ - false - ); + return isExternalModuleReference2() ? parseExternalModuleReference() : parseEntityName( /*allowReservedWords*/ + false); } function parseExternalModuleReference() { const pos = getNodePos(); @@ -34525,6 +33069,7 @@ ${lanes.join("\n")} function parseImportSpecifier() { return parseImportOrExportSpecifier(276 /* ImportSpecifier */); } + function parseImportOrExportSpecifier(kind) { const pos = getNodePos(); let checkIdentifierIsKeyword = isKeyword(token()) && !isIdentifier2(); @@ -34584,10 +33129,8 @@ ${lanes.join("\n")} } function parseExportDeclaration(pos, hasJSDoc, modifiers) { const savedAwaitContext = inAwaitContext(); - setAwaitContext( - /*value*/ - true - ); + setAwaitContext( /*value*/ + true); let exportClause; let moduleSpecifier; let attributes; @@ -34617,27 +33160,24 @@ ${lanes.join("\n")} } function parseExportAssignment(pos, hasJSDoc, modifiers) { const savedAwaitContext = inAwaitContext(); - setAwaitContext( - /*value*/ - true - ); + setAwaitContext( /*value*/ + true); let isExportEquals; if (parseOptional(64 /* EqualsToken */)) { isExportEquals = true; } else { parseExpected(90 /* DefaultKeyword */); } - const expression = parseAssignmentExpressionOrHigher( - /*allowReturnTypeInArrowFunction*/ - true - ); + + const expression = parseAssignmentExpressionOrHigher( /*allowReturnTypeInArrowFunction*/ + true); parseSemicolon(); setAwaitContext(savedAwaitContext); const node = factory2.createExportAssignment(modifiers, isExportEquals, expression); return withJSDoc(finishNode(node, pos), hasJSDoc); } let ParsingContext; - ((ParsingContext2) => { + (ParsingContext2 => { ParsingContext2[ParsingContext2["SourceElements"] = 0] = "SourceElements"; ParsingContext2[ParsingContext2["BlockStatements"] = 1] = "BlockStatements"; ParsingContext2[ParsingContext2["SwitchClauses"] = 2] = "SwitchClauses"; @@ -34667,43 +33207,31 @@ ${lanes.join("\n")} ParsingContext2[ParsingContext2["Count"] = 26] = "Count"; })(ParsingContext || (ParsingContext = {})); let Tristate; - ((Tristate2) => { + (Tristate2 => { Tristate2[Tristate2["False"] = 0] = "False"; Tristate2[Tristate2["True"] = 1] = "True"; Tristate2[Tristate2["Unknown"] = 2] = "Unknown"; })(Tristate || (Tristate = {})); let JSDocParser; - ((JSDocParser2) => { + (JSDocParser2 => { function parseJSDocTypeExpressionForTests2(content, start, length2) { - initializeState( - "file.js", - content, - 99 /* Latest */, - /*syntaxCursor*/ - void 0, - 1 /* JS */, - 0 /* ParseAll */ - ); + initializeState("file.js", content, 99 /* Latest */, /*syntaxCursor*/ + void 0, 1 /* JS */, 0 /* ParseAll */); + scanner2.setText(content, start, length2); currentToken = scanner2.scan(); const jsDocTypeExpression = parseJSDocTypeExpression(); - const sourceFile = createSourceFile2( - "file.js", - 99 /* Latest */, - 1 /* JS */, - /*isDeclarationFile*/ - false, - [], - factoryCreateToken(1 /* EndOfFileToken */), - 0 /* None */, - noop - ); + const sourceFile = createSourceFile2("file.js", 99 /* Latest */, 1 /* JS */, /*isDeclarationFile*/ + false, [], factoryCreateToken(1 /* EndOfFileToken */), 0 /* None */, noop); const diagnostics = attachFileToDiagnostics(parseDiagnostics, sourceFile); if (jsDocDiagnostics) { sourceFile.jsDocDiagnostics = attachFileToDiagnostics(jsDocDiagnostics, sourceFile); } clearState(); - return jsDocTypeExpression ? { jsDocTypeExpression, diagnostics } : void 0; + return jsDocTypeExpression ? { + jsDocTypeExpression, + diagnostics + } : void 0; } JSDocParser2.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests2; function parseJSDocTypeExpression(mayOmitBraces) { @@ -34713,6 +33241,7 @@ ${lanes.join("\n")} if (!mayOmitBraces || hasBrace) { parseExpectedJSDoc(20 /* CloseBraceToken */); } + const result = factory2.createJSDocTypeExpression(type); fixupParentReferences(result); return finishNode(result, pos); @@ -34722,10 +33251,8 @@ ${lanes.join("\n")} const pos = getNodePos(); const hasBrace = parseOptional(19 /* OpenBraceToken */); const p2 = getNodePos(); - let entityName = parseEntityName( - /*allowReservedWords*/ - false - ); + let entityName = parseEntityName( /*allowReservedWords*/ + false); while (token() === 81 /* PrivateIdentifier */) { reScanHashToken(); nextTokenJSDoc(); @@ -34734,26 +33261,27 @@ ${lanes.join("\n")} if (hasBrace) { parseExpectedJSDoc(20 /* CloseBraceToken */); } + const result = factory2.createJSDocNameReference(entityName); fixupParentReferences(result); return finishNode(result, pos); } JSDocParser2.parseJSDocNameReference = parseJSDocNameReference; function parseIsolatedJSDocComment2(content, start, length2) { - initializeState( - "", - content, - 99 /* Latest */, - /*syntaxCursor*/ - void 0, - 1 /* JS */, - 0 /* ParseAll */ - ); + initializeState("", content, 99 /* Latest */, /*syntaxCursor*/ + void 0, 1 /* JS */, 0 /* ParseAll */); + const jsDoc = doInsideOfContext(16777216 /* JSDoc */, () => parseJSDocCommentWorker(start, length2)); - const sourceFile = { languageVariant: 0 /* Standard */, text: content }; + const sourceFile = { + languageVariant: 0 /* Standard */, + text: content + }; const diagnostics = attachFileToDiagnostics(parseDiagnostics, sourceFile); clearState(); - return jsDoc ? { jsDoc, diagnostics } : void 0; + return jsDoc ? { + jsDoc, + diagnostics + } : void 0; } JSDocParser2.parseIsolatedJSDocComment = parseIsolatedJSDocComment2; function parseJSDocComment(parent2, start, length2) { @@ -34775,14 +33303,14 @@ ${lanes.join("\n")} } JSDocParser2.parseJSDocComment = parseJSDocComment; let JSDocState; - ((JSDocState2) => { + (JSDocState2 => { JSDocState2[JSDocState2["BeginningOfLine"] = 0] = "BeginningOfLine"; JSDocState2[JSDocState2["SawAsterisk"] = 1] = "SawAsterisk"; JSDocState2[JSDocState2["SavingComments"] = 2] = "SavingComments"; JSDocState2[JSDocState2["SavingBackticks"] = 3] = "SavingBackticks"; })(JSDocState || (JSDocState = {})); let PropertyLikeParse; - ((PropertyLikeParse2) => { + (PropertyLikeParse2 => { PropertyLikeParse2[PropertyLikeParse2["Property"] = 1] = "Property"; PropertyLikeParse2[PropertyLikeParse2["Parameter"] = 2] = "Parameter"; PropertyLikeParse2[PropertyLikeParse2["CallbackParameter"] = 4] = "CallbackParameter"; @@ -34821,88 +33349,84 @@ ${lanes.join("\n")} indent3 += text.length; } nextTokenJSDoc(); - while (parseOptionalJsdoc(5 /* WhitespaceTrivia */)) - ; + while (parseOptionalJsdoc(5 /* WhitespaceTrivia */)); if (parseOptionalJsdoc(4 /* NewLineTrivia */)) { state = 0 /* BeginningOfLine */; indent3 = 0; } - loop: - while (true) { - switch (token()) { - case 60 /* AtToken */: - removeTrailingWhitespace(comments); - if (!commentsPos) - commentsPos = getNodePos(); - addTag(parseTag(indent3)); - state = 0 /* BeginningOfLine */; - margin = void 0; - break; - case 4 /* NewLineTrivia */: - comments.push(scanner2.getTokenText()); - state = 0 /* BeginningOfLine */; - indent3 = 0; - break; - case 42 /* AsteriskToken */: - const asterisk = scanner2.getTokenText(); - if (state === 1 /* SawAsterisk */) { - state = 2 /* SavingComments */; - pushComment(asterisk); - } else { - Debug.assert(state === 0 /* BeginningOfLine */); - state = 1 /* SawAsterisk */; - indent3 += asterisk.length; - } - break; - case 5 /* WhitespaceTrivia */: - Debug.assert(state !== 2 /* SavingComments */, "whitespace shouldn't come from the scanner while saving top-level comment text"); - const whitespace = scanner2.getTokenText(); - if (margin !== void 0 && indent3 + whitespace.length > margin) { - comments.push(whitespace.slice(margin - indent3)); - } - indent3 += whitespace.length; - break; - case 1 /* EndOfFileToken */: - break loop; - case 82 /* JSDocCommentTextToken */: + loop: while (true) { + switch (token()) { + case 60 /* AtToken */: + removeTrailingWhitespace(comments); + if (!commentsPos) commentsPos = getNodePos(); + addTag(parseTag(indent3)); + state = 0 /* BeginningOfLine */; + margin = void 0; + break; + case 4 /* NewLineTrivia */: + comments.push(scanner2.getTokenText()); + state = 0 /* BeginningOfLine */; + indent3 = 0; + break; + case 42 /* AsteriskToken */: + const asterisk = scanner2.getTokenText(); + if (state === 1 /* SawAsterisk */) { state = 2 /* SavingComments */; - pushComment(scanner2.getTokenValue()); - break; - case 19 /* OpenBraceToken */: - state = 2 /* SavingComments */; - const commentEnd = scanner2.getTokenFullStart(); - const linkStart = scanner2.getTokenEnd() - 1; - const link = parseJSDocLink(linkStart); - if (link) { - if (!linkEnd) { - removeLeadingNewlines(comments); - } - parts.push(finishNode(factory2.createJSDocText(comments.join("")), linkEnd ?? start, commentEnd)); - parts.push(link); - comments = []; - linkEnd = scanner2.getTokenEnd(); - break; + pushComment(asterisk); + } else { + Debug.assert(state === 0 /* BeginningOfLine */); + state = 1 /* SawAsterisk */; + indent3 += asterisk.length; + } + break; + case 5 /* WhitespaceTrivia */: + Debug.assert(state !== 2 /* SavingComments */, "whitespace shouldn't come from the scanner while saving top-level comment text"); + const whitespace = scanner2.getTokenText(); + if (margin !== void 0 && indent3 + whitespace.length > margin) { + comments.push(whitespace.slice(margin - indent3)); + } + indent3 += whitespace.length; + break; + case 1 /* EndOfFileToken */: + break loop; + case 82 /* JSDocCommentTextToken */: + state = 2 /* SavingComments */; + pushComment(scanner2.getTokenValue()); + break; + case 19 /* OpenBraceToken */: + state = 2 /* SavingComments */; + const commentEnd = scanner2.getTokenFullStart(); + const linkStart = scanner2.getTokenEnd() - 1; + const link = parseJSDocLink(linkStart); + if (link) { + var _linkEnd; + if (!linkEnd) { + removeLeadingNewlines(comments); } - default: - state = 2 /* SavingComments */; - pushComment(scanner2.getTokenText()); + parts.push(finishNode(factory2.createJSDocText(comments.join("")), (_linkEnd = linkEnd) !== null && _linkEnd !== void 0 ? _linkEnd : start, commentEnd)); + parts.push(link); + comments = []; + linkEnd = scanner2.getTokenEnd(); break; - } - if (state === 2 /* SavingComments */) { - nextJSDocCommentTextToken( - /*inBackticks*/ - false - ); - } else { - nextTokenJSDoc(); - } + } + default: + state = 2 /* SavingComments */; + pushComment(scanner2.getTokenText()); + break; } + if (state === 2 /* SavingComments */) { + nextJSDocCommentTextToken( /*inBackticks*/ + false); + } else { + nextTokenJSDoc(); + } + } const trimmedComments = comments.join("").trimEnd(); if (parts.length && trimmedComments.length) { - parts.push(finishNode(factory2.createJSDocText(trimmedComments), linkEnd ?? start, commentsPos)); + var _linkEnd2; + parts.push(finishNode(factory2.createJSDocText(trimmedComments), (_linkEnd2 = linkEnd) !== null && _linkEnd2 !== void 0 ? _linkEnd2 : 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); } @@ -34971,10 +33495,8 @@ ${lanes.join("\n")} Debug.assert(token() === 60 /* AtToken */); const start2 = scanner2.getTokenStart(); nextTokenJSDoc(); - const tagName = parseJSDocIdentifierName( - /*message*/ - void 0 - ); + const tagName = parseJSDocIdentifierName( /*message*/ + void 0); const indentText = skipWhitespaceOrAsterisk(); let tag; switch (tagName.escapedText) { @@ -35082,81 +33604,87 @@ ${lanes.join("\n")} } state = 1 /* SawAsterisk */; } + let tok = token(); - loop: - while (true) { - switch (tok) { - case 4 /* NewLineTrivia */: - state = 0 /* BeginningOfLine */; - comments2.push(scanner2.getTokenText()); - indent3 = 0; - break; - case 60 /* AtToken */: - scanner2.resetTokenState(scanner2.getTokenEnd() - 1); - break loop; - case 1 /* EndOfFileToken */: - break loop; - case 5 /* WhitespaceTrivia */: - Debug.assert(state !== 2 /* SavingComments */ && state !== 3 /* SavingBackticks */, "whitespace shouldn't come from the scanner while saving comment text"); - const whitespace = scanner2.getTokenText(); - if (margin !== void 0 && indent3 + whitespace.length > margin) { - comments2.push(whitespace.slice(margin - indent3)); - state = 2 /* SavingComments */; - } - indent3 += whitespace.length; - break; - case 19 /* OpenBraceToken */: + loop: while (true) { + switch (tok) { + case 4 /* NewLineTrivia */: + state = 0 /* BeginningOfLine */; + comments2.push(scanner2.getTokenText()); + indent3 = 0; + break; + case 60 /* AtToken */: + scanner2.resetTokenState(scanner2.getTokenEnd() - 1); + break loop; + case 1 /* EndOfFileToken */: + break loop; + case 5 /* WhitespaceTrivia */: + Debug.assert(state !== 2 /* SavingComments */ && state !== 3 /* SavingBackticks */, "whitespace shouldn't come from the scanner while saving comment text"); + const whitespace = scanner2.getTokenText(); + if (margin !== void 0 && indent3 + whitespace.length > margin) { + comments2.push(whitespace.slice(margin - indent3)); state = 2 /* SavingComments */; - const commentEnd = scanner2.getTokenFullStart(); - const linkStart = scanner2.getTokenEnd() - 1; - const link = parseJSDocLink(linkStart); - if (link) { - parts2.push(finishNode(factory2.createJSDocText(comments2.join("")), linkEnd2 ?? commentsPos2, commentEnd)); - parts2.push(link); - comments2 = []; - linkEnd2 = scanner2.getTokenEnd(); - } else { - pushComment(scanner2.getTokenText()); - } - break; - case 62 /* BacktickToken */: - if (state === 3 /* SavingBackticks */) { - state = 2 /* SavingComments */; - } else { - state = 3 /* SavingBackticks */; - } + } + + indent3 += whitespace.length; + break; + case 19 /* OpenBraceToken */: + state = 2 /* SavingComments */; + const commentEnd = scanner2.getTokenFullStart(); + const linkStart = scanner2.getTokenEnd() - 1; + const link = parseJSDocLink(linkStart); + if (link) { + var _linkEnd3; + parts2.push(finishNode(factory2.createJSDocText(comments2.join("")), (_linkEnd3 = linkEnd2) !== null && _linkEnd3 !== void 0 ? _linkEnd3 : commentsPos2, commentEnd)); + parts2.push(link); + comments2 = []; + linkEnd2 = scanner2.getTokenEnd(); + } else { pushComment(scanner2.getTokenText()); + } + break; + case 62 /* BacktickToken */: + if (state === 3 /* SavingBackticks */) { + state = 2 /* SavingComments */; + } else { + state = 3 /* SavingBackticks */; + } + + pushComment(scanner2.getTokenText()); + break; + case 82 /* JSDocCommentTextToken */: + if (state !== 3 /* SavingBackticks */) { + state = 2 /* SavingComments */; + } + + pushComment(scanner2.getTokenValue()); + break; + case 42 /* AsteriskToken */: + if (state === 0 /* BeginningOfLine */) { + state = 1 /* SawAsterisk */; + indent3 += 1; break; - case 82 /* JSDocCommentTextToken */: - if (state !== 3 /* SavingBackticks */) { - state = 2 /* SavingComments */; - } - pushComment(scanner2.getTokenValue()); - break; - case 42 /* AsteriskToken */: - if (state === 0 /* BeginningOfLine */) { - state = 1 /* SawAsterisk */; - indent3 += 1; - break; - } - default: - if (state !== 3 /* SavingBackticks */) { - state = 2 /* SavingComments */; - } - pushComment(scanner2.getTokenText()); - break; - } - if (state === 2 /* SavingComments */ || state === 3 /* SavingBackticks */) { - tok = nextJSDocCommentTextToken(state === 3 /* SavingBackticks */); - } else { - tok = nextTokenJSDoc(); - } + } + default: + if (state !== 3 /* SavingBackticks */) { + state = 2 /* SavingComments */; + } + + pushComment(scanner2.getTokenText()); + break; } + if (state === 2 /* SavingComments */ || state === 3 /* SavingBackticks */) { + tok = nextJSDocCommentTextToken(state === 3 /* SavingBackticks */); + } else { + tok = nextTokenJSDoc(); + } + } removeLeadingNewlines(comments2); const trimmedComments = comments2.join("").trimEnd(); if (parts2.length) { if (trimmedComments.length) { - parts2.push(finishNode(factory2.createJSDocText(trimmedComments), linkEnd2 ?? commentsPos2)); + var _linkEnd4; + parts2.push(finishNode(factory2.createJSDocText(trimmedComments), (_linkEnd4 = linkEnd2) !== null && _linkEnd4 !== void 0 ? _linkEnd4 : commentsPos2)); } return createNodeArray(parts2, commentsPos2, scanner2.getTokenEnd()); } else if (trimmedComments.length) { @@ -35171,10 +33699,8 @@ ${lanes.join("\n")} nextTokenJSDoc(); skipWhitespace(); const p2 = getNodePos(); - let name = tokenIsIdentifierOrKeyword(token()) ? parseEntityName( - /*allowReservedWords*/ - true - ) : void 0; + let name = tokenIsIdentifierOrKeyword(token()) ? parseEntityName( /*allowReservedWords*/ + true) : void 0; if (name) { while (token() === 81 /* PrivateIdentifier */) { reScanHashToken(); @@ -35194,8 +33720,7 @@ ${lanes.join("\n")} 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) { @@ -35230,6 +33755,7 @@ ${lanes.join("\n")} if (isBackquoted) { parseExpectedTokenJSDoc(62 /* BacktickToken */); } + if (isBracketed) { skipWhitespace(); if (parseOptionalToken(64 /* EqualsToken */)) { @@ -35237,7 +33763,11 @@ ${lanes.join("\n")} } parseExpected(24 /* CloseBracketToken */); } - return { name, isBracketed }; + + return { + name, + isBracketed + }; } function isObjectOrObjectArrayTypeReference(node) { switch (node.kind) { @@ -35253,7 +33783,10 @@ ${lanes.join("\n")} let typeExpression = tryParseTypeExpression(); let isNameFirst = !typeExpression; skipWhitespaceOrAsterisk(); - const { name, isBracketed } = parseBracketNameInPropertyAndParamTag(); + const { + name, + isBracketed + } = parseBracketNameInPropertyAndParamTag(); const indentText = skipWhitespaceOrAsterisk(); if (isNameFirst && !lookAhead(parseJSDocLinkPrefix)) { typeExpression = tryParseTypeExpression(); @@ -35296,10 +33829,8 @@ ${lanes.join("\n")} if (some(tags, isJSDocTypeTag)) { parseErrorAt(tagName.pos, scanner2.getTokenStart(), Diagnostics._0_tag_already_specified, unescapeLeadingUnderscores(tagName.escapedText)); } - const typeExpression = parseJSDocTypeExpression( - /*mayOmitBraces*/ - true - ); + const typeExpression = parseJSDocTypeExpression( /*mayOmitBraces*/ + true); const comments2 = indent3 !== void 0 && indentText !== void 0 ? parseTrailingTagComments(start2, getNodePos(), indent3, indentText) : void 0; return finishNode(factory2.createJSDocTypeTag(tagName, typeExpression, comments2), start2); } @@ -35353,10 +33884,8 @@ ${lanes.join("\n")} return finishNode(factory2.createJSDocAugmentsTag(tagName, className, parseTrailingTagComments(start2, getNodePos(), margin, indentText)), start2); } function parseSatisfiesTag(start2, tagName, margin, indentText) { - const typeExpression = parseJSDocTypeExpression( - /*mayOmitBraces*/ - false - ); + const typeExpression = parseJSDocTypeExpression( /*mayOmitBraces*/ + false); const comments2 = margin !== void 0 && indentText !== void 0 ? parseTrailingTagComments(start2, getNodePos(), margin, indentText) : void 0; return finishNode(factory2.createJSDocSatisfiesTag(tagName, typeExpression, comments2), start2); } @@ -35372,6 +33901,7 @@ ${lanes.join("\n")} if (usedBrace) { parseExpected(20 /* CloseBraceToken */); } + return res; } function parsePropertyAccessEntityNameExpression() { @@ -35387,22 +33917,19 @@ ${lanes.join("\n")} return finishNode(createTag(tagName, parseTrailingTagComments(start2, getNodePos(), margin, indentText)), start2); } function parseThisTag(start2, tagName, margin, indentText) { - const typeExpression = parseJSDocTypeExpression( - /*mayOmitBraces*/ - true - ); + const typeExpression = parseJSDocTypeExpression( /*mayOmitBraces*/ + true); skipWhitespace(); return finishNode(factory2.createJSDocThisTag(tagName, typeExpression, parseTrailingTagComments(start2, getNodePos(), margin, indentText)), start2); } function parseEnumTag(start2, tagName, margin, indentText) { - const typeExpression = parseJSDocTypeExpression( - /*mayOmitBraces*/ - true - ); + const typeExpression = parseJSDocTypeExpression( /*mayOmitBraces*/ + true); skipWhitespace(); return finishNode(factory2.createJSDocEnumTag(tagName, typeExpression, parseTrailingTagComments(start2, getNodePos(), margin, indentText)), start2); } function parseTypedefTag(start2, tagName, indent3, indentText) { + var _ref8; let typeExpression = tryParseTypeExpression(); skipWhitespaceOrAsterisk(); const fullName = parseJSDocTypeNameWithNamespace(); @@ -35440,7 +33967,7 @@ ${lanes.join("\n")} end2 = typeExpression.end; } } - end2 = end2 || comment !== void 0 ? getNodePos() : (fullName ?? typeExpression ?? tagName).end; + end2 = end2 || comment !== void 0 ? getNodePos() : ((_ref8 = fullName !== null && fullName !== void 0 ? fullName : typeExpression) !== null && _ref8 !== void 0 ? _ref8 : tagName).end; if (!comment) { comment = parseTrailingTagComments(start2, end2, indent3, indentText); } @@ -35454,22 +33981,16 @@ ${lanes.join("\n")} } const typeNameOrNamespaceName = parseJSDocIdentifierName(); if (parseOptional(25 /* DotToken */)) { - const body = parseJSDocTypeNameWithNamespace( - /*nested*/ - true - ); - const jsDocNamespaceNode = factory2.createModuleDeclaration( - /*modifiers*/ - void 0, - typeNameOrNamespaceName, - body, - nested ? 8 /* NestedNamespace */ : void 0 - ); + const body = parseJSDocTypeNameWithNamespace( /*nested*/ + true); + const jsDocNamespaceNode = factory2.createModuleDeclaration( /*modifiers*/ + void 0, typeNameOrNamespaceName, body, nested ? 8 /* NestedNamespace */ : void 0); return finishNode(jsDocNamespaceNode, start2); } if (nested) { typeNameOrNamespaceName.flags |= 4096 /* IdentifierIsInJSDocNamespace */; } + return typeNameOrNamespaceName; } function parseCallbackTagParameters(indent3) { @@ -35495,12 +34016,8 @@ ${lanes.join("\n")} } } }); - return finishNode(factory2.createJSDocSignature( - /*typeParameters*/ - void 0, - parameters, - returnTag - ), start2); + return finishNode(factory2.createJSDocSignature( /*typeParameters*/ + void 0, parameters, returnTag), start2); } function parseCallbackTag(start2, tagName, indent3, indentText) { const fullName = parseJSDocTypeNameWithNamespace(); @@ -35613,17 +34130,13 @@ ${lanes.join("\n")} defaultType = doInsideOfContext(16777216 /* JSDoc */, parseJSDocType); parseExpected(24 /* CloseBracketToken */); } + if (nodeIsMissing(name)) { return void 0; } - return finishNode(factory2.createTypeParameterDeclaration( - /*modifiers*/ - void 0, - name, - /*constraint*/ - void 0, - defaultType - ), typeParameterPos); + return finishNode(factory2.createTypeParameterDeclaration( /*modifiers*/ + void 0, name, /*constraint*/ + void 0, defaultType), typeParameterPos); } function parseTemplateTagTypeParameters() { const pos = getNodePos(); @@ -35655,23 +34168,21 @@ ${lanes.join("\n")} if (parseOptional(23 /* OpenBracketToken */)) { parseExpected(24 /* CloseBracketToken */); } + while (parseOptional(25 /* DotToken */)) { const name = parseJSDocIdentifierName(); if (parseOptional(23 /* OpenBracketToken */)) { parseExpected(24 /* CloseBracketToken */); } + entity = createQualifiedName(entity, name); } return entity; } function parseJSDocIdentifierName(message) { if (!tokenIsIdentifierOrKeyword(token())) { - return createMissingNode( - 80 /* Identifier */, - /*reportAtCurrentPosition*/ - !message, - message || Diagnostics.Identifier_expected - ); + return createMissingNode(80 /* Identifier */, /*reportAtCurrentPosition*/ + !message, message || Diagnostics.Identifier_expected); } identifierCount++; const start2 = scanner2.getTokenStart(); @@ -35685,7 +34196,7 @@ ${lanes.join("\n")} } })(JSDocParser = Parser2.JSDocParser || (Parser2.JSDocParser = {})); })(Parser || (Parser = {})); - ((IncrementalParser2) => { + (IncrementalParser2 => { function updateSourceFile2(sourceFile, newText, textChangeRange, aggressiveChecks) { aggressiveChecks = aggressiveChecks || Debug.shouldAssert(2 /* Aggressive */); checkChangeRange(sourceFile, newText, textChangeRange, aggressiveChecks); @@ -35693,18 +34204,9 @@ ${lanes.join("\n")} return sourceFile; } if (sourceFile.statements.length === 0) { - return Parser.parseSourceFile( - sourceFile.fileName, - newText, - sourceFile.languageVersion, - /*syntaxCursor*/ - void 0, - /*setParentNodes*/ - true, - sourceFile.scriptKind, - sourceFile.setExternalModuleIndicator, - sourceFile.jsDocParsingMode - ); + return Parser.parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, /*syntaxCursor*/ + void 0, /*setParentNodes*/ + true, sourceFile.scriptKind, sourceFile.setExternalModuleIndicator, sourceFile.jsDocParsingMode); } const incrementalSourceFile = sourceFile; Debug.assert(!incrementalSourceFile.hasBeenIncrementallyParsed); @@ -35719,44 +34221,31 @@ ${lanes.join("\n")} Debug.assert(textSpanEnd(textChangeRangeNewSpan(changeRange)) === textSpanEnd(textChangeRangeNewSpan(textChangeRange))); const delta = textChangeRangeNewSpan(changeRange).length - changeRange.span.length; updateTokenPositionsAndMarkElements(incrementalSourceFile, changeRange.span.start, textSpanEnd(changeRange.span), textSpanEnd(textChangeRangeNewSpan(changeRange)), delta, oldText, newText, aggressiveChecks); - const result = Parser.parseSourceFile( - sourceFile.fileName, - newText, - sourceFile.languageVersion, - syntaxCursor, - /*setParentNodes*/ - true, - sourceFile.scriptKind, - sourceFile.setExternalModuleIndicator, - sourceFile.jsDocParsingMode - ); - result.commentDirectives = getNewCommentDirectives( - sourceFile.commentDirectives, - result.commentDirectives, - changeRange.span.start, - textSpanEnd(changeRange.span), - delta, - oldText, - newText, - aggressiveChecks - ); + const result = Parser.parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, syntaxCursor, /*setParentNodes*/ + true, sourceFile.scriptKind, sourceFile.setExternalModuleIndicator, sourceFile.jsDocParsingMode); + result.commentDirectives = getNewCommentDirectives(sourceFile.commentDirectives, result.commentDirectives, changeRange.span.start, textSpanEnd(changeRange.span), delta, oldText, newText, aggressiveChecks); result.impliedNodeFormat = sourceFile.impliedNodeFormat; return result; } 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) { - const { range, type } = directive; + const { + range, + type + } = directive; if (range.end < changeStart) { commentDirectives = append(commentDirectives, directive); } else if (range.pos > changeRangeOldEnd) { addNewlyScannedDirectives(); const updatedDirective = { - range: { pos: range.pos + delta, end: range.end + delta }, + range: { + pos: range.pos + delta, + end: range.end + delta + }, type }; commentDirectives = append(commentDirectives, updatedDirective); @@ -35768,8 +34257,7 @@ ${lanes.join("\n")} addNewlyScannedDirectives(); return commentDirectives; function addNewlyScannedDirectives() { - if (addedNewlyScannedDirectives) - return; + if (addedNewlyScannedDirectives) return; addedNewlyScannedDirectives = true; if (!commentDirectives) { commentDirectives = newDirectives; @@ -35827,14 +34315,12 @@ ${lanes.join("\n")} Debug.assert(element.pos <= changeRangeOldEnd, "Adjusting an element that was entirely after the change range"); Debug.assert(element.pos <= element.end); const pos = Math.min(element.pos, changeRangeNewEnd); - const end = element.end >= changeRangeOldEnd ? ( - // Element ends after the change range. Always adjust the end pos. - element.end + delta - ) : ( - // Element ends in the change range. The element will keep its position if - // possible. Or Move backward to the new-end if it's in the 'Y' range. - Math.min(element.end, changeRangeNewEnd) - ); + const end = element.end >= changeRangeOldEnd ? + // Element ends after the change range. Always adjust the end pos. + element.end + delta : + // Element ends in the change range. The element will keep its position if + // possible. Or Move backward to the new-end if it's in the 'Y' range. + Math.min(element.end, changeRangeNewEnd); Debug.assert(pos <= end); if (element.parent) { Debug.assertGreaterThanOrEqual(pos, element.parent.pos); @@ -35845,7 +34331,7 @@ ${lanes.join("\n")} function checkNodePositions(node, aggressiveChecks) { if (aggressiveChecks) { let pos = node.pos; - const visitNode3 = (child) => { + const visitNode3 = child => { Debug.assert(child.pos >= pos); pos = child.end; }; @@ -35864,15 +34350,8 @@ ${lanes.join("\n")} function visitNode3(child) { Debug.assert(child.pos <= child.end); if (child.pos > changeRangeOldEnd) { - moveElementEntirelyPastChangeRange( - child, - /*isArray*/ - false, - delta, - oldText, - newText, - aggressiveChecks - ); + moveElementEntirelyPastChangeRange(child, /*isArray*/ + false, delta, oldText, newText, aggressiveChecks); return; } const fullEnd = child.end; @@ -35894,15 +34373,8 @@ ${lanes.join("\n")} function visitArray2(array) { Debug.assert(array.pos <= array.end); if (array.pos > changeRangeOldEnd) { - moveElementEntirelyPastChangeRange( - array, - /*isArray*/ - true, - delta, - oldText, - newText, - aggressiveChecks - ); + moveElementEntirelyPastChangeRange(array, /*isArray*/ + true, delta, oldText, newText, aggressiveChecks); return; } const fullEnd = array.end; @@ -36047,11 +34519,11 @@ ${lanes.join("\n")} } IncrementalParser2.createSyntaxCursor = createSyntaxCursor; let InvalidPosition; - ((InvalidPosition2) => { + (InvalidPosition2 => { InvalidPosition2[InvalidPosition2["Value"] = -1] = "Value"; })(InvalidPosition || (InvalidPosition = {})); })(IncrementalParser || (IncrementalParser = {})); - namedArgRegExCache = /* @__PURE__ */ new Map(); + namedArgRegExCache = /* @__PURE__ */new Map(); tripleSlashXMLCommentStartRegEx = /^\/\/\/\s*<(\S+)\s.*?\/>/im; singleLinePragmaRegEx = /^\/\/\/?\s*@([^\s:]+)(.*)\s*$/im; } @@ -36059,15 +34531,18 @@ ${lanes.join("\n")} // src/compiler/commandLineParser.ts function createOptionNameMap(optionDeclarations2) { - const optionsNameMap = /* @__PURE__ */ new Map(); - const shortOptionNames = /* @__PURE__ */ new Map(); - forEach(optionDeclarations2, (option) => { + const optionsNameMap = /* @__PURE__ */new Map(); + const shortOptionNames = /* @__PURE__ */new Map(); + forEach(optionDeclarations2, option => { optionsNameMap.set(option.name.toLowerCase(), option); if (option.shortName) { shortOptionNames.set(option.shortName, option.name); } }); - return { optionsNameMap, shortOptionNames }; + return { + optionsNameMap, + shortOptionNames + }; } function getOptionsNameMap() { return optionsNameMapCache || (optionsNameMapCache = createOptionNameMap(optionDeclarations)); @@ -36077,11 +34552,11 @@ ${lanes.join("\n")} } function createDiagnosticForInvalidCustomType(opt, createDiagnostic) { const namesOfType = arrayFrom(opt.type.keys()); - const stringNames = (opt.deprecatedKeys ? namesOfType.filter((k) => !opt.deprecatedKeys.has(k)) : namesOfType).map((key) => `'${key}'`).join(", "); + const stringNames = (opt.deprecatedKeys ? namesOfType.filter(k => !opt.deprecatedKeys.has(k)) : namesOfType).map(key => `'${key}'`).join(", "); return createDiagnostic(Diagnostics.Argument_for_0_option_must_be_Colon_1, `--${opt.name}`, stringNames); } function parseCustomTypeOption(opt, value, errors) { - return convertJsonOptionOfCustomType(opt, (value ?? "").trim(), errors); + return convertJsonOptionOfCustomType(opt, (value !== null && value !== void 0 ? value : "").trim(), errors); } function parseListTypeOption(opt, value = "", errors) { value = value.trim(); @@ -36097,14 +34572,14 @@ ${lanes.join("\n")} const values = value.split(","); switch (opt.element.type) { case "number": - return mapDefined(values, (v) => validateJsonOptionValue(opt.element, parseInt(v), errors)); + return mapDefined(values, v => validateJsonOptionValue(opt.element, parseInt(v), errors)); case "string": - return mapDefined(values, (v) => validateJsonOptionValue(opt.element, v || "", errors)); + return mapDefined(values, v => validateJsonOptionValue(opt.element, v || "", errors)); case "boolean": case "object": return Debug.fail(`List of ${opt.element.type} is not yet supported.`); default: - return mapDefined(values, (v) => parseCustomTypeOption(opt.element, v, errors)); + return mapDefined(values, v => parseCustomTypeOption(opt.element, v, errors)); } } function getOptionName(option) { @@ -36139,21 +34614,13 @@ ${lanes.join("\n")} parseResponseFile(s.slice(1)); } else if (s.charCodeAt(0) === 45 /* minus */) { const inputOptionName = s.slice(s.charCodeAt(1) === 45 /* minus */ ? 2 : 1); - const opt = getOptionDeclarationFromName( - diagnostics.getOptionsNameMap, - inputOptionName, - /*allowShort*/ - true - ); + const opt = getOptionDeclarationFromName(diagnostics.getOptionsNameMap, inputOptionName, /*allowShort*/ + true); if (opt) { i = parseOptionValue(args, i, diagnostics, opt, options, errors); } else { - const watchOpt = getOptionDeclarationFromName( - watchOptionsDidYouMeanDiagnostics.getOptionsNameMap, - inputOptionName, - /*allowShort*/ - true - ); + const watchOpt = getOptionDeclarationFromName(watchOptionsDidYouMeanDiagnostics.getOptionsNameMap, inputOptionName, /*allowShort*/ + true); if (watchOpt) { i = parseOptionValue(args, i, watchOptionsDidYouMeanDiagnostics, watchOpt, watchOptions || (watchOptions = {}), errors); } else { @@ -36166,7 +34633,7 @@ ${lanes.join("\n")} } } function parseResponseFile(fileName) { - const text = tryReadFile(fileName, readFile || ((fileName2) => sys.readFile(fileName2))); + const text = tryReadFile(fileName, readFile || (fileName2 => sys.readFile(fileName2))); if (!isString(text)) { errors.push(text); return; @@ -36174,15 +34641,12 @@ ${lanes.join("\n")} 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++; @@ -36190,8 +34654,7 @@ ${lanes.join("\n")} 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)); } } @@ -36206,22 +34669,16 @@ ${lanes.join("\n")} i++; } else if (opt.type === "boolean") { if (optValue === "false") { - options[opt.name] = validateJsonOptionValue( - opt, - /*value*/ - false, - errors - ); + options[opt.name] = validateJsonOptionValue(opt, /*value*/ + false, 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") { @@ -36274,7 +34731,10 @@ ${lanes.join("\n")} } function getOptionDeclarationFromName(getOptionNameMap, optionName, allowShort = false) { optionName = optionName.toLowerCase(); - const { optionsNameMap, shortOptionNames } = getOptionNameMap(); + const { + optionsNameMap, + shortOptionNames + } = getOptionNameMap(); if (allowShort) { const short = shortOptionNames.get(optionName); if (short !== void 0) { @@ -36287,10 +34747,12 @@ ${lanes.join("\n")} return buildOptionsNameMapCache || (buildOptionsNameMapCache = createOptionNameMap(buildOpts)); } function parseBuildCommand(args) { - const { options, watchOptions, fileNames: projects, errors } = parseCommandLineWorker( - buildOptionsDidYouMeanDiagnostics, - args - ); + const { + options, + watchOptions, + fileNames: projects, + errors + } = parseCommandLineWorker(buildOptionsDidYouMeanDiagnostics, args); const buildOptions = options; if (projects.length === 0) { projects.push("."); @@ -36307,13 +34769,18 @@ ${lanes.join("\n")} if (buildOptions.watch && buildOptions.dry) { errors.push(createCompilerDiagnostic(Diagnostics.Options_0_and_1_cannot_be_combined, "watch", "dry")); } - return { buildOptions, watchOptions, projects, errors }; + return { + buildOptions, + watchOptions, + projects, + errors + }; } function getDiagnosticText(message, ...args) { return cast(createCompilerDiagnostic(message, ...args).messageText, isString); } function getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host, extendedConfigCache, watchOptionsToExtend, extraFileExtensions) { - const configFileText = tryReadFile(configFileName, (fileName) => host.readFile(fileName)); + const configFileText = tryReadFile(configFileName, fileName => host.readFile(fileName)); if (!isString(configFileText)) { host.onUnRecoverableConfigFileDiagnostic(configFileText); return void 0; @@ -36323,38 +34790,30 @@ ${lanes.join("\n")} result.path = toPath(configFileName, cwd, createGetCanonicalFileName(host.useCaseSensitiveFileNames)); result.resolvedPath = result.path; result.originalFileName = result.fileName; - return parseJsonSourceFileConfigFileContent( - result, - host, - getNormalizedAbsolutePath(getDirectoryPath(configFileName), cwd), - optionsToExtend, - getNormalizedAbsolutePath(configFileName, cwd), - /*resolutionStack*/ - void 0, - extraFileExtensions, - extendedConfigCache, - watchOptionsToExtend - ); + return parseJsonSourceFileConfigFileContent(result, host, getNormalizedAbsolutePath(getDirectoryPath(configFileName), cwd), optionsToExtend, getNormalizedAbsolutePath(configFileName, cwd), /*resolutionStack*/ + void 0, extraFileExtensions, extendedConfigCache, watchOptionsToExtend); } function readConfigFile(fileName, readFile) { const textOrDiagnostic = tryReadFile(fileName, readFile); - return isString(textOrDiagnostic) ? parseConfigFileTextToJson(fileName, textOrDiagnostic) : { config: {}, error: textOrDiagnostic }; + return isString(textOrDiagnostic) ? parseConfigFileTextToJson(fileName, textOrDiagnostic) : { + config: {}, + error: textOrDiagnostic + }; } function parseConfigFileTextToJson(fileName, jsonText) { const jsonSourceFile = parseJsonText(fileName, jsonText); return { - config: convertConfigFileToObject( - jsonSourceFile, - jsonSourceFile.parseDiagnostics, - /*jsonConversionNotifier*/ - void 0 - ), + config: convertConfigFileToObject(jsonSourceFile, jsonSourceFile.parseDiagnostics, /*jsonConversionNotifier*/ + void 0), error: jsonSourceFile.parseDiagnostics.length ? jsonSourceFile.parseDiagnostics[0] : void 0 }; } function readJsonConfigFile(fileName, readFile) { const textOrDiagnostic = tryReadFile(fileName, readFile); - return isString(textOrDiagnostic) ? parseJsonText(fileName, textOrDiagnostic) : { fileName, parseDiagnostics: [textOrDiagnostic] }; + return isString(textOrDiagnostic) ? parseJsonText(fileName, textOrDiagnostic) : { + fileName, + parseDiagnostics: [textOrDiagnostic] + }; } function tryReadFile(fileName, readFile) { let text; @@ -36386,51 +34845,41 @@ ${lanes.join("\n")} name: void 0, // should never be needed since this is root type: "object", - elementOptions: commandLineOptionsToMap([ - compilerOptionsDeclaration, - watchOptionsDeclaration, - typeAcquisitionDeclaration, - extendsOptionDeclaration, - { + elementOptions: commandLineOptionsToMap([compilerOptionsDeclaration, watchOptionsDeclaration, typeAcquisitionDeclaration, extendsOptionDeclaration, { + name: "references", + type: "list", + element: { name: "references", - type: "list", - element: { - name: "references", - type: "object" - }, - category: Diagnostics.Projects + type: "object" }, - { + category: Diagnostics.Projects + }, { + name: "files", + type: "list", + element: { name: "files", - type: "list", - element: { - name: "files", - type: "string" - }, - category: Diagnostics.File_Management + type: "string" }, - { + category: Diagnostics.File_Management + }, { + name: "include", + type: "list", + element: { name: "include", - type: "list", - element: { - name: "include", - type: "string" - }, - category: Diagnostics.File_Management, - defaultValueDescription: Diagnostics.if_files_is_specified_otherwise_Asterisk_Asterisk_Slash_Asterisk + type: "string" }, - { + category: Diagnostics.File_Management, + defaultValueDescription: Diagnostics.if_files_is_specified_otherwise_Asterisk_Asterisk_Slash_Asterisk + }, { + name: "exclude", + type: "list", + element: { name: "exclude", - type: "list", - element: { - name: "exclude", - type: "string" - }, - category: Diagnostics.File_Management, - defaultValueDescription: Diagnostics.node_modules_bower_components_jspm_packages_plus_the_value_of_outDir_if_one_is_specified + type: "string" }, - compileOnSaveCommandLineOption - ]) + category: Diagnostics.File_Management, + defaultValueDescription: Diagnostics.node_modules_bower_components_jspm_packages_plus_the_value_of_outDir_if_one_is_specified + }, compileOnSaveCommandLineOption]) }; } return _tsconfigRootOptions; @@ -36439,47 +34888,24 @@ ${lanes.join("\n")} var _a; const rootExpression = (_a = sourceFile.statements[0]) == null ? void 0 : _a.expression; if (rootExpression && rootExpression.kind !== 210 /* ObjectLiteralExpression */) { - errors.push(createDiagnosticForNodeInSourceFile( - sourceFile, - rootExpression, - Diagnostics.The_root_value_of_a_0_file_must_be_an_object, - getBaseFileName(sourceFile.fileName) === "jsconfig.json" ? "jsconfig.json" : "tsconfig.json" - )); + errors.push(createDiagnosticForNodeInSourceFile(sourceFile, rootExpression, Diagnostics.The_root_value_of_a_0_file_must_be_an_object, getBaseFileName(sourceFile.fileName) === "jsconfig.json" ? "jsconfig.json" : "tsconfig.json")); if (isArrayLiteralExpression(rootExpression)) { const firstObject = find(rootExpression.elements, isObjectLiteralExpression); if (firstObject) { - return convertToJson( - sourceFile, - firstObject, - errors, - /*returnValue*/ - true, - jsonConversionNotifier - ); + return convertToJson(sourceFile, firstObject, errors, /*returnValue*/ + true, jsonConversionNotifier); } } return {}; } - return convertToJson( - sourceFile, - rootExpression, - errors, - /*returnValue*/ - true, - jsonConversionNotifier - ); + return convertToJson(sourceFile, rootExpression, errors, /*returnValue*/ + true, jsonConversionNotifier); } function convertToObject(sourceFile, errors) { var _a; - return convertToJson( - sourceFile, - (_a = sourceFile.statements[0]) == null ? void 0 : _a.expression, - errors, - /*returnValue*/ - true, - /*jsonConversionNotifier*/ - void 0 - ); + return convertToJson(sourceFile, (_a = sourceFile.statements[0]) == null ? void 0 : _a.expression, errors, /*returnValue*/ + true, /*jsonConversionNotifier*/ + void 0); } function convertToJson(sourceFile, rootExpression, errors, returnValue, jsonConversionNotifier) { if (!rootExpression) { @@ -36515,10 +34941,10 @@ ${lanes.join("\n")} } function convertArrayLiteralExpressionToJson(elements, elementOption) { if (!returnValue) { - elements.forEach((element) => convertPropertyValueToJson(element, elementOption)); + elements.forEach(element => convertPropertyValueToJson(element, elementOption)); return void 0; } - return filter(elements.map((element) => convertPropertyValueToJson(element, elementOption)), (v) => v !== void 0); + return filter(elements.map(element => convertPropertyValueToJson(element, elementOption)), v => v !== void 0); } function convertPropertyValueToJson(valueExpression, option) { switch (valueExpression.kind) { @@ -36544,10 +34970,7 @@ ${lanes.join("\n")} const objectLiteralExpression = valueExpression; return convertObjectLiteralExpressionToJson(objectLiteralExpression, option); case 209 /* ArrayLiteralExpression */: - return convertArrayLiteralExpressionToJson( - valueExpression.elements, - option && option.element - ); + return convertArrayLiteralExpressionToJson(valueExpression.elements, option && option.element); } if (option) { errors.push(createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, Diagnostics.Compiler_option_0_requires_a_value_of_type_1, option.name, getCompilerOptionValueTypeString(option))); @@ -36565,8 +34988,7 @@ ${lanes.join("\n")} } 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); } @@ -36581,19 +35003,11 @@ ${lanes.join("\n")} function convertToTSConfig(configParseResult, configFileName, host) { var _a, _b, _c; const getCanonicalFileName = createGetCanonicalFileName(host.useCaseSensitiveFileNames); - const files = map( - filter( - configParseResult.fileNames, - !((_b = (_a = configParseResult.options.configFile) == null ? void 0 : _a.configFileSpecs) == null ? void 0 : _b.validatedIncludeSpecs) ? returnTrue : matchesSpecs( - configFileName, - configParseResult.options.configFile.configFileSpecs.validatedIncludeSpecs, - configParseResult.options.configFile.configFileSpecs.validatedExcludeSpecs, - host - ) - ), - (f) => getRelativePathFromFile(getNormalizedAbsolutePath(configFileName, host.getCurrentDirectory()), getNormalizedAbsolutePath(f, host.getCurrentDirectory()), getCanonicalFileName) - ); - const optionMap = serializeCompilerOptions(configParseResult.options, { configFilePath: getNormalizedAbsolutePath(configFileName, host.getCurrentDirectory()), useCaseSensitiveFileNames: host.useCaseSensitiveFileNames }); + const files = map(filter(configParseResult.fileNames, !((_b = (_a = configParseResult.options.configFile) == null ? void 0 : _a.configFileSpecs) == null ? void 0 : _b.validatedIncludeSpecs) ? returnTrue : matchesSpecs(configFileName, configParseResult.options.configFile.configFileSpecs.validatedIncludeSpecs, configParseResult.options.configFile.configFileSpecs.validatedExcludeSpecs, host)), f => getRelativePathFromFile(getNormalizedAbsolutePath(configFileName, host.getCurrentDirectory()), getNormalizedAbsolutePath(f, host.getCurrentDirectory()), getCanonicalFileName)); + const optionMap = serializeCompilerOptions(configParseResult.options, { + configFilePath: getNormalizedAbsolutePath(configFileName, host.getCurrentDirectory()), + useCaseSensitiveFileNames: host.useCaseSensitiveFileNames + }); const watchOptionMap = configParseResult.watchOptions && serializeWatchOptions(configParseResult.watchOptions); const config = { compilerOptions: { @@ -36610,44 +35024,47 @@ ${lanes.join("\n")} version: void 0 }, watchOptions: watchOptionMap && optionMapToObject(watchOptionMap), - references: map(configParseResult.projectReferences, (r) => ({ ...r, path: r.originalPath ? r.originalPath : "", originalPath: void 0 })), + references: map(configParseResult.projectReferences, r => ({ + ...r, + path: r.originalPath ? r.originalPath : "", + originalPath: void 0 + })), files: length(files) ? files : void 0, - ...((_c = configParseResult.options.configFile) == null ? void 0 : _c.configFileSpecs) ? { + ...(((_c = configParseResult.options.configFile) == null ? void 0 : _c.configFileSpecs) ? { include: filterSameAsDefaultInclude(configParseResult.options.configFile.configFileSpecs.validatedIncludeSpecs), exclude: configParseResult.options.configFile.configFileSpecs.validatedExcludeSpecs - } : {}, + } : {}), compileOnSave: !!configParseResult.compileOnSave ? true : void 0 }; return config; } function optionMapToObject(optionMap) { return { - ...arrayFrom(optionMap.entries()).reduce((prev, cur) => ({ ...prev, [cur[0]]: cur[1] }), {}) + ...arrayFrom(optionMap.entries()).reduce((prev, cur) => ({ + ...prev, + [cur[0]]: cur[1] + }), {}) }; } 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); if (includeRe) { if (excludeRe) { - return (path2) => !(includeRe.test(path2) && !excludeRe.test(path2)); + return path2 => !(includeRe.test(path2) && !excludeRe.test(path2)); } - return (path2) => !includeRe.test(path2); + return path2 => !includeRe.test(path2); } if (excludeRe) { - return (path2) => excludeRe.test(path2); + return path2 => excludeRe.test(path2); } return returnTrue; } @@ -36678,8 +35095,10 @@ ${lanes.join("\n")} function serializeWatchOptions(options) { return serializeOptionBaseObject(options, getWatchOptionsNameMap()); } - function serializeOptionBaseObject(options, { optionsNameMap }, pathOptions) { - const result = /* @__PURE__ */ new Map(); + function serializeOptionBaseObject(options, { + optionsNameMap + }, pathOptions) { + const result = /* @__PURE__ */new Map(); const getCanonicalFileName = pathOptions && createGetCanonicalFileName(pathOptions.useCaseSensitiveFileNames); for (const name in options) { if (hasProperty(options, name)) { @@ -36699,7 +35118,7 @@ ${lanes.join("\n")} } } else { if (optionDefinition.type === "list") { - result.set(name, value.map((element) => getNameOfCompilerOptionValue(element, customTypeMap))); + result.set(name, value.map(element => getNameOfCompilerOptionValue(element, customTypeMap))); } else { result.set(name, getNameOfCompilerOptionValue(value, customTypeMap)); } @@ -36718,7 +35137,7 @@ ${lanes.join("\n")} function getOverwrittenDefaultOptions() { const result = []; const tab = makePadding(2); - commandOptionsWithoutBuild.forEach((cmd) => { + commandOptionsWithoutBuild.forEach(cmd => { if (!compilerOptionsMap.has(cmd.name)) { return; } @@ -36743,12 +35162,16 @@ ${lanes.join("\n")} function makePadding(paddingLength) { return Array(paddingLength + 1).join(" "); } - function isAllowedOptionForOutput({ category, name, isCommandLineOnly }) { + function isAllowedOptionForOutput({ + category, + name, + isCommandLineOnly + }) { const categoriesToSkip = [Diagnostics.Command_line_Options, Diagnostics.Editor_Support, Diagnostics.Compiler_Diagnostics, Diagnostics.Backwards_Compatibility, Diagnostics.Watch_and_Build_Modes, Diagnostics.Output_Formatting]; return !isCommandLineOnly && category !== void 0 && (!categoriesToSkip.includes(category) || compilerOptionsMap.has(name)); } function writeConfigurations() { - const categorizedOptions = /* @__PURE__ */ new Map(); + const categorizedOptions = /* @__PURE__ */new Map(); categorizedOptions.set(Diagnostics.Projects, []); categorizedOptions.set(Diagnostics.Language_and_Environment, []); categorizedOptions.set(Diagnostics.Modules, []); @@ -36760,8 +35183,7 @@ ${lanes.join("\n")} 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); } } @@ -36770,9 +35192,13 @@ ${lanes.join("\n")} const entries = []; categorizedOptions.forEach((options2, category) => { if (entries.length !== 0) { - entries.push({ value: "" }); + entries.push({ + value: "" + }); } - entries.push({ value: `/* ${getLocaleSpecificMessage(category)} */` }); + entries.push({ + value: `/* ${getLocaleSpecificMessage(category)} */` + }); for (const option of options2) { let optionName; if (compilerOptionsMap.has(option.name)) { @@ -36794,7 +35220,10 @@ ${lanes.join("\n")} result.push(`${tab}${tab}/* ${getLocaleSpecificMessage(Diagnostics.Visit_https_Colon_Slash_Slashaka_ms_Slashtsconfig_to_read_more_about_this_file)} */`); result.push(""); for (const entry of entries) { - const { value, description: description3 = "" } = entry; + const { + value, + description: description3 = "" + } = entry; result.push(value && `${tab}${tab}${value}${description3 && makePadding(marginLength - value.length + 2) + description3}`); } if (fileNames.length) { @@ -36816,11 +35245,7 @@ ${lanes.join("\n")} const optionsNameMap = getOptionsNameMap().optionsNameMap; for (const name in options) { if (hasProperty(options, name)) { - result[name] = convertToOptionValueWithAbsolutePaths( - optionsNameMap.get(name.toLowerCase()), - options[name], - toAbsolutePath - ); + result[name] = convertToOptionValueWithAbsolutePaths(optionsNameMap.get(name.toLowerCase()), options[name], toAbsolutePath); } } if (result.configFilePath) { @@ -36843,42 +35268,26 @@ ${lanes.join("\n")} return value; } function parseJsonConfigFileContent(json, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions, extendedConfigCache, existingWatchOptions) { - return parseJsonConfigFileContentWorker( - json, - /*sourceFile*/ - void 0, - host, - basePath, - existingOptions, - existingWatchOptions, - configFileName, - resolutionStack, - extraFileExtensions, - extendedConfigCache - ); + return parseJsonConfigFileContentWorker(json, /*sourceFile*/ + void 0, host, basePath, existingOptions, existingWatchOptions, configFileName, resolutionStack, extraFileExtensions, extendedConfigCache); } function parseJsonSourceFileConfigFileContent(sourceFile, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions, extendedConfigCache, existingWatchOptions) { var _a, _b; - (_a = tracing) == null ? void 0 : _a.push(tracing.Phase.Parse, "parseJsonSourceFileConfigFileContent", { path: sourceFile.fileName }); - const result = parseJsonConfigFileContentWorker( - /*json*/ - void 0, - sourceFile, - host, - basePath, - existingOptions, - existingWatchOptions, - configFileName, - resolutionStack, - extraFileExtensions, - extendedConfigCache - ); + (_a = tracing) == null ? void 0 : _a.push(tracing.Phase.Parse, "parseJsonSourceFileConfigFileContent", { + path: sourceFile.fileName + }); + const result = parseJsonConfigFileContentWorker( /*json*/ + void 0, sourceFile, host, basePath, existingOptions, existingWatchOptions, configFileName, resolutionStack, extraFileExtensions, extendedConfigCache); (_b = tracing) == null ? void 0 : _b.pop(); return result; } function setConfigFileInOptions(options, configFile) { if (configFile) { - Object.defineProperty(options, "configFile", { enumerable: false, writable: false, value: configFile }); + Object.defineProperty(options, "configFile", { + enumerable: false, + writable: false, + value: configFile + }); } } function isNullOrUndefined(x) { @@ -36891,13 +35300,14 @@ ${lanes.join("\n")} Debug.assert(json === void 0 && sourceFile !== void 0 || json !== void 0 && sourceFile === void 0); const errors = []; const parsedConfig = parseConfig(json, sourceFile, host, basePath, configFileName, resolutionStack, errors, extendedConfigCache); - const { raw } = parsedConfig; + const { + raw + } = parsedConfig; const options = extend(existingOptions, parsedConfig.options || {}); const watchOptions = existingWatchOptions && parsedConfig.watchOptions ? extend(existingWatchOptions, parsedConfig.watchOptions) : parsedConfig.watchOptions || existingWatchOptions; options.configFilePath = configFileName && normalizeSlashes(configFileName); const configFileSpecs = getConfigFileSpecs(); - if (sourceFile) - sourceFile.configFileSpecs = configFileSpecs; + if (sourceFile) sourceFile.configFileSpecs = configFileSpecs; setConfigFileInOptions(options, sourceFile); const basePathForFileNames = normalizePath(configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath); return { @@ -36916,7 +35326,7 @@ ${lanes.join("\n")} compileOnSave: !!raw.compileOnSave }; function getConfigFileSpecs() { - const referencesOfRaw = getPropFromRaw("references", (element) => typeof element === "object", "object"); + const referencesOfRaw = getPropFromRaw("references", element => typeof element === "object", "object"); const filesSpecs = toPropValue(getSpecsFromRaw("files")); if (filesSpecs) { const hasZeroOrNoReferences = referencesOfRaw === "no-prop" || isArray(referencesOfRaw) && referencesOfRaw.length === 0; @@ -36925,7 +35335,7 @@ ${lanes.join("\n")} if (sourceFile) { const fileName = configFileName || "tsconfig.json"; const diagnosticMessage = Diagnostics.The_files_list_in_config_file_0_is_empty; - const nodeValue = forEachTsConfigPropArray(sourceFile, "files", (property) => property.initializer); + const nodeValue = forEachTsConfigPropArray(sourceFile, "files", property => property.initializer); const error2 = createDiagnosticForNodeInSourceFileOrCompilerDiagnostic(sourceFile, nodeValue, diagnosticMessage, fileName); errors.push(error2); } else { @@ -36941,7 +35351,7 @@ ${lanes.join("\n")} const outDir = raw.compilerOptions.outDir; const declarationDir = raw.compilerOptions.declarationDir; if (outDir || declarationDir) { - excludeSpecs = [outDir, declarationDir].filter((d) => !!d); + excludeSpecs = [outDir, declarationDir].filter(d => !!d); } } if (filesSpecs === void 0 && includeSpecs === void 0) { @@ -36950,24 +35360,12 @@ ${lanes.join("\n")} } let validatedIncludeSpecs, validatedExcludeSpecs; if (includeSpecs) { - validatedIncludeSpecs = validateSpecs( - includeSpecs, - errors, - /*disallowTrailingRecursion*/ - true, - sourceFile, - "include" - ); + validatedIncludeSpecs = validateSpecs(includeSpecs, errors, /*disallowTrailingRecursion*/ + true, sourceFile, "include"); } if (excludeSpecs) { - validatedExcludeSpecs = validateSpecs( - excludeSpecs, - errors, - /*disallowTrailingRecursion*/ - false, - sourceFile, - "exclude" - ); + validatedExcludeSpecs = validateSpecs(excludeSpecs, errors, /*disallowTrailingRecursion*/ + false, sourceFile, "exclude"); } return { filesSpecs, @@ -36990,7 +35388,7 @@ ${lanes.join("\n")} } function getProjectReferences(basePath2) { let projectReferences; - const referencesOfRaw = getPropFromRaw("references", (element) => typeof element === "object", "object"); + const referencesOfRaw = getPropFromRaw("references", element => typeof element === "object", "object"); if (isArray(referencesOfRaw)) { for (const ref of referencesOfRaw) { if (typeof ref.path !== "string") { @@ -37037,13 +35435,11 @@ ${lanes.join("\n")} function isErrorNoInputFiles(error2) { return error2.code === Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2.code; } - function getErrorForNoInputFiles({ includeSpecs, excludeSpecs }, configFileName) { - return createCompilerDiagnostic( - Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2, - configFileName || "tsconfig.json", - JSON.stringify(includeSpecs || []), - JSON.stringify(excludeSpecs || []) - ); + function getErrorForNoInputFiles({ + includeSpecs, + excludeSpecs + }, configFileName) { + return createCompilerDiagnostic(Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2, configFileName || "tsconfig.json", JSON.stringify(includeSpecs || []), JSON.stringify(excludeSpecs || [])); } function shouldReportNoInputFiles(fileNames, canJsonReportNoInutFiles, resolutionStack) { return fileNames.length === 0 && canJsonReportNoInutFiles && (!resolutionStack || resolutionStack.length === 0); @@ -37056,7 +35452,7 @@ ${lanes.join("\n")} if (shouldReportNoInputFiles(fileNames, canJsonReportNoInutFiles)) { configParseDiagnostics.push(getErrorForNoInputFiles(configFileSpecs, configFileName)); } else { - filterMutate(configParseDiagnostics, (error2) => !isErrorNoInputFiles(error2)); + filterMutate(configParseDiagnostics, error2 => !isErrorNoInputFiles(error2)); } return existingErrors !== configParseDiagnostics.length; } @@ -37069,7 +35465,9 @@ ${lanes.join("\n")} const resolvedPath = getNormalizedAbsolutePath(configFileName || "", basePath); if (resolutionStack.includes(resolvedPath)) { errors.push(createCompilerDiagnostic(Diagnostics.Circularity_detected_while_resolving_configuration_Colon_0, [...resolutionStack, resolvedPath].join(" -> "))); - return { raw: json || convertToObject(sourceFile, errors) }; + return { + raw: json || convertToObject(sourceFile, errors) + }; } const ownConfig = json ? parseOwnConfigOfJson(json, host, basePath, configFileName, errors) : parseOwnConfigOfJsonSourceFile(sourceFile, host, basePath, configFileName, errors); if ((_a = ownConfig.options) == null ? void 0 : _a.paths) { @@ -37077,22 +35475,19 @@ ${lanes.join("\n")} } if (ownConfig.extendedConfigPath) { resolutionStack = resolutionStack.concat([resolvedPath]); - const result = { options: {} }; + const result = { + options: {} + }; if (isString(ownConfig.extendedConfigPath)) { applyExtendedConfig(result, ownConfig.extendedConfigPath); } else { - ownConfig.extendedConfigPath.forEach((extendedConfigPath) => applyExtendedConfig(result, extendedConfigPath)); + ownConfig.extendedConfigPath.forEach(extendedConfigPath => applyExtendedConfig(result, extendedConfigPath)); } - if (!ownConfig.raw.include && result.include) - ownConfig.raw.include = result.include; - if (!ownConfig.raw.exclude && result.exclude) - ownConfig.raw.exclude = result.exclude; - if (!ownConfig.raw.files && 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 (!ownConfig.raw.include && result.include) ownConfig.raw.include = result.include; + if (!ownConfig.raw.exclude && result.exclude) ownConfig.raw.exclude = result.exclude; + if (!ownConfig.raw.files && 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; } @@ -37102,12 +35497,9 @@ ${lanes.join("\n")} if (extendedConfig && isSuccessfulParsedTsconfig(extendedConfig)) { const extendsRaw = extendedConfig.raw; let relativeDifference; - const setPropertyInResultIfNotUndefined = (propertyName) => { + const setPropertyInResultIfNotUndefined = propertyName => { if (extendsRaw[propertyName]) { - result[propertyName] = map(extendsRaw[propertyName], (path) => isRootedDiskPath(path) ? path : combinePaths( - relativeDifference || (relativeDifference = convertToRelativePath(getDirectoryPath(extendedConfigPath), basePath, createGetCanonicalFileName(host.useCaseSensitiveFileNames))), - path - )); + result[propertyName] = map(extendsRaw[propertyName], path => isRootedDiskPath(path) ? path : combinePaths(relativeDifference || (relativeDifference = convertToRelativePath(getDirectoryPath(extendedConfigPath), basePath, createGetCanonicalFileName(host.useCaseSensitiveFileNames))), path)); } }; setPropertyInResultIfNotUndefined("include"); @@ -37130,36 +35522,25 @@ ${lanes.join("\n")} const watchOptions = convertWatchOptionsFromJsonWorker(json.watchOptions, basePath, errors); json.compileOnSave = convertCompileOnSaveOptionFromJson(json, basePath, errors); const extendedConfigPath = json.extends || json.extends === "" ? getExtendsConfigPathOrArray(json.extends, host, basePath, configFileName, errors) : void 0; - return { raw: json, options, watchOptions, typeAcquisition, extendedConfigPath }; + return { + raw: json, + options, + watchOptions, + typeAcquisition, + extendedConfigPath + }; } function getExtendsConfigPathOrArray(value, host, basePath, configFileName, errors, propertyAssignment, valueExpression, sourceFile) { let extendedConfigPath; const newBase = configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath; if (isString(value)) { - extendedConfigPath = getExtendsConfigPath( - value, - host, - newBase, - errors, - valueExpression, - sourceFile - ); + extendedConfigPath = getExtendsConfigPath(value, host, newBase, errors, valueExpression, sourceFile); } else if (isArray(value)) { extendedConfigPath = []; for (let index = 0; index < value.length; index++) { const fileName = value[index]; if (isString(fileName)) { - extendedConfigPath = append( - extendedConfigPath, - getExtendsConfigPath( - fileName, - host, - newBase, - errors, - valueExpression == null ? void 0 : valueExpression.elements[index], - sourceFile - ) - ); + extendedConfigPath = append(extendedConfigPath, getExtendsConfigPath(fileName, host, newBase, errors, valueExpression == null ? void 0 : valueExpression.elements[index], sourceFile)); } else { convertJsonOption(extendsOptionDeclaration.element, value, basePath, errors, propertyAssignment, valueExpression == null ? void 0 : valueExpression.elements[index], sourceFile); } @@ -37176,43 +35557,35 @@ ${lanes.join("\n")} let extendedConfigPath; let rootCompilerOptions; const rootOptions = getTsconfigRootOptionsMap(); - const json = convertConfigFileToObject( - sourceFile, - errors, - { rootOptions, onPropertySet } - ); + const json = convertConfigFileToObject(sourceFile, errors, { + rootOptions, + onPropertySet + }); if (!typeAcquisition) { typeAcquisition = getDefaultTypeAcquisition(configFileName); } if (rootCompilerOptions && json && json.compilerOptions === void 0) { errors.push(createDiagnosticForNodeInSourceFile(sourceFile, rootCompilerOptions[0], Diagnostics._0_should_be_set_inside_the_compilerOptions_object_of_the_config_json_file, getTextOfPropertyName(rootCompilerOptions[0]))); } - return { raw: json, options, watchOptions, typeAcquisition, extendedConfigPath }; + 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) { + var _watchOptions, _typeAcquisition; 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) !== null && _watchOptions !== void 0 ? _watchOptions : watchOptions = {};else if (parentOption === typeAcquisitionDeclaration) currentOption = (_typeAcquisition = typeAcquisition) !== null && _typeAcquisition !== void 0 ? _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) { - errors.push(createUnknownOptionError( - keyText, - parentOption.extraKeyDiagnostics, - /*unknownOptionErrorText*/ - void 0, - propertyAssignment.name, - sourceFile - )); + errors.push(createUnknownOptionError(keyText, parentOption.extraKeyDiagnostics, /*unknownOptionErrorText*/ + void 0, propertyAssignment.name, sourceFile)); } else { errors.push(createDiagnosticForNodeInSourceFile(sourceFile, propertyAssignment.name, parentOption.extraKeyDiagnostics.unknownOptionDiagnostic, keyText)); } @@ -37224,7 +35597,7 @@ ${lanes.join("\n")} if (keyText === "excludes") { errors.push(createDiagnosticForNodeInSourceFile(sourceFile, propertyAssignment.name, Diagnostics.Unknown_option_excludes_Did_you_mean_exclude)); } - if (find(commandOptionsWithoutBuild, (opt) => opt.name === keyText)) { + if (find(commandOptionsWithoutBuild, opt => opt.name === keyText)) { rootCompilerOptions = append(rootCompilerOptions, propertyAssignment.name); } } @@ -37261,28 +35634,26 @@ ${lanes.join("\n")} let extendedResult; let extendedConfig; if (extendedConfigCache && (value = extendedConfigCache.get(path))) { - ({ extendedResult, extendedConfig } = value); + ({ + extendedResult, + extendedConfig + } = value); } else { - extendedResult = readJsonConfigFile(extendedConfigPath, (path2) => host.readFile(path2)); + extendedResult = readJsonConfigFile(extendedConfigPath, path2 => host.readFile(path2)); if (!extendedResult.parseDiagnostics.length) { - extendedConfig = parseConfig( - /*json*/ - void 0, - extendedResult, - host, - getDirectoryPath(extendedConfigPath), - getBaseFileName(extendedConfigPath), - resolutionStack, - errors, - extendedConfigCache - ); + extendedConfig = parseConfig( /*json*/ + void 0, extendedResult, host, getDirectoryPath(extendedConfigPath), getBaseFileName(extendedConfigPath), resolutionStack, errors, extendedConfigCache); } if (extendedConfigCache) { - extendedConfigCache.set(path, { extendedResult, extendedConfig }); + extendedConfigCache.set(path, { + extendedResult, + extendedConfig + }); } } if (sourceFile) { - (result.extendedSourceFiles ?? (result.extendedSourceFiles = /* @__PURE__ */ new Set())).add(extendedResult.fileName); + var _result$extendedSourc; + ((_result$extendedSourc = result.extendedSourceFiles) !== null && _result$extendedSourc !== void 0 ? _result$extendedSourc : result.extendedSourceFiles = /* @__PURE__ */new Set()).add(extendedResult.fileName); if (extendedResult.extendedSourceFiles) { for (const extenedSourceFile of extendedResult.extendedSourceFiles) { result.extendedSourceFiles.add(extenedSourceFile); @@ -37305,15 +35676,27 @@ ${lanes.join("\n")} function convertCompilerOptionsFromJson(jsonOptions, basePath, configFileName) { const errors = []; const options = convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName); - return { options, errors }; + return { + options, + errors + }; } function convertTypeAcquisitionFromJson(jsonOptions, basePath, configFileName) { const errors = []; const options = convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName); - return { options, errors }; + return { + options, + errors + }; } function getDefaultCompilerOptions(configFileName) { - const options = configFileName && getBaseFileName(configFileName) === "jsconfig.json" ? { allowJs: true, maxNodeModuleJsDepth: 2, allowSyntheticDefaultImports: true, skipLibCheck: true, noEmit: true } : {}; + const options = configFileName && getBaseFileName(configFileName) === "jsconfig.json" ? { + allowJs: true, + maxNodeModuleJsDepth: 2, + allowSyntheticDefaultImports: true, + skipLibCheck: true, + noEmit: true + } : {}; return options; } function convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName) { @@ -37325,7 +35708,11 @@ ${lanes.join("\n")} return options; } function getDefaultTypeAcquisition(configFileName) { - return { enable: !!configFileName && getBaseFileName(configFileName) === "jsconfig.json", include: [], exclude: [] }; + return { + enable: !!configFileName && getBaseFileName(configFileName) === "jsconfig.json", + include: [], + exclude: [] + }; } function convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName) { const options = getDefaultTypeAcquisition(configFileName); @@ -37333,15 +35720,8 @@ ${lanes.join("\n")} return options; } function convertWatchOptionsFromJsonWorker(jsonOptions, basePath, errors) { - return convertOptionsFromJson( - getCommandLineWatchOptionsMap(), - jsonOptions, - basePath, - /*defaultOptions*/ - void 0, - watchOptionsDidYouMeanDiagnostics, - errors - ); + return convertOptionsFromJson(getCommandLineWatchOptionsMap(), jsonOptions, basePath, /*defaultOptions*/ + void 0, watchOptionsDidYouMeanDiagnostics, errors); } function convertOptionsFromJson(optionsNameMap, jsonOptions, basePath, defaultOptions, diagnostics, errors) { if (!jsonOptions) { @@ -37391,17 +35771,14 @@ ${lanes.join("\n")} } 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) { @@ -37411,15 +35788,19 @@ ${lanes.join("\n")} } } function convertJsonOptionOfListType(option, values, basePath, errors, propertyAssignment, valueExpression, sourceFile) { - return filter(map(values, (v, index) => convertJsonOption(option.element, v, basePath, errors, propertyAssignment, valueExpression == null ? void 0 : valueExpression.elements[index], sourceFile)), (v) => option.listPreserveFalsyValues ? true : !!v); + return filter(map(values, (v, index) => convertJsonOption(option.element, v, basePath, errors, propertyAssignment, valueExpression == null ? void 0 : valueExpression.elements[index], sourceFile)), v => option.listPreserveFalsyValues ? true : !!v); } function getFileNamesFromConfigSpecs(configFileSpecs, basePath, options, host, extraFileExtensions = emptyArray) { basePath = normalizePath(basePath); const keyMapper = createGetCanonicalFileName(host.useCaseSensitiveFileNames); - const literalFileMap = /* @__PURE__ */ new Map(); - const wildcardFileMap = /* @__PURE__ */ new Map(); - const wildCardJsonFileMap = /* @__PURE__ */ new Map(); - const { validatedFilesSpec, validatedIncludeSpecs, validatedExcludeSpecs } = configFileSpecs; + const literalFileMap = /* @__PURE__ */new Map(); + const wildcardFileMap = /* @__PURE__ */new Map(); + const wildCardJsonFileMap = /* @__PURE__ */new Map(); + const { + validatedFilesSpec, + validatedIncludeSpecs, + validatedExcludeSpecs + } = configFileSpecs; const supportedExtensions = getSupportedExtensions(options, extraFileExtensions); const supportedExtensionsWithJsonIfResolveJsonModule = getSupportedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions); if (validatedFilesSpec) { @@ -37430,21 +35811,15 @@ ${lanes.join("\n")} } let jsonOnlyIncludeRegexes; if (validatedIncludeSpecs && validatedIncludeSpecs.length > 0) { - for (const file of host.readDirectory( - basePath, - flatten(supportedExtensionsWithJsonIfResolveJsonModule), - validatedExcludeSpecs, - validatedIncludeSpecs, - /*depth*/ - void 0 - )) { + for (const file of host.readDirectory(basePath, flatten(supportedExtensionsWithJsonIfResolveJsonModule), validatedExcludeSpecs, validatedIncludeSpecs, /*depth*/ + void 0)) { if (fileExtensionIs(file, ".json" /* Json */)) { if (!jsonOnlyIncludeRegexes) { - const includes = validatedIncludeSpecs.filter((s) => endsWith(s, ".json" /* Json */)); - const includeFilePatterns = map(getRegularExpressionsForWildcards(includes, basePath, "files"), (pattern) => `^${pattern}$`); - jsonOnlyIncludeRegexes = includeFilePatterns ? includeFilePatterns.map((pattern) => getRegexFromPattern(pattern, host.useCaseSensitiveFileNames)) : emptyArray; + const includes = validatedIncludeSpecs.filter(s => endsWith(s, ".json" /* Json */)); + const includeFilePatterns = map(getRegularExpressionsForWildcards(includes, basePath, "files"), pattern => `^${pattern}$`); + jsonOnlyIncludeRegexes = includeFilePatterns ? includeFilePatterns.map(pattern => getRegexFromPattern(pattern, host.useCaseSensitiveFileNames)) : emptyArray; } - const includeIndex = findIndex(jsonOnlyIncludeRegexes, (re) => re.test(file)); + const includeIndex = findIndex(jsonOnlyIncludeRegexes, re => re.test(file)); if (includeIndex !== -1) { const key2 = keyMapper(file); if (!literalFileMap.has(key2) && !wildCardJsonFileMap.has(key2)) { @@ -37468,15 +35843,17 @@ ${lanes.join("\n")} return literalFiles.concat(wildcardFiles, arrayFrom(wildCardJsonFileMap.values())); } function isExcludedFile(pathToCheck, spec, basePath, useCaseSensitiveFileNames2, currentDirectory) { - const { validatedFilesSpec, validatedIncludeSpecs, validatedExcludeSpecs } = spec; - if (!length(validatedIncludeSpecs) || !length(validatedExcludeSpecs)) - return false; + const { + validatedFilesSpec, + validatedIncludeSpecs, + validatedExcludeSpecs + } = spec; + 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); @@ -37490,26 +35867,18 @@ ${lanes.join("\n")} return lastDotIndex > wildcardIndex; } function matchesExclude(pathToCheck, excludeSpecs, useCaseSensitiveFileNames2, currentDirectory) { - return matchesExcludeWorker( - pathToCheck, - filter(excludeSpecs, (spec) => !invalidDotDotAfterRecursiveWildcard(spec)), - useCaseSensitiveFileNames2, - currentDirectory - ); + return matchesExcludeWorker(pathToCheck, filter(excludeSpecs, spec => !invalidDotDotAfterRecursiveWildcard(spec)), useCaseSensitiveFileNames2, currentDirectory); } 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; + return specs.filter(spec => { + if (!isString(spec)) return false; const diag2 = specToDiagnostic(spec, disallowTrailingRecursion); if (diag2 !== void 0) { errors.push(createDiagnostic(...diag2)); @@ -37529,7 +35898,10 @@ ${lanes.join("\n")} return [Diagnostics.File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0, spec]; } } - function getWildcardDirectories({ validatedIncludeSpecs: include, validatedExcludeSpecs: exclude }, path, useCaseSensitiveFileNames2) { + function getWildcardDirectories({ + validatedIncludeSpecs: include, + validatedExcludeSpecs: exclude + }, path, useCaseSensitiveFileNames2) { const rawExcludeRegex = getRegularExpressionForWildcard(exclude, path, "exclude"); const excludeRegex = rawExcludeRegex && new RegExp(rawExcludeRegex, useCaseSensitiveFileNames2 ? "" : "i"); const wildcardDirectories = {}; @@ -37542,7 +35914,10 @@ ${lanes.join("\n")} } const match = getWildcardDirectoryFromSpec(spec, useCaseSensitiveFileNames2); if (match) { - const { key, flags } = match; + const { + key, + flags + } = match; const existingFlags = wildcardDirectories[key]; if (existingFlags === void 0 || existingFlags < flags) { wildcardDirectories[key] = flags; @@ -37575,16 +35950,18 @@ ${lanes.join("\n")} flags: questionWildcardIndex !== -1 && questionWildcardIndex < lastDirectorySeperatorIndex || starWildcardIndex !== -1 && starWildcardIndex < lastDirectorySeperatorIndex ? 1 /* Recursive */ : 0 /* None */ }; } + if (isImplicitGlob(spec.substring(spec.lastIndexOf(directorySeparator) + 1))) { return { key: removeTrailingDirectorySeparator(useCaseSensitiveFileNames2 ? spec : toFileNameLowerCase(spec)), flags: 1 /* Recursive */ }; } + return void 0; } function hasFileWithHigherPriorityExtension(file, literalFiles, wildcardFiles, extensions, keyMapper) { - const extensionGroup = forEach(extensions, (group2) => fileExtensionIsOneOf(file, group2) ? group2 : void 0); + const extensionGroup = forEach(extensions, group2 => fileExtensionIsOneOf(file, group2) ? group2 : void 0); if (!extensionGroup) { return false; } @@ -37603,7 +35980,7 @@ ${lanes.join("\n")} return false; } function removeWildcardFilesWithLowerPriorityExtension(file, wildcardFiles, extensions, keyMapper) { - const extensionGroup = forEach(extensions, (group2) => fileExtensionIsOneOf(file, group2) ? group2 : void 0); + const extensionGroup = forEach(extensions, group2 => fileExtensionIsOneOf(file, group2) ? group2 : void 0); if (!extensionGroup) { return; } @@ -37629,8 +36006,7 @@ ${lanes.join("\n")} return out; } function getOptionValueWithEmptyStrings(value, option) { - if (value === void 0) - return value; + if (value === void 0) return value; switch (option.type) { case "object": return ""; @@ -37641,11 +36017,10 @@ ${lanes.join("\n")} 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)) : ""; + return isArray(value) ? mapDefined(value, v => getOptionValueWithEmptyStrings(v, elementType)) : ""; default: return forEachEntry(option.type, (optionEnumValue, optionStringValue) => { if (optionEnumValue === value) { @@ -37671,8 +36046,7 @@ ${lanes.join("\n")} 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."); } } @@ -37680,6 +36054,7 @@ ${lanes.join("\n")} var init_commandLineParser = __esm({ "src/compiler/commandLineParser.ts"() { "use strict"; + init_ts2(); compileOnSaveCommandLineOption = { name: "compileOnSave", @@ -37693,350 +36068,248 @@ ${lanes.join("\n")} "react-jsx": 4 /* ReactJSX */, "react-jsxdev": 5 /* ReactJSXDev */ })); + inverseJsxOptionMap = new Map(mapIterator(jsxOptionMap.entries(), ([key, value]) => ["" + value, key])); libEntries = [ - // JavaScript only - ["es5", "lib.es5.d.ts"], - ["es6", "lib.es2015.d.ts"], - ["es2015", "lib.es2015.d.ts"], - ["es7", "lib.es2016.d.ts"], - ["es2016", "lib.es2016.d.ts"], - ["es2017", "lib.es2017.d.ts"], - ["es2018", "lib.es2018.d.ts"], - ["es2019", "lib.es2019.d.ts"], - ["es2020", "lib.es2020.d.ts"], - ["es2021", "lib.es2021.d.ts"], - ["es2022", "lib.es2022.d.ts"], - ["es2023", "lib.es2023.d.ts"], - ["esnext", "lib.esnext.d.ts"], - // Host only - ["dom", "lib.dom.d.ts"], - ["dom.iterable", "lib.dom.iterable.d.ts"], - ["webworker", "lib.webworker.d.ts"], - ["webworker.importscripts", "lib.webworker.importscripts.d.ts"], - ["webworker.iterable", "lib.webworker.iterable.d.ts"], - ["scripthost", "lib.scripthost.d.ts"], - // ES2015 Or ESNext By-feature options - ["es2015.core", "lib.es2015.core.d.ts"], - ["es2015.collection", "lib.es2015.collection.d.ts"], - ["es2015.generator", "lib.es2015.generator.d.ts"], - ["es2015.iterable", "lib.es2015.iterable.d.ts"], - ["es2015.promise", "lib.es2015.promise.d.ts"], - ["es2015.proxy", "lib.es2015.proxy.d.ts"], - ["es2015.reflect", "lib.es2015.reflect.d.ts"], - ["es2015.symbol", "lib.es2015.symbol.d.ts"], - ["es2015.symbol.wellknown", "lib.es2015.symbol.wellknown.d.ts"], - ["es2016.array.include", "lib.es2016.array.include.d.ts"], - ["es2017.date", "lib.es2017.date.d.ts"], - ["es2017.object", "lib.es2017.object.d.ts"], - ["es2017.sharedmemory", "lib.es2017.sharedmemory.d.ts"], - ["es2017.string", "lib.es2017.string.d.ts"], - ["es2017.intl", "lib.es2017.intl.d.ts"], - ["es2017.typedarrays", "lib.es2017.typedarrays.d.ts"], - ["es2018.asyncgenerator", "lib.es2018.asyncgenerator.d.ts"], - ["es2018.asynciterable", "lib.es2018.asynciterable.d.ts"], - ["es2018.intl", "lib.es2018.intl.d.ts"], - ["es2018.promise", "lib.es2018.promise.d.ts"], - ["es2018.regexp", "lib.es2018.regexp.d.ts"], - ["es2019.array", "lib.es2019.array.d.ts"], - ["es2019.object", "lib.es2019.object.d.ts"], - ["es2019.string", "lib.es2019.string.d.ts"], - ["es2019.symbol", "lib.es2019.symbol.d.ts"], - ["es2019.intl", "lib.es2019.intl.d.ts"], - ["es2020.bigint", "lib.es2020.bigint.d.ts"], - ["es2020.date", "lib.es2020.date.d.ts"], - ["es2020.promise", "lib.es2020.promise.d.ts"], - ["es2020.sharedmemory", "lib.es2020.sharedmemory.d.ts"], - ["es2020.string", "lib.es2020.string.d.ts"], - ["es2020.symbol.wellknown", "lib.es2020.symbol.wellknown.d.ts"], - ["es2020.intl", "lib.es2020.intl.d.ts"], - ["es2020.number", "lib.es2020.number.d.ts"], - ["es2021.promise", "lib.es2021.promise.d.ts"], - ["es2021.string", "lib.es2021.string.d.ts"], - ["es2021.weakref", "lib.es2021.weakref.d.ts"], - ["es2021.intl", "lib.es2021.intl.d.ts"], - ["es2022.array", "lib.es2022.array.d.ts"], - ["es2022.error", "lib.es2022.error.d.ts"], - ["es2022.intl", "lib.es2022.intl.d.ts"], - ["es2022.object", "lib.es2022.object.d.ts"], - ["es2022.sharedmemory", "lib.es2022.sharedmemory.d.ts"], - ["es2022.string", "lib.es2022.string.d.ts"], - ["es2022.regexp", "lib.es2022.regexp.d.ts"], - ["es2023.array", "lib.es2023.array.d.ts"], - ["es2023.collection", "lib.es2023.collection.d.ts"], - ["esnext.array", "lib.es2023.array.d.ts"], - ["esnext.collection", "lib.es2023.collection.d.ts"], - ["esnext.symbol", "lib.es2019.symbol.d.ts"], - ["esnext.asynciterable", "lib.es2018.asynciterable.d.ts"], - ["esnext.intl", "lib.esnext.intl.d.ts"], - ["esnext.disposable", "lib.esnext.disposable.d.ts"], - ["esnext.bigint", "lib.es2020.bigint.d.ts"], - ["esnext.string", "lib.es2022.string.d.ts"], - ["esnext.promise", "lib.es2021.promise.d.ts"], - ["esnext.weakref", "lib.es2021.weakref.d.ts"], - ["esnext.decorators", "lib.esnext.decorators.d.ts"], - ["decorators", "lib.decorators.d.ts"], - ["decorators.legacy", "lib.decorators.legacy.d.ts"] - ]; - libs = libEntries.map((entry) => entry[0]); + // JavaScript only + ["es5", "lib.es5.d.ts"], ["es6", "lib.es2015.d.ts"], ["es2015", "lib.es2015.d.ts"], ["es7", "lib.es2016.d.ts"], ["es2016", "lib.es2016.d.ts"], ["es2017", "lib.es2017.d.ts"], ["es2018", "lib.es2018.d.ts"], ["es2019", "lib.es2019.d.ts"], ["es2020", "lib.es2020.d.ts"], ["es2021", "lib.es2021.d.ts"], ["es2022", "lib.es2022.d.ts"], ["es2023", "lib.es2023.d.ts"], ["esnext", "lib.esnext.d.ts"], + // Host only + ["dom", "lib.dom.d.ts"], ["dom.iterable", "lib.dom.iterable.d.ts"], ["webworker", "lib.webworker.d.ts"], ["webworker.importscripts", "lib.webworker.importscripts.d.ts"], ["webworker.iterable", "lib.webworker.iterable.d.ts"], ["scripthost", "lib.scripthost.d.ts"], + // ES2015 Or ESNext By-feature options + ["es2015.core", "lib.es2015.core.d.ts"], ["es2015.collection", "lib.es2015.collection.d.ts"], ["es2015.generator", "lib.es2015.generator.d.ts"], ["es2015.iterable", "lib.es2015.iterable.d.ts"], ["es2015.promise", "lib.es2015.promise.d.ts"], ["es2015.proxy", "lib.es2015.proxy.d.ts"], ["es2015.reflect", "lib.es2015.reflect.d.ts"], ["es2015.symbol", "lib.es2015.symbol.d.ts"], ["es2015.symbol.wellknown", "lib.es2015.symbol.wellknown.d.ts"], ["es2016.array.include", "lib.es2016.array.include.d.ts"], ["es2017.date", "lib.es2017.date.d.ts"], ["es2017.object", "lib.es2017.object.d.ts"], ["es2017.sharedmemory", "lib.es2017.sharedmemory.d.ts"], ["es2017.string", "lib.es2017.string.d.ts"], ["es2017.intl", "lib.es2017.intl.d.ts"], ["es2017.typedarrays", "lib.es2017.typedarrays.d.ts"], ["es2018.asyncgenerator", "lib.es2018.asyncgenerator.d.ts"], ["es2018.asynciterable", "lib.es2018.asynciterable.d.ts"], ["es2018.intl", "lib.es2018.intl.d.ts"], ["es2018.promise", "lib.es2018.promise.d.ts"], ["es2018.regexp", "lib.es2018.regexp.d.ts"], ["es2019.array", "lib.es2019.array.d.ts"], ["es2019.object", "lib.es2019.object.d.ts"], ["es2019.string", "lib.es2019.string.d.ts"], ["es2019.symbol", "lib.es2019.symbol.d.ts"], ["es2019.intl", "lib.es2019.intl.d.ts"], ["es2020.bigint", "lib.es2020.bigint.d.ts"], ["es2020.date", "lib.es2020.date.d.ts"], ["es2020.promise", "lib.es2020.promise.d.ts"], ["es2020.sharedmemory", "lib.es2020.sharedmemory.d.ts"], ["es2020.string", "lib.es2020.string.d.ts"], ["es2020.symbol.wellknown", "lib.es2020.symbol.wellknown.d.ts"], ["es2020.intl", "lib.es2020.intl.d.ts"], ["es2020.number", "lib.es2020.number.d.ts"], ["es2021.promise", "lib.es2021.promise.d.ts"], ["es2021.string", "lib.es2021.string.d.ts"], ["es2021.weakref", "lib.es2021.weakref.d.ts"], ["es2021.intl", "lib.es2021.intl.d.ts"], ["es2022.array", "lib.es2022.array.d.ts"], ["es2022.error", "lib.es2022.error.d.ts"], ["es2022.intl", "lib.es2022.intl.d.ts"], ["es2022.object", "lib.es2022.object.d.ts"], ["es2022.sharedmemory", "lib.es2022.sharedmemory.d.ts"], ["es2022.string", "lib.es2022.string.d.ts"], ["es2022.regexp", "lib.es2022.regexp.d.ts"], ["es2023.array", "lib.es2023.array.d.ts"], ["es2023.collection", "lib.es2023.collection.d.ts"], ["esnext.array", "lib.es2023.array.d.ts"], ["esnext.collection", "lib.es2023.collection.d.ts"], ["esnext.symbol", "lib.es2019.symbol.d.ts"], ["esnext.asynciterable", "lib.es2018.asynciterable.d.ts"], ["esnext.intl", "lib.esnext.intl.d.ts"], ["esnext.disposable", "lib.esnext.disposable.d.ts"], ["esnext.bigint", "lib.es2020.bigint.d.ts"], ["esnext.string", "lib.es2022.string.d.ts"], ["esnext.promise", "lib.es2021.promise.d.ts"], ["esnext.weakref", "lib.es2021.weakref.d.ts"], ["esnext.decorators", "lib.esnext.decorators.d.ts"], ["decorators", "lib.decorators.d.ts"], ["decorators.legacy", "lib.decorators.legacy.d.ts"]]; + libs = libEntries.map(entry => entry[0]); libMap = new Map(libEntries); - optionsForWatch = [ - { - name: "watchFile", - type: new Map(Object.entries({ - fixedpollinginterval: 0 /* FixedPollingInterval */, - prioritypollinginterval: 1 /* PriorityPollingInterval */, - dynamicprioritypolling: 2 /* DynamicPriorityPolling */, - fixedchunksizepolling: 3 /* FixedChunkSizePolling */, - usefsevents: 4 /* UseFsEvents */, - usefseventsonparentdirectory: 5 /* UseFsEventsOnParentDirectory */ - })), - category: Diagnostics.Watch_and_Build_Modes, - description: Diagnostics.Specify_how_the_TypeScript_watch_mode_works, - defaultValueDescription: 4 /* UseFsEvents */ - }, - { - name: "watchDirectory", - type: new Map(Object.entries({ - usefsevents: 0 /* UseFsEvents */, - fixedpollinginterval: 1 /* FixedPollingInterval */, - dynamicprioritypolling: 2 /* DynamicPriorityPolling */, - fixedchunksizepolling: 3 /* FixedChunkSizePolling */ - })), - category: Diagnostics.Watch_and_Build_Modes, - description: Diagnostics.Specify_how_directories_are_watched_on_systems_that_lack_recursive_file_watching_functionality, - defaultValueDescription: 0 /* UseFsEvents */ - }, - { - name: "fallbackPolling", - type: new Map(Object.entries({ - fixedinterval: 0 /* FixedInterval */, - priorityinterval: 1 /* PriorityInterval */, - dynamicpriority: 2 /* DynamicPriority */, - fixedchunksize: 3 /* FixedChunkSize */ - })), - category: Diagnostics.Watch_and_Build_Modes, - description: Diagnostics.Specify_what_approach_the_watcher_should_use_if_the_system_runs_out_of_native_file_watchers, - defaultValueDescription: 1 /* PriorityInterval */ - }, - { - name: "synchronousWatchDirectory", - type: "boolean", - category: Diagnostics.Watch_and_Build_Modes, - description: Diagnostics.Synchronously_call_callbacks_and_update_the_state_of_directory_watchers_on_platforms_that_don_t_support_recursive_watching_natively, - defaultValueDescription: false - }, - { - name: "excludeDirectories", - type: "list", - element: { - name: "excludeDirectory", - type: "string", - isFilePath: true, - extraValidation: specToDiagnostic - }, - category: Diagnostics.Watch_and_Build_Modes, - description: Diagnostics.Remove_a_list_of_directories_from_the_watch_process - }, - { - name: "excludeFiles", - type: "list", - element: { - name: "excludeFile", - type: "string", - isFilePath: true, - extraValidation: specToDiagnostic - }, - category: Diagnostics.Watch_and_Build_Modes, - description: Diagnostics.Remove_a_list_of_files_from_the_watch_mode_s_processing - } - ]; - commonOptionsWithBuild = [ - { - name: "help", - shortName: "h", - type: "boolean", - showInSimplifiedHelpView: true, - isCommandLineOnly: true, - category: Diagnostics.Command_line_Options, - description: Diagnostics.Print_this_message, - defaultValueDescription: false - }, - { - name: "help", - shortName: "?", - type: "boolean", - isCommandLineOnly: true, - category: Diagnostics.Command_line_Options, - defaultValueDescription: false - }, - { - name: "watch", - shortName: "w", - type: "boolean", - showInSimplifiedHelpView: true, - isCommandLineOnly: true, - category: Diagnostics.Command_line_Options, - description: Diagnostics.Watch_input_files, - defaultValueDescription: false - }, - { - name: "preserveWatchOutput", - type: "boolean", - showInSimplifiedHelpView: false, - category: Diagnostics.Output_Formatting, - description: Diagnostics.Disable_wiping_the_console_in_watch_mode, - defaultValueDescription: false - }, - { - name: "listFiles", - type: "boolean", - category: Diagnostics.Compiler_Diagnostics, - description: Diagnostics.Print_all_of_the_files_read_during_the_compilation, - defaultValueDescription: false - }, - { - name: "explainFiles", - type: "boolean", - category: Diagnostics.Compiler_Diagnostics, - description: Diagnostics.Print_files_read_during_the_compilation_including_why_it_was_included, - defaultValueDescription: false - }, - { - name: "listEmittedFiles", - type: "boolean", - category: Diagnostics.Compiler_Diagnostics, - description: Diagnostics.Print_the_names_of_emitted_files_after_a_compilation, - defaultValueDescription: false - }, - { - name: "pretty", - type: "boolean", - showInSimplifiedHelpView: true, - category: Diagnostics.Output_Formatting, - description: Diagnostics.Enable_color_and_formatting_in_TypeScript_s_output_to_make_compiler_errors_easier_to_read, - defaultValueDescription: true - }, - { - name: "traceResolution", - type: "boolean", - category: Diagnostics.Compiler_Diagnostics, - description: Diagnostics.Log_paths_used_during_the_moduleResolution_process, - defaultValueDescription: false - }, - { - name: "diagnostics", - type: "boolean", - category: Diagnostics.Compiler_Diagnostics, - description: Diagnostics.Output_compiler_performance_information_after_building, - defaultValueDescription: false - }, - { - name: "extendedDiagnostics", - type: "boolean", - category: Diagnostics.Compiler_Diagnostics, - description: Diagnostics.Output_more_detailed_compiler_performance_information_after_building, - defaultValueDescription: false - }, - { - name: "generateCpuProfile", + optionsForWatch = [{ + name: "watchFile", + type: new Map(Object.entries({ + fixedpollinginterval: 0 /* FixedPollingInterval */, + prioritypollinginterval: 1 /* PriorityPollingInterval */, + dynamicprioritypolling: 2 /* DynamicPriorityPolling */, + fixedchunksizepolling: 3 /* FixedChunkSizePolling */, + usefsevents: 4 /* UseFsEvents */, + usefseventsonparentdirectory: 5 /* UseFsEventsOnParentDirectory */ + })), + + category: Diagnostics.Watch_and_Build_Modes, + description: Diagnostics.Specify_how_the_TypeScript_watch_mode_works, + defaultValueDescription: 4 /* UseFsEvents */ + }, { + name: "watchDirectory", + type: new Map(Object.entries({ + usefsevents: 0 /* UseFsEvents */, + fixedpollinginterval: 1 /* FixedPollingInterval */, + dynamicprioritypolling: 2 /* DynamicPriorityPolling */, + fixedchunksizepolling: 3 /* FixedChunkSizePolling */ + })), + + category: Diagnostics.Watch_and_Build_Modes, + description: Diagnostics.Specify_how_directories_are_watched_on_systems_that_lack_recursive_file_watching_functionality, + defaultValueDescription: 0 /* UseFsEvents */ + }, { + name: "fallbackPolling", + type: new Map(Object.entries({ + fixedinterval: 0 /* FixedInterval */, + priorityinterval: 1 /* PriorityInterval */, + dynamicpriority: 2 /* DynamicPriority */, + fixedchunksize: 3 /* FixedChunkSize */ + })), + + category: Diagnostics.Watch_and_Build_Modes, + description: Diagnostics.Specify_what_approach_the_watcher_should_use_if_the_system_runs_out_of_native_file_watchers, + defaultValueDescription: 1 /* PriorityInterval */ + }, { + name: "synchronousWatchDirectory", + type: "boolean", + category: Diagnostics.Watch_and_Build_Modes, + description: Diagnostics.Synchronously_call_callbacks_and_update_the_state_of_directory_watchers_on_platforms_that_don_t_support_recursive_watching_natively, + defaultValueDescription: false + }, { + name: "excludeDirectories", + type: "list", + element: { + name: "excludeDirectory", type: "string", isFilePath: true, - paramType: Diagnostics.FILE_OR_DIRECTORY, - category: Diagnostics.Compiler_Diagnostics, - description: Diagnostics.Emit_a_v8_CPU_profile_of_the_compiler_run_for_debugging, - defaultValueDescription: "profile.cpuprofile" + extraValidation: specToDiagnostic }, - { - name: "generateTrace", + category: Diagnostics.Watch_and_Build_Modes, + description: Diagnostics.Remove_a_list_of_directories_from_the_watch_process + }, { + name: "excludeFiles", + type: "list", + element: { + name: "excludeFile", type: "string", isFilePath: true, - isCommandLineOnly: true, - paramType: Diagnostics.DIRECTORY, - category: Diagnostics.Compiler_Diagnostics, - description: Diagnostics.Generates_an_event_trace_and_a_list_of_types + extraValidation: specToDiagnostic }, - { - name: "incremental", - shortName: "i", - type: "boolean", - category: Diagnostics.Projects, - description: Diagnostics.Save_tsbuildinfo_files_to_allow_for_incremental_compilation_of_projects, - transpileOptionValue: void 0, - defaultValueDescription: Diagnostics.false_unless_composite_is_set - }, - { - name: "declaration", - shortName: "d", - type: "boolean", - // Not setting affectsEmit because we calculate this flag might not affect full emit - affectsBuildInfo: true, - showInSimplifiedHelpView: true, - category: Diagnostics.Emit, - transpileOptionValue: void 0, - description: Diagnostics.Generate_d_ts_files_from_TypeScript_and_JavaScript_files_in_your_project, - defaultValueDescription: Diagnostics.false_unless_composite_is_set - }, - { - name: "declarationMap", - type: "boolean", - // Not setting affectsEmit because we calculate this flag might not affect full emit - affectsBuildInfo: true, - showInSimplifiedHelpView: true, - category: Diagnostics.Emit, - transpileOptionValue: void 0, - defaultValueDescription: false, - description: Diagnostics.Create_sourcemaps_for_d_ts_files - }, - { - name: "emitDeclarationOnly", - type: "boolean", - // Not setting affectsEmit because we calculate this flag might not affect full emit - affectsBuildInfo: true, - showInSimplifiedHelpView: true, - category: Diagnostics.Emit, - description: Diagnostics.Only_output_d_ts_files_and_not_JavaScript_files, - transpileOptionValue: void 0, - defaultValueDescription: false - }, - { - name: "sourceMap", - type: "boolean", - // Not setting affectsEmit because we calculate this flag might not affect full emit - affectsBuildInfo: true, - showInSimplifiedHelpView: true, - category: Diagnostics.Emit, - defaultValueDescription: false, - description: Diagnostics.Create_source_map_files_for_emitted_JavaScript_files - }, - { - name: "inlineSourceMap", - type: "boolean", - // Not setting affectsEmit because we calculate this flag might not affect full emit - affectsBuildInfo: true, - category: Diagnostics.Emit, - description: Diagnostics.Include_sourcemap_files_inside_the_emitted_JavaScript, - defaultValueDescription: false - }, - { - name: "assumeChangesOnlyAffectDirectDependencies", - type: "boolean", - affectsSemanticDiagnostics: true, - affectsEmit: true, - affectsBuildInfo: true, - category: Diagnostics.Watch_and_Build_Modes, - description: Diagnostics.Have_recompiles_in_projects_that_use_incremental_and_watch_mode_assume_that_changes_within_a_file_will_only_affect_files_directly_depending_on_it, - defaultValueDescription: false - }, - { - name: "locale", - type: "string", - category: Diagnostics.Command_line_Options, - isCommandLineOnly: true, - description: Diagnostics.Set_the_language_of_the_messaging_from_TypeScript_This_does_not_affect_emit, - defaultValueDescription: Diagnostics.Platform_specific - } - ]; + category: Diagnostics.Watch_and_Build_Modes, + description: Diagnostics.Remove_a_list_of_files_from_the_watch_mode_s_processing + }]; + commonOptionsWithBuild = [{ + name: "help", + shortName: "h", + type: "boolean", + showInSimplifiedHelpView: true, + isCommandLineOnly: true, + category: Diagnostics.Command_line_Options, + description: Diagnostics.Print_this_message, + defaultValueDescription: false + }, { + name: "help", + shortName: "?", + type: "boolean", + isCommandLineOnly: true, + category: Diagnostics.Command_line_Options, + defaultValueDescription: false + }, { + name: "watch", + shortName: "w", + type: "boolean", + showInSimplifiedHelpView: true, + isCommandLineOnly: true, + category: Diagnostics.Command_line_Options, + description: Diagnostics.Watch_input_files, + defaultValueDescription: false + }, { + name: "preserveWatchOutput", + type: "boolean", + showInSimplifiedHelpView: false, + category: Diagnostics.Output_Formatting, + description: Diagnostics.Disable_wiping_the_console_in_watch_mode, + defaultValueDescription: false + }, { + name: "listFiles", + type: "boolean", + category: Diagnostics.Compiler_Diagnostics, + description: Diagnostics.Print_all_of_the_files_read_during_the_compilation, + defaultValueDescription: false + }, { + name: "explainFiles", + type: "boolean", + category: Diagnostics.Compiler_Diagnostics, + description: Diagnostics.Print_files_read_during_the_compilation_including_why_it_was_included, + defaultValueDescription: false + }, { + name: "listEmittedFiles", + type: "boolean", + category: Diagnostics.Compiler_Diagnostics, + description: Diagnostics.Print_the_names_of_emitted_files_after_a_compilation, + defaultValueDescription: false + }, { + name: "pretty", + type: "boolean", + showInSimplifiedHelpView: true, + category: Diagnostics.Output_Formatting, + description: Diagnostics.Enable_color_and_formatting_in_TypeScript_s_output_to_make_compiler_errors_easier_to_read, + defaultValueDescription: true + }, { + name: "traceResolution", + type: "boolean", + category: Diagnostics.Compiler_Diagnostics, + description: Diagnostics.Log_paths_used_during_the_moduleResolution_process, + defaultValueDescription: false + }, { + name: "diagnostics", + type: "boolean", + category: Diagnostics.Compiler_Diagnostics, + description: Diagnostics.Output_compiler_performance_information_after_building, + defaultValueDescription: false + }, { + name: "extendedDiagnostics", + type: "boolean", + category: Diagnostics.Compiler_Diagnostics, + description: Diagnostics.Output_more_detailed_compiler_performance_information_after_building, + defaultValueDescription: false + }, { + name: "generateCpuProfile", + type: "string", + isFilePath: true, + paramType: Diagnostics.FILE_OR_DIRECTORY, + category: Diagnostics.Compiler_Diagnostics, + description: Diagnostics.Emit_a_v8_CPU_profile_of_the_compiler_run_for_debugging, + defaultValueDescription: "profile.cpuprofile" + }, { + name: "generateTrace", + type: "string", + isFilePath: true, + isCommandLineOnly: true, + paramType: Diagnostics.DIRECTORY, + category: Diagnostics.Compiler_Diagnostics, + description: Diagnostics.Generates_an_event_trace_and_a_list_of_types + }, { + name: "incremental", + shortName: "i", + type: "boolean", + category: Diagnostics.Projects, + description: Diagnostics.Save_tsbuildinfo_files_to_allow_for_incremental_compilation_of_projects, + transpileOptionValue: void 0, + defaultValueDescription: Diagnostics.false_unless_composite_is_set + }, { + name: "declaration", + shortName: "d", + type: "boolean", + // Not setting affectsEmit because we calculate this flag might not affect full emit + affectsBuildInfo: true, + showInSimplifiedHelpView: true, + category: Diagnostics.Emit, + transpileOptionValue: void 0, + description: Diagnostics.Generate_d_ts_files_from_TypeScript_and_JavaScript_files_in_your_project, + defaultValueDescription: Diagnostics.false_unless_composite_is_set + }, { + name: "declarationMap", + type: "boolean", + // Not setting affectsEmit because we calculate this flag might not affect full emit + affectsBuildInfo: true, + showInSimplifiedHelpView: true, + category: Diagnostics.Emit, + transpileOptionValue: void 0, + defaultValueDescription: false, + description: Diagnostics.Create_sourcemaps_for_d_ts_files + }, { + name: "emitDeclarationOnly", + type: "boolean", + // Not setting affectsEmit because we calculate this flag might not affect full emit + affectsBuildInfo: true, + showInSimplifiedHelpView: true, + category: Diagnostics.Emit, + description: Diagnostics.Only_output_d_ts_files_and_not_JavaScript_files, + transpileOptionValue: void 0, + defaultValueDescription: false + }, { + name: "sourceMap", + type: "boolean", + // Not setting affectsEmit because we calculate this flag might not affect full emit + affectsBuildInfo: true, + showInSimplifiedHelpView: true, + category: Diagnostics.Emit, + defaultValueDescription: false, + description: Diagnostics.Create_source_map_files_for_emitted_JavaScript_files + }, { + name: "inlineSourceMap", + type: "boolean", + // Not setting affectsEmit because we calculate this flag might not affect full emit + affectsBuildInfo: true, + category: Diagnostics.Emit, + description: Diagnostics.Include_sourcemap_files_inside_the_emitted_JavaScript, + defaultValueDescription: false + }, { + name: "assumeChangesOnlyAffectDirectDependencies", + type: "boolean", + affectsSemanticDiagnostics: true, + affectsEmit: true, + affectsBuildInfo: true, + category: Diagnostics.Watch_and_Build_Modes, + description: Diagnostics.Have_recompiles_in_projects_that_use_incremental_and_watch_mode_assume_that_changes_within_a_file_will_only_affect_files_directly_depending_on_it, + defaultValueDescription: false + }, { + name: "locale", + type: "string", + category: Diagnostics.Command_line_Options, + isCommandLineOnly: true, + description: Diagnostics.Set_the_language_of_the_messaging_from_TypeScript_This_does_not_affect_emit, + defaultValueDescription: Diagnostics.Platform_specific + }]; targetOptionDeclaration = { name: "target", shortName: "t", @@ -38054,6 +36327,7 @@ ${lanes.join("\n")} es2022: 9 /* ES2022 */, esnext: 99 /* ESNext */ })), + affectsSourceFile: true, affectsModuleResolution: true, affectsEmit: true, @@ -38064,6 +36338,7 @@ ${lanes.join("\n")} description: Diagnostics.Set_the_JavaScript_language_version_for_emitted_JavaScript_and_include_compatible_library_declarations, defaultValueDescription: 1 /* ES5 */ }; + moduleOptionDeclaration = { name: "module", shortName: "m", @@ -38081,6 +36356,7 @@ ${lanes.join("\n")} node16: 100 /* Node16 */, nodenext: 199 /* NodeNext */ })), + affectsSourceFile: true, affectsModuleResolution: true, affectsEmit: true, @@ -38092,1063 +36368,958 @@ ${lanes.join("\n")} defaultValueDescription: void 0 }; commandOptionsWithoutBuild = [ - // CommandLine only options - { - name: "all", - type: "boolean", - showInSimplifiedHelpView: true, - category: Diagnostics.Command_line_Options, - description: Diagnostics.Show_all_compiler_options, - defaultValueDescription: false - }, - { - name: "version", - shortName: "v", - type: "boolean", - showInSimplifiedHelpView: true, - category: Diagnostics.Command_line_Options, - description: Diagnostics.Print_the_compiler_s_version, - defaultValueDescription: false - }, - { - name: "init", - type: "boolean", - showInSimplifiedHelpView: true, - category: Diagnostics.Command_line_Options, - description: Diagnostics.Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file, - defaultValueDescription: false - }, - { - name: "project", - shortName: "p", - type: "string", - isFilePath: true, - showInSimplifiedHelpView: true, - category: Diagnostics.Command_line_Options, - paramType: Diagnostics.FILE_OR_DIRECTORY, - description: Diagnostics.Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json - }, - { - name: "build", - type: "boolean", - shortName: "b", - showInSimplifiedHelpView: true, - category: Diagnostics.Command_line_Options, - description: Diagnostics.Build_one_or_more_projects_and_their_dependencies_if_out_of_date, - defaultValueDescription: false - }, - { - name: "showConfig", - type: "boolean", - showInSimplifiedHelpView: true, - category: Diagnostics.Command_line_Options, - isCommandLineOnly: true, - description: Diagnostics.Print_the_final_configuration_instead_of_building, - defaultValueDescription: false - }, - { - name: "listFilesOnly", - type: "boolean", - category: Diagnostics.Command_line_Options, - isCommandLineOnly: true, - description: Diagnostics.Print_names_of_files_that_are_part_of_the_compilation_and_then_stop_processing, - defaultValueDescription: false - }, - // Basic - targetOptionDeclaration, - moduleOptionDeclaration, - { + // CommandLine only options + { + name: "all", + type: "boolean", + showInSimplifiedHelpView: true, + category: Diagnostics.Command_line_Options, + description: Diagnostics.Show_all_compiler_options, + defaultValueDescription: false + }, { + name: "version", + shortName: "v", + type: "boolean", + showInSimplifiedHelpView: true, + category: Diagnostics.Command_line_Options, + description: Diagnostics.Print_the_compiler_s_version, + defaultValueDescription: false + }, { + name: "init", + type: "boolean", + showInSimplifiedHelpView: true, + category: Diagnostics.Command_line_Options, + description: Diagnostics.Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file, + defaultValueDescription: false + }, { + name: "project", + shortName: "p", + type: "string", + isFilePath: true, + showInSimplifiedHelpView: true, + category: Diagnostics.Command_line_Options, + paramType: Diagnostics.FILE_OR_DIRECTORY, + description: Diagnostics.Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json + }, { + name: "build", + type: "boolean", + shortName: "b", + showInSimplifiedHelpView: true, + category: Diagnostics.Command_line_Options, + description: Diagnostics.Build_one_or_more_projects_and_their_dependencies_if_out_of_date, + defaultValueDescription: false + }, { + name: "showConfig", + type: "boolean", + showInSimplifiedHelpView: true, + category: Diagnostics.Command_line_Options, + isCommandLineOnly: true, + description: Diagnostics.Print_the_final_configuration_instead_of_building, + defaultValueDescription: false + }, { + name: "listFilesOnly", + type: "boolean", + category: Diagnostics.Command_line_Options, + isCommandLineOnly: true, + description: Diagnostics.Print_names_of_files_that_are_part_of_the_compilation_and_then_stop_processing, + defaultValueDescription: false + }, + // Basic + targetOptionDeclaration, moduleOptionDeclaration, { + name: "lib", + type: "list", + element: { name: "lib", - type: "list", - element: { - name: "lib", - type: libMap, - defaultValueDescription: void 0 - }, - affectsProgramStructure: true, - showInSimplifiedHelpView: true, - category: Diagnostics.Language_and_Environment, - description: Diagnostics.Specify_a_set_of_bundled_library_declaration_files_that_describe_the_target_runtime_environment, - transpileOptionValue: void 0 - }, - { - name: "allowJs", - type: "boolean", - allowJsFlag: true, - affectsBuildInfo: true, - showInSimplifiedHelpView: true, - category: Diagnostics.JavaScript_Support, - description: Diagnostics.Allow_JavaScript_files_to_be_a_part_of_your_program_Use_the_checkJS_option_to_get_errors_from_these_files, - defaultValueDescription: false - }, - { - name: "checkJs", - type: "boolean", - affectsModuleResolution: true, - affectsSemanticDiagnostics: true, - affectsBuildInfo: true, - showInSimplifiedHelpView: true, - category: Diagnostics.JavaScript_Support, - description: Diagnostics.Enable_error_reporting_in_type_checked_JavaScript_files, - defaultValueDescription: false - }, - { - name: "jsx", - type: jsxOptionMap, - affectsSourceFile: true, - affectsEmit: true, - affectsBuildInfo: true, - affectsModuleResolution: true, - // The checker emits an error when it sees JSX but this option is not set in compilerOptions. - // This is effectively a semantic error, so mark this option as affecting semantic diagnostics - // so we know to refresh errors when this option is changed. - affectsSemanticDiagnostics: true, - paramType: Diagnostics.KIND, - showInSimplifiedHelpView: true, - category: Diagnostics.Language_and_Environment, - description: Diagnostics.Specify_what_JSX_code_is_generated, + type: libMap, defaultValueDescription: void 0 }, - { - name: "outFile", - type: "string", - affectsEmit: true, - affectsBuildInfo: true, - affectsDeclarationPath: true, - isFilePath: true, - paramType: Diagnostics.FILE, - showInSimplifiedHelpView: true, - category: Diagnostics.Emit, - description: Diagnostics.Specify_a_file_that_bundles_all_outputs_into_one_JavaScript_file_If_declaration_is_true_also_designates_a_file_that_bundles_all_d_ts_output, - transpileOptionValue: void 0 - }, - { - name: "outDir", - type: "string", - affectsEmit: true, - affectsBuildInfo: true, - affectsDeclarationPath: true, - isFilePath: true, - paramType: Diagnostics.DIRECTORY, - showInSimplifiedHelpView: true, - category: Diagnostics.Emit, - description: Diagnostics.Specify_an_output_folder_for_all_emitted_files - }, - { - name: "rootDir", - type: "string", - affectsEmit: true, - affectsBuildInfo: true, - affectsDeclarationPath: true, - isFilePath: true, - paramType: Diagnostics.LOCATION, - category: Diagnostics.Modules, - description: Diagnostics.Specify_the_root_folder_within_your_source_files, - defaultValueDescription: Diagnostics.Computed_from_the_list_of_input_files - }, - { - name: "composite", - type: "boolean", - // Not setting affectsEmit because we calculate this flag might not affect full emit - affectsBuildInfo: true, - isTSConfigOnly: true, - category: Diagnostics.Projects, - transpileOptionValue: void 0, - defaultValueDescription: false, - description: Diagnostics.Enable_constraints_that_allow_a_TypeScript_project_to_be_used_with_project_references - }, - { - name: "tsBuildInfoFile", - type: "string", - affectsEmit: true, - affectsBuildInfo: true, - isFilePath: true, - paramType: Diagnostics.FILE, - category: Diagnostics.Projects, - transpileOptionValue: void 0, - defaultValueDescription: ".tsbuildinfo", - description: Diagnostics.Specify_the_path_to_tsbuildinfo_incremental_compilation_file - }, - { - name: "removeComments", - type: "boolean", - affectsEmit: true, - affectsBuildInfo: true, - showInSimplifiedHelpView: true, - category: Diagnostics.Emit, - defaultValueDescription: false, - description: Diagnostics.Disable_emitting_comments - }, - { - name: "noEmit", - type: "boolean", - showInSimplifiedHelpView: true, - category: Diagnostics.Emit, - description: Diagnostics.Disable_emitting_files_from_a_compilation, - transpileOptionValue: void 0, - defaultValueDescription: false - }, - { - name: "importHelpers", - type: "boolean", - affectsEmit: true, - affectsBuildInfo: true, - category: Diagnostics.Emit, - description: Diagnostics.Allow_importing_helper_functions_from_tslib_once_per_project_instead_of_including_them_per_file, - defaultValueDescription: false - }, - { - name: "importsNotUsedAsValues", - type: new Map(Object.entries({ - remove: 0 /* Remove */, - preserve: 1 /* Preserve */, - error: 2 /* Error */ - })), - affectsEmit: true, - affectsSemanticDiagnostics: true, - affectsBuildInfo: true, - category: Diagnostics.Emit, - description: Diagnostics.Specify_emit_Slashchecking_behavior_for_imports_that_are_only_used_for_types, - defaultValueDescription: 0 /* Remove */ - }, - { - name: "downlevelIteration", - type: "boolean", - affectsEmit: true, - affectsBuildInfo: true, - category: Diagnostics.Emit, - description: Diagnostics.Emit_more_compliant_but_verbose_and_less_performant_JavaScript_for_iteration, - defaultValueDescription: false - }, - { - name: "isolatedModules", - type: "boolean", - category: Diagnostics.Interop_Constraints, - description: Diagnostics.Ensure_that_each_file_can_be_safely_transpiled_without_relying_on_other_imports, - transpileOptionValue: true, - defaultValueDescription: false - }, - { - name: "verbatimModuleSyntax", - type: "boolean", - category: Diagnostics.Interop_Constraints, - description: Diagnostics.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, - defaultValueDescription: false - }, - // Strict Type Checks - { - name: "strict", - type: "boolean", - // Though this affects semantic diagnostics, affectsSemanticDiagnostics is not set here - // The value of each strictFlag depends on own strictFlag value or this and never accessed directly. - // But we need to store `strict` in builf info, even though it won't be examined directly, so that the - // flags it controls (e.g. `strictNullChecks`) will be retrieved correctly - affectsBuildInfo: true, - showInSimplifiedHelpView: true, - category: Diagnostics.Type_Checking, - description: Diagnostics.Enable_all_strict_type_checking_options, - defaultValueDescription: false - }, - { - name: "noImplicitAny", - type: "boolean", - affectsSemanticDiagnostics: true, - affectsBuildInfo: true, - strictFlag: true, - category: Diagnostics.Type_Checking, - description: Diagnostics.Enable_error_reporting_for_expressions_and_declarations_with_an_implied_any_type, - defaultValueDescription: Diagnostics.false_unless_strict_is_set - }, - { - name: "strictNullChecks", - type: "boolean", - affectsSemanticDiagnostics: true, - affectsBuildInfo: true, - strictFlag: true, - category: Diagnostics.Type_Checking, - description: Diagnostics.When_type_checking_take_into_account_null_and_undefined, - defaultValueDescription: Diagnostics.false_unless_strict_is_set - }, - { - name: "strictFunctionTypes", - type: "boolean", - affectsSemanticDiagnostics: true, - affectsBuildInfo: true, - strictFlag: true, - category: Diagnostics.Type_Checking, - description: Diagnostics.When_assigning_functions_check_to_ensure_parameters_and_the_return_values_are_subtype_compatible, - defaultValueDescription: Diagnostics.false_unless_strict_is_set - }, - { - name: "strictBindCallApply", - type: "boolean", - affectsSemanticDiagnostics: true, - affectsBuildInfo: true, - strictFlag: true, - category: Diagnostics.Type_Checking, - description: Diagnostics.Check_that_the_arguments_for_bind_call_and_apply_methods_match_the_original_function, - defaultValueDescription: Diagnostics.false_unless_strict_is_set - }, - { - name: "strictPropertyInitialization", - type: "boolean", - affectsSemanticDiagnostics: true, - affectsBuildInfo: true, - strictFlag: true, - category: Diagnostics.Type_Checking, - description: Diagnostics.Check_for_class_properties_that_are_declared_but_not_set_in_the_constructor, - defaultValueDescription: Diagnostics.false_unless_strict_is_set - }, - { - name: "noImplicitThis", - type: "boolean", - affectsSemanticDiagnostics: true, - affectsBuildInfo: true, - strictFlag: true, - category: Diagnostics.Type_Checking, - description: Diagnostics.Enable_error_reporting_when_this_is_given_the_type_any, - defaultValueDescription: Diagnostics.false_unless_strict_is_set - }, - { - name: "useUnknownInCatchVariables", - type: "boolean", - affectsSemanticDiagnostics: true, - affectsBuildInfo: true, - strictFlag: true, - category: Diagnostics.Type_Checking, - description: Diagnostics.Default_catch_clause_variables_as_unknown_instead_of_any, - defaultValueDescription: Diagnostics.false_unless_strict_is_set - }, - { - name: "alwaysStrict", - type: "boolean", - affectsSourceFile: true, - affectsEmit: true, - affectsBuildInfo: true, - strictFlag: true, - category: Diagnostics.Type_Checking, - description: Diagnostics.Ensure_use_strict_is_always_emitted, - defaultValueDescription: Diagnostics.false_unless_strict_is_set - }, - // Additional Checks - { - name: "noUnusedLocals", - type: "boolean", - affectsSemanticDiagnostics: true, - affectsBuildInfo: true, - category: Diagnostics.Type_Checking, - description: Diagnostics.Enable_error_reporting_when_local_variables_aren_t_read, - defaultValueDescription: false - }, - { - name: "noUnusedParameters", - type: "boolean", - affectsSemanticDiagnostics: true, - affectsBuildInfo: true, - category: Diagnostics.Type_Checking, - description: Diagnostics.Raise_an_error_when_a_function_parameter_isn_t_read, - defaultValueDescription: false - }, - { - name: "exactOptionalPropertyTypes", - type: "boolean", - affectsSemanticDiagnostics: true, - affectsBuildInfo: true, - category: Diagnostics.Type_Checking, - description: Diagnostics.Interpret_optional_property_types_as_written_rather_than_adding_undefined, - defaultValueDescription: false - }, - { - name: "noImplicitReturns", - type: "boolean", - affectsSemanticDiagnostics: true, - affectsBuildInfo: true, - category: Diagnostics.Type_Checking, - description: Diagnostics.Enable_error_reporting_for_codepaths_that_do_not_explicitly_return_in_a_function, - defaultValueDescription: false - }, - { - name: "noFallthroughCasesInSwitch", - type: "boolean", - affectsBindDiagnostics: true, - affectsSemanticDiagnostics: true, - affectsBuildInfo: true, - category: Diagnostics.Type_Checking, - description: Diagnostics.Enable_error_reporting_for_fallthrough_cases_in_switch_statements, - defaultValueDescription: false - }, - { - name: "noUncheckedIndexedAccess", - type: "boolean", - affectsSemanticDiagnostics: true, - affectsBuildInfo: true, - category: Diagnostics.Type_Checking, - description: Diagnostics.Add_undefined_to_a_type_when_accessed_using_an_index, - defaultValueDescription: false - }, - { - name: "noImplicitOverride", - type: "boolean", - affectsSemanticDiagnostics: true, - affectsBuildInfo: true, - category: Diagnostics.Type_Checking, - description: Diagnostics.Ensure_overriding_members_in_derived_classes_are_marked_with_an_override_modifier, - defaultValueDescription: false - }, - { - name: "noPropertyAccessFromIndexSignature", - type: "boolean", - affectsSemanticDiagnostics: true, - affectsBuildInfo: true, - showInSimplifiedHelpView: false, - category: Diagnostics.Type_Checking, - description: Diagnostics.Enforces_using_indexed_accessors_for_keys_declared_using_an_indexed_type, - defaultValueDescription: false - }, - // Module Resolution - { - name: "moduleResolution", - type: new Map(Object.entries({ - // N.B. The first entry specifies the value shown in `tsc --init` - node10: 2 /* Node10 */, - node: 2 /* Node10 */, - classic: 1 /* Classic */, - node16: 3 /* Node16 */, - nodenext: 99 /* NodeNext */, - bundler: 100 /* Bundler */ - })), - deprecatedKeys: /* @__PURE__ */ new Set(["node"]), - affectsSourceFile: true, - affectsModuleResolution: true, - paramType: Diagnostics.STRATEGY, - category: Diagnostics.Modules, - description: Diagnostics.Specify_how_TypeScript_looks_up_a_file_from_a_given_module_specifier, - defaultValueDescription: Diagnostics.module_AMD_or_UMD_or_System_or_ES6_then_Classic_Otherwise_Node - }, - { - name: "baseUrl", - type: "string", - affectsModuleResolution: true, - isFilePath: true, - category: Diagnostics.Modules, - description: Diagnostics.Specify_the_base_directory_to_resolve_non_relative_module_names - }, - { - // this option can only be specified in tsconfig.json - // use type = object to copy the value as-is - name: "paths", - type: "object", - affectsModuleResolution: true, - isTSConfigOnly: true, - category: Diagnostics.Modules, - description: Diagnostics.Specify_a_set_of_entries_that_re_map_imports_to_additional_lookup_locations, - transpileOptionValue: void 0 - }, - { - // this option can only be specified in tsconfig.json - // use type = object to copy the value as-is + affectsProgramStructure: true, + showInSimplifiedHelpView: true, + category: Diagnostics.Language_and_Environment, + description: Diagnostics.Specify_a_set_of_bundled_library_declaration_files_that_describe_the_target_runtime_environment, + transpileOptionValue: void 0 + }, { + name: "allowJs", + type: "boolean", + allowJsFlag: true, + affectsBuildInfo: true, + showInSimplifiedHelpView: true, + category: Diagnostics.JavaScript_Support, + description: Diagnostics.Allow_JavaScript_files_to_be_a_part_of_your_program_Use_the_checkJS_option_to_get_errors_from_these_files, + defaultValueDescription: false + }, { + name: "checkJs", + type: "boolean", + affectsModuleResolution: true, + affectsSemanticDiagnostics: true, + affectsBuildInfo: true, + showInSimplifiedHelpView: true, + category: Diagnostics.JavaScript_Support, + description: Diagnostics.Enable_error_reporting_in_type_checked_JavaScript_files, + defaultValueDescription: false + }, { + name: "jsx", + type: jsxOptionMap, + affectsSourceFile: true, + affectsEmit: true, + affectsBuildInfo: true, + affectsModuleResolution: true, + // The checker emits an error when it sees JSX but this option is not set in compilerOptions. + // This is effectively a semantic error, so mark this option as affecting semantic diagnostics + // so we know to refresh errors when this option is changed. + affectsSemanticDiagnostics: true, + paramType: Diagnostics.KIND, + showInSimplifiedHelpView: true, + category: Diagnostics.Language_and_Environment, + description: Diagnostics.Specify_what_JSX_code_is_generated, + defaultValueDescription: void 0 + }, { + name: "outFile", + type: "string", + affectsEmit: true, + affectsBuildInfo: true, + affectsDeclarationPath: true, + isFilePath: true, + paramType: Diagnostics.FILE, + showInSimplifiedHelpView: true, + category: Diagnostics.Emit, + description: Diagnostics.Specify_a_file_that_bundles_all_outputs_into_one_JavaScript_file_If_declaration_is_true_also_designates_a_file_that_bundles_all_d_ts_output, + transpileOptionValue: void 0 + }, { + name: "outDir", + type: "string", + affectsEmit: true, + affectsBuildInfo: true, + affectsDeclarationPath: true, + isFilePath: true, + paramType: Diagnostics.DIRECTORY, + showInSimplifiedHelpView: true, + category: Diagnostics.Emit, + description: Diagnostics.Specify_an_output_folder_for_all_emitted_files + }, { + name: "rootDir", + type: "string", + affectsEmit: true, + affectsBuildInfo: true, + affectsDeclarationPath: true, + isFilePath: true, + paramType: Diagnostics.LOCATION, + category: Diagnostics.Modules, + description: Diagnostics.Specify_the_root_folder_within_your_source_files, + defaultValueDescription: Diagnostics.Computed_from_the_list_of_input_files + }, { + name: "composite", + type: "boolean", + // Not setting affectsEmit because we calculate this flag might not affect full emit + affectsBuildInfo: true, + isTSConfigOnly: true, + category: Diagnostics.Projects, + transpileOptionValue: void 0, + defaultValueDescription: false, + description: Diagnostics.Enable_constraints_that_allow_a_TypeScript_project_to_be_used_with_project_references + }, { + name: "tsBuildInfoFile", + type: "string", + affectsEmit: true, + affectsBuildInfo: true, + isFilePath: true, + paramType: Diagnostics.FILE, + category: Diagnostics.Projects, + transpileOptionValue: void 0, + defaultValueDescription: ".tsbuildinfo", + description: Diagnostics.Specify_the_path_to_tsbuildinfo_incremental_compilation_file + }, { + name: "removeComments", + type: "boolean", + affectsEmit: true, + affectsBuildInfo: true, + showInSimplifiedHelpView: true, + category: Diagnostics.Emit, + defaultValueDescription: false, + description: Diagnostics.Disable_emitting_comments + }, { + name: "noEmit", + type: "boolean", + showInSimplifiedHelpView: true, + category: Diagnostics.Emit, + description: Diagnostics.Disable_emitting_files_from_a_compilation, + transpileOptionValue: void 0, + defaultValueDescription: false + }, { + name: "importHelpers", + type: "boolean", + affectsEmit: true, + affectsBuildInfo: true, + category: Diagnostics.Emit, + description: Diagnostics.Allow_importing_helper_functions_from_tslib_once_per_project_instead_of_including_them_per_file, + defaultValueDescription: false + }, { + name: "importsNotUsedAsValues", + type: new Map(Object.entries({ + remove: 0 /* Remove */, + preserve: 1 /* Preserve */, + error: 2 /* Error */ + })), + + affectsEmit: true, + affectsSemanticDiagnostics: true, + affectsBuildInfo: true, + category: Diagnostics.Emit, + description: Diagnostics.Specify_emit_Slashchecking_behavior_for_imports_that_are_only_used_for_types, + defaultValueDescription: 0 /* Remove */ + }, { + name: "downlevelIteration", + type: "boolean", + affectsEmit: true, + affectsBuildInfo: true, + category: Diagnostics.Emit, + description: Diagnostics.Emit_more_compliant_but_verbose_and_less_performant_JavaScript_for_iteration, + defaultValueDescription: false + }, { + name: "isolatedModules", + type: "boolean", + category: Diagnostics.Interop_Constraints, + description: Diagnostics.Ensure_that_each_file_can_be_safely_transpiled_without_relying_on_other_imports, + transpileOptionValue: true, + defaultValueDescription: false + }, { + name: "verbatimModuleSyntax", + type: "boolean", + category: Diagnostics.Interop_Constraints, + description: Diagnostics.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, + defaultValueDescription: false + }, + // Strict Type Checks + { + name: "strict", + type: "boolean", + // Though this affects semantic diagnostics, affectsSemanticDiagnostics is not set here + // The value of each strictFlag depends on own strictFlag value or this and never accessed directly. + // But we need to store `strict` in builf info, even though it won't be examined directly, so that the + // flags it controls (e.g. `strictNullChecks`) will be retrieved correctly + affectsBuildInfo: true, + showInSimplifiedHelpView: true, + category: Diagnostics.Type_Checking, + description: Diagnostics.Enable_all_strict_type_checking_options, + defaultValueDescription: false + }, { + name: "noImplicitAny", + type: "boolean", + affectsSemanticDiagnostics: true, + affectsBuildInfo: true, + strictFlag: true, + category: Diagnostics.Type_Checking, + description: Diagnostics.Enable_error_reporting_for_expressions_and_declarations_with_an_implied_any_type, + defaultValueDescription: Diagnostics.false_unless_strict_is_set + }, { + name: "strictNullChecks", + type: "boolean", + affectsSemanticDiagnostics: true, + affectsBuildInfo: true, + strictFlag: true, + category: Diagnostics.Type_Checking, + description: Diagnostics.When_type_checking_take_into_account_null_and_undefined, + defaultValueDescription: Diagnostics.false_unless_strict_is_set + }, { + name: "strictFunctionTypes", + type: "boolean", + affectsSemanticDiagnostics: true, + affectsBuildInfo: true, + strictFlag: true, + category: Diagnostics.Type_Checking, + description: Diagnostics.When_assigning_functions_check_to_ensure_parameters_and_the_return_values_are_subtype_compatible, + defaultValueDescription: Diagnostics.false_unless_strict_is_set + }, { + name: "strictBindCallApply", + type: "boolean", + affectsSemanticDiagnostics: true, + affectsBuildInfo: true, + strictFlag: true, + category: Diagnostics.Type_Checking, + description: Diagnostics.Check_that_the_arguments_for_bind_call_and_apply_methods_match_the_original_function, + defaultValueDescription: Diagnostics.false_unless_strict_is_set + }, { + name: "strictPropertyInitialization", + type: "boolean", + affectsSemanticDiagnostics: true, + affectsBuildInfo: true, + strictFlag: true, + category: Diagnostics.Type_Checking, + description: Diagnostics.Check_for_class_properties_that_are_declared_but_not_set_in_the_constructor, + defaultValueDescription: Diagnostics.false_unless_strict_is_set + }, { + name: "noImplicitThis", + type: "boolean", + affectsSemanticDiagnostics: true, + affectsBuildInfo: true, + strictFlag: true, + category: Diagnostics.Type_Checking, + description: Diagnostics.Enable_error_reporting_when_this_is_given_the_type_any, + defaultValueDescription: Diagnostics.false_unless_strict_is_set + }, { + name: "useUnknownInCatchVariables", + type: "boolean", + affectsSemanticDiagnostics: true, + affectsBuildInfo: true, + strictFlag: true, + category: Diagnostics.Type_Checking, + description: Diagnostics.Default_catch_clause_variables_as_unknown_instead_of_any, + defaultValueDescription: Diagnostics.false_unless_strict_is_set + }, { + name: "alwaysStrict", + type: "boolean", + affectsSourceFile: true, + affectsEmit: true, + affectsBuildInfo: true, + strictFlag: true, + category: Diagnostics.Type_Checking, + description: Diagnostics.Ensure_use_strict_is_always_emitted, + defaultValueDescription: Diagnostics.false_unless_strict_is_set + }, + // Additional Checks + { + name: "noUnusedLocals", + type: "boolean", + affectsSemanticDiagnostics: true, + affectsBuildInfo: true, + category: Diagnostics.Type_Checking, + description: Diagnostics.Enable_error_reporting_when_local_variables_aren_t_read, + defaultValueDescription: false + }, { + name: "noUnusedParameters", + type: "boolean", + affectsSemanticDiagnostics: true, + affectsBuildInfo: true, + category: Diagnostics.Type_Checking, + description: Diagnostics.Raise_an_error_when_a_function_parameter_isn_t_read, + defaultValueDescription: false + }, { + name: "exactOptionalPropertyTypes", + type: "boolean", + affectsSemanticDiagnostics: true, + affectsBuildInfo: true, + category: Diagnostics.Type_Checking, + description: Diagnostics.Interpret_optional_property_types_as_written_rather_than_adding_undefined, + defaultValueDescription: false + }, { + name: "noImplicitReturns", + type: "boolean", + affectsSemanticDiagnostics: true, + affectsBuildInfo: true, + category: Diagnostics.Type_Checking, + description: Diagnostics.Enable_error_reporting_for_codepaths_that_do_not_explicitly_return_in_a_function, + defaultValueDescription: false + }, { + name: "noFallthroughCasesInSwitch", + type: "boolean", + affectsBindDiagnostics: true, + affectsSemanticDiagnostics: true, + affectsBuildInfo: true, + category: Diagnostics.Type_Checking, + description: Diagnostics.Enable_error_reporting_for_fallthrough_cases_in_switch_statements, + defaultValueDescription: false + }, { + name: "noUncheckedIndexedAccess", + type: "boolean", + affectsSemanticDiagnostics: true, + affectsBuildInfo: true, + category: Diagnostics.Type_Checking, + description: Diagnostics.Add_undefined_to_a_type_when_accessed_using_an_index, + defaultValueDescription: false + }, { + name: "noImplicitOverride", + type: "boolean", + affectsSemanticDiagnostics: true, + affectsBuildInfo: true, + category: Diagnostics.Type_Checking, + description: Diagnostics.Ensure_overriding_members_in_derived_classes_are_marked_with_an_override_modifier, + defaultValueDescription: false + }, { + name: "noPropertyAccessFromIndexSignature", + type: "boolean", + affectsSemanticDiagnostics: true, + affectsBuildInfo: true, + showInSimplifiedHelpView: false, + category: Diagnostics.Type_Checking, + description: Diagnostics.Enforces_using_indexed_accessors_for_keys_declared_using_an_indexed_type, + defaultValueDescription: false + }, + // Module Resolution + { + name: "moduleResolution", + type: new Map(Object.entries({ + // N.B. The first entry specifies the value shown in `tsc --init` + node10: 2 /* Node10 */, + node: 2 /* Node10 */, + classic: 1 /* Classic */, + node16: 3 /* Node16 */, + nodenext: 99 /* NodeNext */, + bundler: 100 /* Bundler */ + })), + + deprecatedKeys: /* @__PURE__ */new Set(["node"]), + affectsSourceFile: true, + affectsModuleResolution: true, + paramType: Diagnostics.STRATEGY, + category: Diagnostics.Modules, + description: Diagnostics.Specify_how_TypeScript_looks_up_a_file_from_a_given_module_specifier, + defaultValueDescription: Diagnostics.module_AMD_or_UMD_or_System_or_ES6_then_Classic_Otherwise_Node + }, { + name: "baseUrl", + type: "string", + affectsModuleResolution: true, + isFilePath: true, + category: Diagnostics.Modules, + description: Diagnostics.Specify_the_base_directory_to_resolve_non_relative_module_names + }, { + // this option can only be specified in tsconfig.json + // use type = object to copy the value as-is + name: "paths", + type: "object", + affectsModuleResolution: true, + isTSConfigOnly: true, + category: Diagnostics.Modules, + description: Diagnostics.Specify_a_set_of_entries_that_re_map_imports_to_additional_lookup_locations, + transpileOptionValue: void 0 + }, { + // this option can only be specified in tsconfig.json + // use type = object to copy the value as-is + name: "rootDirs", + type: "list", + isTSConfigOnly: true, + element: { name: "rootDirs", - type: "list", - isTSConfigOnly: true, - element: { - name: "rootDirs", - type: "string", - isFilePath: true - }, - affectsModuleResolution: true, - category: Diagnostics.Modules, - description: Diagnostics.Allow_multiple_folders_to_be_treated_as_one_when_resolving_modules, - transpileOptionValue: void 0, - defaultValueDescription: Diagnostics.Computed_from_the_list_of_input_files + type: "string", + isFilePath: true }, - { + affectsModuleResolution: true, + category: Diagnostics.Modules, + description: Diagnostics.Allow_multiple_folders_to_be_treated_as_one_when_resolving_modules, + transpileOptionValue: void 0, + defaultValueDescription: Diagnostics.Computed_from_the_list_of_input_files + }, { + name: "typeRoots", + type: "list", + element: { name: "typeRoots", - type: "list", - element: { - name: "typeRoots", - type: "string", - isFilePath: true - }, - affectsModuleResolution: true, - category: Diagnostics.Modules, - description: Diagnostics.Specify_multiple_folders_that_act_like_Slashnode_modules_Slash_types + type: "string", + isFilePath: true }, - { + affectsModuleResolution: true, + category: Diagnostics.Modules, + description: Diagnostics.Specify_multiple_folders_that_act_like_Slashnode_modules_Slash_types + }, { + name: "types", + type: "list", + element: { name: "types", - type: "list", - element: { - name: "types", - type: "string" - }, - affectsProgramStructure: true, - showInSimplifiedHelpView: true, - category: Diagnostics.Modules, - description: Diagnostics.Specify_type_package_names_to_be_included_without_being_referenced_in_a_source_file, - transpileOptionValue: void 0 + type: "string" }, - { - name: "allowSyntheticDefaultImports", - type: "boolean", - affectsSemanticDiagnostics: true, - affectsBuildInfo: true, - category: Diagnostics.Interop_Constraints, - description: Diagnostics.Allow_import_x_from_y_when_a_module_doesn_t_have_a_default_export, - defaultValueDescription: Diagnostics.module_system_or_esModuleInterop + affectsProgramStructure: true, + showInSimplifiedHelpView: true, + category: Diagnostics.Modules, + description: Diagnostics.Specify_type_package_names_to_be_included_without_being_referenced_in_a_source_file, + transpileOptionValue: void 0 + }, { + name: "allowSyntheticDefaultImports", + type: "boolean", + affectsSemanticDiagnostics: true, + affectsBuildInfo: true, + category: Diagnostics.Interop_Constraints, + description: Diagnostics.Allow_import_x_from_y_when_a_module_doesn_t_have_a_default_export, + defaultValueDescription: Diagnostics.module_system_or_esModuleInterop + }, { + name: "esModuleInterop", + type: "boolean", + affectsSemanticDiagnostics: true, + affectsEmit: true, + affectsBuildInfo: true, + showInSimplifiedHelpView: true, + category: Diagnostics.Interop_Constraints, + description: Diagnostics.Emit_additional_JavaScript_to_ease_support_for_importing_CommonJS_modules_This_enables_allowSyntheticDefaultImports_for_type_compatibility, + defaultValueDescription: false + }, { + name: "preserveSymlinks", + type: "boolean", + category: Diagnostics.Interop_Constraints, + description: Diagnostics.Disable_resolving_symlinks_to_their_realpath_This_correlates_to_the_same_flag_in_node, + defaultValueDescription: false + }, { + name: "allowUmdGlobalAccess", + type: "boolean", + affectsSemanticDiagnostics: true, + affectsBuildInfo: true, + category: Diagnostics.Modules, + description: Diagnostics.Allow_accessing_UMD_globals_from_modules, + defaultValueDescription: false + }, { + name: "moduleSuffixes", + type: "list", + element: { + name: "suffix", + type: "string" }, - { - name: "esModuleInterop", - type: "boolean", - affectsSemanticDiagnostics: true, - affectsEmit: true, - affectsBuildInfo: true, - showInSimplifiedHelpView: true, - category: Diagnostics.Interop_Constraints, - description: Diagnostics.Emit_additional_JavaScript_to_ease_support_for_importing_CommonJS_modules_This_enables_allowSyntheticDefaultImports_for_type_compatibility, - defaultValueDescription: false + listPreserveFalsyValues: true, + affectsModuleResolution: true, + category: Diagnostics.Modules, + description: Diagnostics.List_of_file_name_suffixes_to_search_when_resolving_a_module + }, { + name: "allowImportingTsExtensions", + type: "boolean", + affectsSemanticDiagnostics: true, + affectsBuildInfo: true, + category: Diagnostics.Modules, + description: Diagnostics.Allow_imports_to_include_TypeScript_file_extensions_Requires_moduleResolution_bundler_and_either_noEmit_or_emitDeclarationOnly_to_be_set, + defaultValueDescription: false, + transpileOptionValue: void 0 + }, { + name: "resolvePackageJsonExports", + type: "boolean", + affectsModuleResolution: true, + category: Diagnostics.Modules, + description: Diagnostics.Use_the_package_json_exports_field_when_resolving_package_imports, + defaultValueDescription: Diagnostics.true_when_moduleResolution_is_node16_nodenext_or_bundler_otherwise_false + }, { + name: "resolvePackageJsonImports", + type: "boolean", + affectsModuleResolution: true, + category: Diagnostics.Modules, + description: Diagnostics.Use_the_package_json_imports_field_when_resolving_imports, + defaultValueDescription: Diagnostics.true_when_moduleResolution_is_node16_nodenext_or_bundler_otherwise_false + }, { + name: "customConditions", + type: "list", + element: { + name: "condition", + type: "string" }, - { - name: "preserveSymlinks", - type: "boolean", - category: Diagnostics.Interop_Constraints, - description: Diagnostics.Disable_resolving_symlinks_to_their_realpath_This_correlates_to_the_same_flag_in_node, - defaultValueDescription: false + affectsModuleResolution: true, + category: Diagnostics.Modules, + description: Diagnostics.Conditions_to_set_in_addition_to_the_resolver_specific_defaults_when_resolving_imports + }, + // Source Maps + { + name: "sourceRoot", + type: "string", + affectsEmit: true, + affectsBuildInfo: true, + paramType: Diagnostics.LOCATION, + category: Diagnostics.Emit, + description: Diagnostics.Specify_the_root_path_for_debuggers_to_find_the_reference_source_code + }, { + name: "mapRoot", + type: "string", + affectsEmit: true, + affectsBuildInfo: true, + paramType: Diagnostics.LOCATION, + category: Diagnostics.Emit, + description: Diagnostics.Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations + }, { + name: "inlineSources", + type: "boolean", + affectsEmit: true, + affectsBuildInfo: true, + category: Diagnostics.Emit, + description: Diagnostics.Include_source_code_in_the_sourcemaps_inside_the_emitted_JavaScript, + defaultValueDescription: false + }, + // Experimental + { + name: "experimentalDecorators", + type: "boolean", + affectsEmit: true, + affectsSemanticDiagnostics: true, + affectsBuildInfo: true, + category: Diagnostics.Language_and_Environment, + description: Diagnostics.Enable_experimental_support_for_legacy_experimental_decorators, + defaultValueDescription: false + }, { + name: "emitDecoratorMetadata", + type: "boolean", + affectsSemanticDiagnostics: true, + affectsEmit: true, + affectsBuildInfo: true, + category: Diagnostics.Language_and_Environment, + description: Diagnostics.Emit_design_type_metadata_for_decorated_declarations_in_source_files, + defaultValueDescription: false + }, + // Advanced + { + name: "jsxFactory", + type: "string", + category: Diagnostics.Language_and_Environment, + description: Diagnostics.Specify_the_JSX_factory_function_used_when_targeting_React_JSX_emit_e_g_React_createElement_or_h, + defaultValueDescription: "`React.createElement`" + }, { + name: "jsxFragmentFactory", + type: "string", + category: Diagnostics.Language_and_Environment, + description: Diagnostics.Specify_the_JSX_Fragment_reference_used_for_fragments_when_targeting_React_JSX_emit_e_g_React_Fragment_or_Fragment, + defaultValueDescription: "React.Fragment" + }, { + name: "jsxImportSource", + type: "string", + affectsSemanticDiagnostics: true, + affectsEmit: true, + affectsBuildInfo: true, + affectsModuleResolution: true, + category: Diagnostics.Language_and_Environment, + description: Diagnostics.Specify_module_specifier_used_to_import_the_JSX_factory_functions_when_using_jsx_Colon_react_jsx_Asterisk, + defaultValueDescription: "react" + }, { + name: "resolveJsonModule", + type: "boolean", + affectsModuleResolution: true, + category: Diagnostics.Modules, + description: Diagnostics.Enable_importing_json_files, + defaultValueDescription: false + }, { + name: "allowArbitraryExtensions", + type: "boolean", + affectsProgramStructure: true, + category: Diagnostics.Modules, + description: Diagnostics.Enable_importing_files_with_any_extension_provided_a_declaration_file_is_present, + defaultValueDescription: false + }, { + name: "out", + type: "string", + affectsEmit: true, + affectsBuildInfo: true, + affectsDeclarationPath: true, + isFilePath: false, + // This is intentionally broken to support compatibility with existing tsconfig files + // for correct behaviour, please use outFile + category: Diagnostics.Backwards_Compatibility, + paramType: Diagnostics.FILE, + transpileOptionValue: void 0, + description: Diagnostics.Deprecated_setting_Use_outFile_instead + }, { + name: "reactNamespace", + type: "string", + affectsEmit: true, + affectsBuildInfo: true, + category: Diagnostics.Language_and_Environment, + description: Diagnostics.Specify_the_object_invoked_for_createElement_This_only_applies_when_targeting_react_JSX_emit, + defaultValueDescription: "`React`" + }, { + name: "skipDefaultLibCheck", + type: "boolean", + // We need to store these to determine whether `lib` files need to be rechecked + affectsBuildInfo: true, + category: Diagnostics.Completeness, + description: Diagnostics.Skip_type_checking_d_ts_files_that_are_included_with_TypeScript, + defaultValueDescription: false + }, { + name: "charset", + type: "string", + category: Diagnostics.Backwards_Compatibility, + description: Diagnostics.No_longer_supported_In_early_versions_manually_set_the_text_encoding_for_reading_files, + defaultValueDescription: "utf8" + }, { + name: "emitBOM", + type: "boolean", + affectsEmit: true, + affectsBuildInfo: true, + category: Diagnostics.Emit, + description: Diagnostics.Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files, + defaultValueDescription: false + }, { + name: "newLine", + type: new Map(Object.entries({ + crlf: 0 /* CarriageReturnLineFeed */, + lf: 1 /* LineFeed */ + })), + + affectsEmit: true, + affectsBuildInfo: true, + paramType: Diagnostics.NEWLINE, + category: Diagnostics.Emit, + description: Diagnostics.Set_the_newline_character_for_emitting_files, + defaultValueDescription: "lf" + }, { + name: "noErrorTruncation", + type: "boolean", + affectsSemanticDiagnostics: true, + affectsBuildInfo: true, + category: Diagnostics.Output_Formatting, + description: Diagnostics.Disable_truncating_types_in_error_messages, + defaultValueDescription: false + }, { + name: "noLib", + type: "boolean", + category: Diagnostics.Language_and_Environment, + affectsProgramStructure: true, + description: Diagnostics.Disable_including_any_library_files_including_the_default_lib_d_ts, + // We are not returning a sourceFile for lib file when asked by the program, + // so pass --noLib to avoid reporting a file not found error. + transpileOptionValue: true, + defaultValueDescription: false + }, { + name: "noResolve", + type: "boolean", + affectsModuleResolution: true, + category: Diagnostics.Modules, + description: Diagnostics.Disallow_import_s_require_s_or_reference_s_from_expanding_the_number_of_files_TypeScript_should_add_to_a_project, + // We are not doing a full typecheck, we are not resolving the whole context, + // so pass --noResolve to avoid reporting missing file errors. + transpileOptionValue: true, + defaultValueDescription: false + }, { + name: "stripInternal", + type: "boolean", + affectsEmit: true, + affectsBuildInfo: true, + category: Diagnostics.Emit, + description: Diagnostics.Disable_emitting_declarations_that_have_internal_in_their_JSDoc_comments, + defaultValueDescription: false + }, { + name: "disableSizeLimit", + type: "boolean", + affectsProgramStructure: true, + category: Diagnostics.Editor_Support, + description: Diagnostics.Remove_the_20mb_cap_on_total_source_code_size_for_JavaScript_files_in_the_TypeScript_language_server, + defaultValueDescription: false + }, { + name: "disableSourceOfProjectReferenceRedirect", + type: "boolean", + isTSConfigOnly: true, + category: Diagnostics.Projects, + description: Diagnostics.Disable_preferring_source_files_instead_of_declaration_files_when_referencing_composite_projects, + defaultValueDescription: false + }, { + name: "disableSolutionSearching", + type: "boolean", + isTSConfigOnly: true, + category: Diagnostics.Projects, + description: Diagnostics.Opt_a_project_out_of_multi_project_reference_checking_when_editing, + defaultValueDescription: false + }, { + name: "disableReferencedProjectLoad", + type: "boolean", + isTSConfigOnly: true, + category: Diagnostics.Projects, + description: Diagnostics.Reduce_the_number_of_projects_loaded_automatically_by_TypeScript, + defaultValueDescription: false + }, { + name: "noImplicitUseStrict", + type: "boolean", + affectsSemanticDiagnostics: true, + affectsBuildInfo: true, + category: Diagnostics.Backwards_Compatibility, + description: Diagnostics.Disable_adding_use_strict_directives_in_emitted_JavaScript_files, + defaultValueDescription: false + }, { + name: "noEmitHelpers", + type: "boolean", + affectsEmit: true, + affectsBuildInfo: true, + category: Diagnostics.Emit, + description: Diagnostics.Disable_generating_custom_helper_functions_like_extends_in_compiled_output, + defaultValueDescription: false + }, { + name: "noEmitOnError", + type: "boolean", + affectsEmit: true, + affectsBuildInfo: true, + category: Diagnostics.Emit, + transpileOptionValue: void 0, + description: Diagnostics.Disable_emitting_files_if_any_type_checking_errors_are_reported, + defaultValueDescription: false + }, { + name: "preserveConstEnums", + type: "boolean", + affectsEmit: true, + affectsBuildInfo: true, + category: Diagnostics.Emit, + description: Diagnostics.Disable_erasing_const_enum_declarations_in_generated_code, + defaultValueDescription: false + }, { + name: "declarationDir", + type: "string", + affectsEmit: true, + affectsBuildInfo: true, + affectsDeclarationPath: true, + isFilePath: true, + paramType: Diagnostics.DIRECTORY, + category: Diagnostics.Emit, + transpileOptionValue: void 0, + description: Diagnostics.Specify_the_output_directory_for_generated_declaration_files + }, { + name: "skipLibCheck", + type: "boolean", + // We need to store these to determine whether `lib` files need to be rechecked + affectsBuildInfo: true, + category: Diagnostics.Completeness, + description: Diagnostics.Skip_type_checking_all_d_ts_files, + defaultValueDescription: false + }, { + name: "allowUnusedLabels", + type: "boolean", + affectsBindDiagnostics: true, + affectsSemanticDiagnostics: true, + affectsBuildInfo: true, + category: Diagnostics.Type_Checking, + description: Diagnostics.Disable_error_reporting_for_unused_labels, + defaultValueDescription: void 0 + }, { + name: "allowUnreachableCode", + type: "boolean", + affectsBindDiagnostics: true, + affectsSemanticDiagnostics: true, + affectsBuildInfo: true, + category: Diagnostics.Type_Checking, + description: Diagnostics.Disable_error_reporting_for_unreachable_code, + defaultValueDescription: void 0 + }, { + name: "suppressExcessPropertyErrors", + type: "boolean", + affectsSemanticDiagnostics: true, + affectsBuildInfo: true, + category: Diagnostics.Backwards_Compatibility, + description: Diagnostics.Disable_reporting_of_excess_property_errors_during_the_creation_of_object_literals, + defaultValueDescription: false + }, { + name: "suppressImplicitAnyIndexErrors", + type: "boolean", + affectsSemanticDiagnostics: true, + affectsBuildInfo: true, + category: Diagnostics.Backwards_Compatibility, + description: Diagnostics.Suppress_noImplicitAny_errors_when_indexing_objects_that_lack_index_signatures, + defaultValueDescription: false + }, { + name: "forceConsistentCasingInFileNames", + type: "boolean", + affectsModuleResolution: true, + category: Diagnostics.Interop_Constraints, + description: Diagnostics.Ensure_that_casing_is_correct_in_imports, + defaultValueDescription: true + }, { + name: "maxNodeModuleJsDepth", + type: "number", + affectsModuleResolution: true, + category: Diagnostics.JavaScript_Support, + description: Diagnostics.Specify_the_maximum_folder_depth_used_for_checking_JavaScript_files_from_node_modules_Only_applicable_with_allowJs, + defaultValueDescription: 0 + }, { + name: "noStrictGenericChecks", + type: "boolean", + affectsSemanticDiagnostics: true, + affectsBuildInfo: true, + category: Diagnostics.Backwards_Compatibility, + description: Diagnostics.Disable_strict_checking_of_generic_signatures_in_function_types, + defaultValueDescription: false + }, { + name: "useDefineForClassFields", + type: "boolean", + affectsSemanticDiagnostics: true, + affectsEmit: true, + affectsBuildInfo: true, + category: Diagnostics.Language_and_Environment, + description: Diagnostics.Emit_ECMAScript_standard_compliant_class_fields, + defaultValueDescription: Diagnostics.true_for_ES2022_and_above_including_ESNext + }, { + name: "preserveValueImports", + type: "boolean", + affectsEmit: true, + affectsBuildInfo: true, + category: Diagnostics.Emit, + description: Diagnostics.Preserve_unused_imported_values_in_the_JavaScript_output_that_would_otherwise_be_removed, + defaultValueDescription: false + }, { + name: "keyofStringsOnly", + type: "boolean", + category: Diagnostics.Backwards_Compatibility, + description: Diagnostics.Make_keyof_only_return_strings_instead_of_string_numbers_or_symbols_Legacy_option, + defaultValueDescription: false + }, { + // A list of plugins to load in the language service + name: "plugins", + type: "list", + isTSConfigOnly: true, + element: { + name: "plugin", + type: "object" }, - { - name: "allowUmdGlobalAccess", - type: "boolean", - affectsSemanticDiagnostics: true, - affectsBuildInfo: true, - category: Diagnostics.Modules, - description: Diagnostics.Allow_accessing_UMD_globals_from_modules, - defaultValueDescription: false - }, - { - name: "moduleSuffixes", - type: "list", - element: { - name: "suffix", - type: "string" - }, - listPreserveFalsyValues: true, - affectsModuleResolution: true, - category: Diagnostics.Modules, - description: Diagnostics.List_of_file_name_suffixes_to_search_when_resolving_a_module - }, - { - name: "allowImportingTsExtensions", - type: "boolean", - affectsSemanticDiagnostics: true, - affectsBuildInfo: true, - category: Diagnostics.Modules, - description: Diagnostics.Allow_imports_to_include_TypeScript_file_extensions_Requires_moduleResolution_bundler_and_either_noEmit_or_emitDeclarationOnly_to_be_set, - defaultValueDescription: false, - transpileOptionValue: void 0 - }, - { - name: "resolvePackageJsonExports", - type: "boolean", - affectsModuleResolution: true, - category: Diagnostics.Modules, - description: Diagnostics.Use_the_package_json_exports_field_when_resolving_package_imports, - defaultValueDescription: Diagnostics.true_when_moduleResolution_is_node16_nodenext_or_bundler_otherwise_false - }, - { - name: "resolvePackageJsonImports", - type: "boolean", - affectsModuleResolution: true, - category: Diagnostics.Modules, - description: Diagnostics.Use_the_package_json_imports_field_when_resolving_imports, - defaultValueDescription: Diagnostics.true_when_moduleResolution_is_node16_nodenext_or_bundler_otherwise_false - }, - { - name: "customConditions", - type: "list", - element: { - name: "condition", - type: "string" - }, - affectsModuleResolution: true, - category: Diagnostics.Modules, - description: Diagnostics.Conditions_to_set_in_addition_to_the_resolver_specific_defaults_when_resolving_imports - }, - // Source Maps - { - name: "sourceRoot", - type: "string", - affectsEmit: true, - affectsBuildInfo: true, - paramType: Diagnostics.LOCATION, - category: Diagnostics.Emit, - description: Diagnostics.Specify_the_root_path_for_debuggers_to_find_the_reference_source_code - }, - { - name: "mapRoot", - type: "string", - affectsEmit: true, - affectsBuildInfo: true, - paramType: Diagnostics.LOCATION, - category: Diagnostics.Emit, - description: Diagnostics.Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations - }, - { - name: "inlineSources", - type: "boolean", - affectsEmit: true, - affectsBuildInfo: true, - category: Diagnostics.Emit, - description: Diagnostics.Include_source_code_in_the_sourcemaps_inside_the_emitted_JavaScript, - defaultValueDescription: false - }, - // Experimental - { - name: "experimentalDecorators", - type: "boolean", - affectsEmit: true, - affectsSemanticDiagnostics: true, - affectsBuildInfo: true, - category: Diagnostics.Language_and_Environment, - description: Diagnostics.Enable_experimental_support_for_legacy_experimental_decorators, - defaultValueDescription: false - }, - { - name: "emitDecoratorMetadata", - type: "boolean", - affectsSemanticDiagnostics: true, - affectsEmit: true, - affectsBuildInfo: true, - category: Diagnostics.Language_and_Environment, - description: Diagnostics.Emit_design_type_metadata_for_decorated_declarations_in_source_files, - defaultValueDescription: false - }, - // Advanced - { - name: "jsxFactory", - type: "string", - category: Diagnostics.Language_and_Environment, - description: Diagnostics.Specify_the_JSX_factory_function_used_when_targeting_React_JSX_emit_e_g_React_createElement_or_h, - defaultValueDescription: "`React.createElement`" - }, - { - name: "jsxFragmentFactory", - type: "string", - category: Diagnostics.Language_and_Environment, - description: Diagnostics.Specify_the_JSX_Fragment_reference_used_for_fragments_when_targeting_React_JSX_emit_e_g_React_Fragment_or_Fragment, - defaultValueDescription: "React.Fragment" - }, - { - name: "jsxImportSource", - type: "string", - affectsSemanticDiagnostics: true, - affectsEmit: true, - affectsBuildInfo: true, - affectsModuleResolution: true, - category: Diagnostics.Language_and_Environment, - description: Diagnostics.Specify_module_specifier_used_to_import_the_JSX_factory_functions_when_using_jsx_Colon_react_jsx_Asterisk, - defaultValueDescription: "react" - }, - { - name: "resolveJsonModule", - type: "boolean", - affectsModuleResolution: true, - category: Diagnostics.Modules, - description: Diagnostics.Enable_importing_json_files, - defaultValueDescription: false - }, - { - name: "allowArbitraryExtensions", - type: "boolean", - affectsProgramStructure: true, - category: Diagnostics.Modules, - description: Diagnostics.Enable_importing_files_with_any_extension_provided_a_declaration_file_is_present, - defaultValueDescription: false - }, - { - name: "out", - type: "string", - affectsEmit: true, - affectsBuildInfo: true, - affectsDeclarationPath: true, - isFilePath: false, - // This is intentionally broken to support compatibility with existing tsconfig files - // for correct behaviour, please use outFile - category: Diagnostics.Backwards_Compatibility, - paramType: Diagnostics.FILE, - transpileOptionValue: void 0, - description: Diagnostics.Deprecated_setting_Use_outFile_instead - }, - { - name: "reactNamespace", - type: "string", - affectsEmit: true, - affectsBuildInfo: true, - category: Diagnostics.Language_and_Environment, - description: Diagnostics.Specify_the_object_invoked_for_createElement_This_only_applies_when_targeting_react_JSX_emit, - defaultValueDescription: "`React`" - }, - { - name: "skipDefaultLibCheck", - type: "boolean", - // We need to store these to determine whether `lib` files need to be rechecked - affectsBuildInfo: true, - category: Diagnostics.Completeness, - description: Diagnostics.Skip_type_checking_d_ts_files_that_are_included_with_TypeScript, - defaultValueDescription: false - }, - { - name: "charset", - type: "string", - category: Diagnostics.Backwards_Compatibility, - description: Diagnostics.No_longer_supported_In_early_versions_manually_set_the_text_encoding_for_reading_files, - defaultValueDescription: "utf8" - }, - { - name: "emitBOM", - type: "boolean", - affectsEmit: true, - affectsBuildInfo: true, - category: Diagnostics.Emit, - description: Diagnostics.Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files, - defaultValueDescription: false - }, - { - name: "newLine", - type: new Map(Object.entries({ - crlf: 0 /* CarriageReturnLineFeed */, - lf: 1 /* LineFeed */ - })), - affectsEmit: true, - affectsBuildInfo: true, - paramType: Diagnostics.NEWLINE, - category: Diagnostics.Emit, - description: Diagnostics.Set_the_newline_character_for_emitting_files, - defaultValueDescription: "lf" - }, - { - name: "noErrorTruncation", - type: "boolean", - affectsSemanticDiagnostics: true, - affectsBuildInfo: true, - category: Diagnostics.Output_Formatting, - description: Diagnostics.Disable_truncating_types_in_error_messages, - defaultValueDescription: false - }, - { - name: "noLib", - type: "boolean", - category: Diagnostics.Language_and_Environment, - affectsProgramStructure: true, - description: Diagnostics.Disable_including_any_library_files_including_the_default_lib_d_ts, - // We are not returning a sourceFile for lib file when asked by the program, - // so pass --noLib to avoid reporting a file not found error. - transpileOptionValue: true, - defaultValueDescription: false - }, - { - name: "noResolve", - type: "boolean", - affectsModuleResolution: true, - category: Diagnostics.Modules, - description: Diagnostics.Disallow_import_s_require_s_or_reference_s_from_expanding_the_number_of_files_TypeScript_should_add_to_a_project, - // We are not doing a full typecheck, we are not resolving the whole context, - // so pass --noResolve to avoid reporting missing file errors. - transpileOptionValue: true, - defaultValueDescription: false - }, - { - name: "stripInternal", - type: "boolean", - affectsEmit: true, - affectsBuildInfo: true, - category: Diagnostics.Emit, - description: Diagnostics.Disable_emitting_declarations_that_have_internal_in_their_JSDoc_comments, - defaultValueDescription: false - }, - { - name: "disableSizeLimit", - type: "boolean", - affectsProgramStructure: true, - category: Diagnostics.Editor_Support, - description: Diagnostics.Remove_the_20mb_cap_on_total_source_code_size_for_JavaScript_files_in_the_TypeScript_language_server, - defaultValueDescription: false - }, - { - name: "disableSourceOfProjectReferenceRedirect", - type: "boolean", - isTSConfigOnly: true, - category: Diagnostics.Projects, - description: Diagnostics.Disable_preferring_source_files_instead_of_declaration_files_when_referencing_composite_projects, - defaultValueDescription: false - }, - { - name: "disableSolutionSearching", - type: "boolean", - isTSConfigOnly: true, - category: Diagnostics.Projects, - description: Diagnostics.Opt_a_project_out_of_multi_project_reference_checking_when_editing, - defaultValueDescription: false - }, - { - name: "disableReferencedProjectLoad", - type: "boolean", - isTSConfigOnly: true, - category: Diagnostics.Projects, - description: Diagnostics.Reduce_the_number_of_projects_loaded_automatically_by_TypeScript, - defaultValueDescription: false - }, - { - name: "noImplicitUseStrict", - type: "boolean", - affectsSemanticDiagnostics: true, - affectsBuildInfo: true, - category: Diagnostics.Backwards_Compatibility, - description: Diagnostics.Disable_adding_use_strict_directives_in_emitted_JavaScript_files, - defaultValueDescription: false - }, - { - name: "noEmitHelpers", - type: "boolean", - affectsEmit: true, - affectsBuildInfo: true, - category: Diagnostics.Emit, - description: Diagnostics.Disable_generating_custom_helper_functions_like_extends_in_compiled_output, - defaultValueDescription: false - }, - { - name: "noEmitOnError", - type: "boolean", - affectsEmit: true, - affectsBuildInfo: true, - category: Diagnostics.Emit, - transpileOptionValue: void 0, - description: Diagnostics.Disable_emitting_files_if_any_type_checking_errors_are_reported, - defaultValueDescription: false - }, - { - name: "preserveConstEnums", - type: "boolean", - affectsEmit: true, - affectsBuildInfo: true, - category: Diagnostics.Emit, - description: Diagnostics.Disable_erasing_const_enum_declarations_in_generated_code, - defaultValueDescription: false - }, - { - name: "declarationDir", - type: "string", - affectsEmit: true, - affectsBuildInfo: true, - affectsDeclarationPath: true, - isFilePath: true, - paramType: Diagnostics.DIRECTORY, - category: Diagnostics.Emit, - transpileOptionValue: void 0, - description: Diagnostics.Specify_the_output_directory_for_generated_declaration_files - }, - { - name: "skipLibCheck", - type: "boolean", - // We need to store these to determine whether `lib` files need to be rechecked - affectsBuildInfo: true, - category: Diagnostics.Completeness, - description: Diagnostics.Skip_type_checking_all_d_ts_files, - defaultValueDescription: false - }, - { - name: "allowUnusedLabels", - type: "boolean", - affectsBindDiagnostics: true, - affectsSemanticDiagnostics: true, - affectsBuildInfo: true, - category: Diagnostics.Type_Checking, - description: Diagnostics.Disable_error_reporting_for_unused_labels, - defaultValueDescription: void 0 - }, - { - name: "allowUnreachableCode", - type: "boolean", - affectsBindDiagnostics: true, - affectsSemanticDiagnostics: true, - affectsBuildInfo: true, - category: Diagnostics.Type_Checking, - description: Diagnostics.Disable_error_reporting_for_unreachable_code, - defaultValueDescription: void 0 - }, - { - name: "suppressExcessPropertyErrors", - type: "boolean", - affectsSemanticDiagnostics: true, - affectsBuildInfo: true, - category: Diagnostics.Backwards_Compatibility, - description: Diagnostics.Disable_reporting_of_excess_property_errors_during_the_creation_of_object_literals, - defaultValueDescription: false - }, - { - name: "suppressImplicitAnyIndexErrors", - type: "boolean", - affectsSemanticDiagnostics: true, - affectsBuildInfo: true, - category: Diagnostics.Backwards_Compatibility, - description: Diagnostics.Suppress_noImplicitAny_errors_when_indexing_objects_that_lack_index_signatures, - defaultValueDescription: false - }, - { - name: "forceConsistentCasingInFileNames", - type: "boolean", - affectsModuleResolution: true, - category: Diagnostics.Interop_Constraints, - description: Diagnostics.Ensure_that_casing_is_correct_in_imports, - defaultValueDescription: true - }, - { - name: "maxNodeModuleJsDepth", - type: "number", - affectsModuleResolution: true, - category: Diagnostics.JavaScript_Support, - description: Diagnostics.Specify_the_maximum_folder_depth_used_for_checking_JavaScript_files_from_node_modules_Only_applicable_with_allowJs, - defaultValueDescription: 0 - }, - { - name: "noStrictGenericChecks", - type: "boolean", - affectsSemanticDiagnostics: true, - affectsBuildInfo: true, - category: Diagnostics.Backwards_Compatibility, - description: Diagnostics.Disable_strict_checking_of_generic_signatures_in_function_types, - defaultValueDescription: false - }, - { - name: "useDefineForClassFields", - type: "boolean", - affectsSemanticDiagnostics: true, - affectsEmit: true, - affectsBuildInfo: true, - category: Diagnostics.Language_and_Environment, - description: Diagnostics.Emit_ECMAScript_standard_compliant_class_fields, - defaultValueDescription: Diagnostics.true_for_ES2022_and_above_including_ESNext - }, - { - name: "preserveValueImports", - type: "boolean", - affectsEmit: true, - affectsBuildInfo: true, - category: Diagnostics.Emit, - description: Diagnostics.Preserve_unused_imported_values_in_the_JavaScript_output_that_would_otherwise_be_removed, - defaultValueDescription: false - }, - { - name: "keyofStringsOnly", - type: "boolean", - category: Diagnostics.Backwards_Compatibility, - description: Diagnostics.Make_keyof_only_return_strings_instead_of_string_numbers_or_symbols_Legacy_option, - defaultValueDescription: false - }, - { - // A list of plugins to load in the language service - name: "plugins", - type: "list", - isTSConfigOnly: true, - element: { - name: "plugin", - type: "object" - }, - description: Diagnostics.Specify_a_list_of_language_service_plugins_to_include, - category: Diagnostics.Editor_Support - }, - { - name: "moduleDetection", - type: new Map(Object.entries({ - auto: 2 /* Auto */, - legacy: 1 /* Legacy */, - force: 3 /* Force */ - })), - affectsSourceFile: true, - affectsModuleResolution: true, - description: Diagnostics.Control_what_method_is_used_to_detect_module_format_JS_files, - category: Diagnostics.Language_and_Environment, - defaultValueDescription: Diagnostics.auto_Colon_Treat_files_with_imports_exports_import_meta_jsx_with_jsx_Colon_react_jsx_or_esm_format_with_module_Colon_node16_as_modules - }, - { - name: "ignoreDeprecations", - type: "string", - defaultValueDescription: void 0 - } - ]; - optionDeclarations = [ - ...commonOptionsWithBuild, - ...commandOptionsWithoutBuild - ]; - semanticDiagnosticsOptionDeclarations = optionDeclarations.filter((option) => !!option.affectsSemanticDiagnostics); - affectsEmitOptionDeclarations = optionDeclarations.filter((option) => !!option.affectsEmit); - affectsDeclarationPathOptionDeclarations = optionDeclarations.filter((option) => !!option.affectsDeclarationPath); - moduleResolutionOptionDeclarations = optionDeclarations.filter((option) => !!option.affectsModuleResolution); - sourceFileAffectingCompilerOptions = optionDeclarations.filter((option) => !!option.affectsSourceFile || !!option.affectsBindDiagnostics); - optionsAffectingProgramStructure = optionDeclarations.filter((option) => !!option.affectsProgramStructure); - transpileOptionValueCompilerOptions = optionDeclarations.filter((option) => hasProperty(option, "transpileOptionValue")); - optionsForBuild = [ - { - name: "verbose", - shortName: "v", - category: Diagnostics.Command_line_Options, - description: Diagnostics.Enable_verbose_logging, - type: "boolean", - defaultValueDescription: false - }, - { - name: "dry", - shortName: "d", - category: Diagnostics.Command_line_Options, - description: Diagnostics.Show_what_would_be_built_or_deleted_if_specified_with_clean, - type: "boolean", - defaultValueDescription: false - }, - { - name: "force", - shortName: "f", - category: Diagnostics.Command_line_Options, - description: Diagnostics.Build_all_projects_including_those_that_appear_to_be_up_to_date, - type: "boolean", - defaultValueDescription: false - }, - { - name: "clean", - category: Diagnostics.Command_line_Options, - description: Diagnostics.Delete_the_outputs_of_all_projects, - type: "boolean", - defaultValueDescription: false - } - ]; - buildOpts = [ - ...commonOptionsWithBuild, - ...optionsForBuild - ]; - typeAcquisitionDeclarations = [ - { - name: "enable", - type: "boolean", - defaultValueDescription: false - }, - { + description: Diagnostics.Specify_a_list_of_language_service_plugins_to_include, + category: Diagnostics.Editor_Support + }, { + name: "moduleDetection", + type: new Map(Object.entries({ + auto: 2 /* Auto */, + legacy: 1 /* Legacy */, + force: 3 /* Force */ + })), + + affectsSourceFile: true, + affectsModuleResolution: true, + description: Diagnostics.Control_what_method_is_used_to_detect_module_format_JS_files, + category: Diagnostics.Language_and_Environment, + defaultValueDescription: Diagnostics.auto_Colon_Treat_files_with_imports_exports_import_meta_jsx_with_jsx_Colon_react_jsx_or_esm_format_with_module_Colon_node16_as_modules + }, { + name: "ignoreDeprecations", + type: "string", + defaultValueDescription: void 0 + }]; + optionDeclarations = [...commonOptionsWithBuild, ...commandOptionsWithoutBuild]; + semanticDiagnosticsOptionDeclarations = optionDeclarations.filter(option => !!option.affectsSemanticDiagnostics); + affectsEmitOptionDeclarations = optionDeclarations.filter(option => !!option.affectsEmit); + affectsDeclarationPathOptionDeclarations = optionDeclarations.filter(option => !!option.affectsDeclarationPath); + moduleResolutionOptionDeclarations = optionDeclarations.filter(option => !!option.affectsModuleResolution); + sourceFileAffectingCompilerOptions = optionDeclarations.filter(option => !!option.affectsSourceFile || !!option.affectsBindDiagnostics); + optionsAffectingProgramStructure = optionDeclarations.filter(option => !!option.affectsProgramStructure); + transpileOptionValueCompilerOptions = optionDeclarations.filter(option => hasProperty(option, "transpileOptionValue")); + optionsForBuild = [{ + name: "verbose", + shortName: "v", + category: Diagnostics.Command_line_Options, + description: Diagnostics.Enable_verbose_logging, + type: "boolean", + defaultValueDescription: false + }, { + name: "dry", + shortName: "d", + category: Diagnostics.Command_line_Options, + description: Diagnostics.Show_what_would_be_built_or_deleted_if_specified_with_clean, + type: "boolean", + defaultValueDescription: false + }, { + name: "force", + shortName: "f", + category: Diagnostics.Command_line_Options, + description: Diagnostics.Build_all_projects_including_those_that_appear_to_be_up_to_date, + type: "boolean", + defaultValueDescription: false + }, { + name: "clean", + category: Diagnostics.Command_line_Options, + description: Diagnostics.Delete_the_outputs_of_all_projects, + type: "boolean", + defaultValueDescription: false + }]; + buildOpts = [...commonOptionsWithBuild, ...optionsForBuild]; + typeAcquisitionDeclarations = [{ + name: "enable", + type: "boolean", + defaultValueDescription: false + }, { + name: "include", + type: "list", + element: { name: "include", - type: "list", - element: { - name: "include", - type: "string" - } - }, - { - name: "exclude", - type: "list", - element: { - name: "exclude", - type: "string" - } - }, - { - name: "disableFilenameBasedTypeAcquisition", - type: "boolean", - defaultValueDescription: false + type: "string" } - ]; + }, { + name: "exclude", + type: "list", + element: { + name: "exclude", + type: "string" + } + }, { + name: "disableFilenameBasedTypeAcquisition", + type: "boolean", + defaultValueDescription: false + }]; compilerOptionsAlternateMode = { diagnostic: Diagnostics.Compiler_option_0_may_only_be_used_with_build, getOptionsNameMap: getBuildOptionsNameMap @@ -39246,43 +37417,41 @@ ${lanes.join("\n")} }; } } - return r && { path: r.path, extension: r.ext, packageId, resolvedUsingTsExtension: r.resolvedUsingTsExtension }; + return r && { + path: r.path, + extension: r.ext, + packageId, + resolvedUsingTsExtension: r.resolvedUsingTsExtension + }; } function noPackageId(r) { - return withPackageId( - /*packageInfo*/ - void 0, - r - ); + return withPackageId( /*packageInfo*/ + void 0, r); } function removeIgnoredPackageId(r) { if (r) { Debug.assert(r.packageId === void 0); - return { path: r.path, ext: r.extension, resolvedUsingTsExtension: r.resolvedUsingTsExtension }; + return { + path: r.path, + ext: r.extension, + resolvedUsingTsExtension: r.resolvedUsingTsExtension + }; } } 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) { @@ -39290,24 +37459,24 @@ ${lanes.join("\n")} return void 0; } Debug.assert(extensionIsTS(resolved.extension)); - return { fileName: resolved.path, packageId: resolved.packageId }; + return { + fileName: resolved.path, + packageId: resolved.packageId + }; } function createResolvedModuleWithFailedLookupLocationsHandlingSymlink(moduleName, resolved, isExternalLibraryImport, failedLookupLocations, affectingLocations, diagnostics, state, cache, legacyResult) { 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 }; + const { + resolvedFileName, + originalPath + } = getOriginalAndResolvedFileName(resolved.path, state.host, state.traceEnabled); + if (originalPath) resolved = { + ...resolved, + path: resolvedFileName, + originalPath + }; } - return createResolvedModuleWithFailedLookupLocations( - resolved, - isExternalLibraryImport, - failedLookupLocations, - affectingLocations, - diagnostics, - state.resultFromCache, - cache, - legacyResult - ); + return createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations, affectingLocations, diagnostics, state.resultFromCache, cache, legacyResult); } function createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations, affectingLocations, diagnostics, resultFromCache, cache, legacyResult) { if (resultFromCache) { @@ -39344,18 +37513,14 @@ ${lanes.join("\n")} 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) { @@ -39402,8 +37567,7 @@ ${lanes.join("\n")} } 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); } @@ -39411,8 +37575,7 @@ ${lanes.join("\n")} } 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)) { @@ -39427,7 +37590,10 @@ ${lanes.join("\n")} } return; } - const { version: bestVersionKey, paths: bestVersionPaths } = result; + const { + version: bestVersionKey, + paths: bestVersionPaths + } = result; if (typeof bestVersionPaths !== "object") { if (state.traceEnabled) { trace(state.host, Diagnostics.Expected_type_of_0_field_in_package_json_to_be_1_got_2, `typesVersions['${bestVersionKey}']`, "object", typeof bestVersionPaths); @@ -39437,17 +37603,18 @@ ${lanes.join("\n")} return result; } 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; } if (keyRange.test(typeScriptVersion)) { - return { version: key, paths: typesVersions[key] }; + return { + version: key, + paths: typesVersions[key] + }; } } } @@ -39467,9 +37634,10 @@ ${lanes.join("\n")} } function getDefaultTypeRoots(currentDirectory) { let typeRoots; - forEachAncestorDirectory(normalizePath(currentDirectory), (directory) => { + forEachAncestorDirectory(normalizePath(currentDirectory), directory => { + var _typeRoots; const atTypes = combinePaths(directory, nodeModulesAtTypes); - (typeRoots ?? (typeRoots = [])).push(atTypes); + ((_typeRoots = typeRoots) !== null && _typeRoots !== void 0 ? _typeRoots : typeRoots = []).push(atTypes); }); return typeRoots; } @@ -39477,6 +37645,7 @@ ${lanes.join("\n")} const useCaseSensitiveFileNames2 = typeof host.useCaseSensitiveFileNames === "function" ? host.useCaseSensitiveFileNames() : host.useCaseSensitiveFileNames; return comparePaths(path1, path2, !useCaseSensitiveFileNames2) === 0 /* EqualTo */; } + function getOriginalAndResolvedFileName(fileName, host, traceEnabled) { const resolvedFileName = realPath(fileName, host, traceEnabled); const pathsAreEqual = arePathsEqual(fileName, resolvedFileName, host); @@ -39504,8 +37673,7 @@ ${lanes.join("\n")} 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); } @@ -39536,10 +37704,12 @@ ${lanes.join("\n")} if (resolutionMode !== void 0) { features |= 30 /* AllFeatures */; } + const moduleResolution = getEmitModuleResolutionKind(options); - if (resolutionMode === 99 /* ESNext */ && (3 /* Node16 */ <= moduleResolution && moduleResolution <= 99 /* NodeNext */)) { + if (resolutionMode === 99 /* ESNext */ && 3 /* Node16 */ <= moduleResolution && moduleResolution <= 99 /* NodeNext */) { features |= 32 /* EsmMode */; } + const conditions = features & 8 /* Exports */ ? getConditions(options, resolutionMode) : []; const diagnostics = []; const moduleResolutionState = { @@ -39552,7 +37722,7 @@ ${lanes.join("\n")} features, conditions, requestContainingDirectory: containingDirectory, - reportDiagnostic: (diag2) => void diagnostics.push(diag2), + reportDiagnostic: diag2 => void diagnostics.push(diag2), isConfigLookup: false, candidateIsFromPackageJsonField: false }; @@ -39564,10 +37734,16 @@ ${lanes.join("\n")} } let resolvedTypeReferenceDirective; if (resolved) { - const { fileName, packageId } = resolved; - let resolvedFileName = fileName, originalPath; - if (!options.preserveSymlinks) - ({ resolvedFileName, originalPath } = getOriginalAndResolvedFileName(fileName, host, traceEnabled)); + const { + fileName, + packageId + } = resolved; + let resolvedFileName = fileName, + originalPath; + if (!options.preserveSymlinks) ({ + resolvedFileName, + originalPath + } = getOriginalAndResolvedFileName(fileName, host, traceEnabled)); resolvedTypeReferenceDirective = { primary, resolvedFileName, @@ -39583,18 +37759,13 @@ ${lanes.join("\n")} resolutionDiagnostics: initializeResolutionField(diagnostics) }; if (containingDirectory && cache && !cache.isReadonly) { - cache.getOrCreateCacheForDirectory(containingDirectory, redirectedReference).set( - typeReferenceDirectiveName, - /*mode*/ - resolutionMode, - result - ); + cache.getOrCreateCacheForDirectory(containingDirectory, redirectedReference).set(typeReferenceDirectiveName, /*mode*/ + resolutionMode, result); if (!isExternalModuleNameRelative(typeReferenceDirectiveName)) { cache.getOrCreateCacheForNonRelativeName(typeReferenceDirectiveName, resolutionMode, redirectedReference).set(containingDirectory, result); } } - if (traceEnabled) - traceResult(result); + if (traceEnabled) traceResult(result); return result; function traceResult(result2) { var _a; @@ -39611,7 +37782,7 @@ ${lanes.join("\n")} if (traceEnabled) { trace(host, Diagnostics.Resolving_with_primary_search_path_0, typeRoots.join(", ")); } - return firstDefined(typeRoots, (typeRoot) => { + return firstDefined(typeRoots, typeRoot => { const candidate = getCandidateFromTypeRoot(typeRoot, typeReferenceDirectiveName, moduleResolutionState); const directoryExists = directoryProbablyExists(typeRoot, host); if (!directoryExists && traceEnabled) { @@ -39621,18 +37792,12 @@ ${lanes.join("\n")} const resolvedFromFile = loadModuleFromFile(4 /* Declaration */, candidate, !directoryExists, moduleResolutionState); if (resolvedFromFile) { const packageDirectory = parseNodeModuleFromPath(resolvedFromFile.path); - const packageInfo = packageDirectory ? getPackageJsonInfo( - packageDirectory, - /*onlyRecordFailures*/ - false, - moduleResolutionState - ) : void 0; + const packageInfo = packageDirectory ? getPackageJsonInfo(packageDirectory, /*onlyRecordFailures*/ + false, moduleResolutionState) : void 0; return resolvedTypeScriptOnly(withPackageId(packageInfo, resolvedFromFile)); } } - return resolvedTypeScriptOnly( - loadNodeModuleFromDirectory(4 /* Declaration */, candidate, !directoryExists, moduleResolutionState) - ); + return resolvedTypeScriptOnly(loadNodeModuleFromDirectory(4 /* Declaration */, candidate, !directoryExists, moduleResolutionState)); }); } else { if (traceEnabled) { @@ -39649,28 +37814,17 @@ ${lanes.join("\n")} trace(host, Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup); } if (!isExternalModuleNameRelative(typeReferenceDirectiveName)) { - const searchResult = loadModuleFromNearestNodeModulesDirectory( - 4 /* Declaration */, - typeReferenceDirectiveName, - initialLocationForSecondaryLookup, - moduleResolutionState, - /*cache*/ - void 0, - /*redirectedReference*/ - void 0 - ); + const searchResult = loadModuleFromNearestNodeModulesDirectory(4 /* Declaration */, typeReferenceDirectiveName, initialLocationForSecondaryLookup, moduleResolutionState, /*cache*/ + void 0, /*redirectedReference*/ + void 0); result2 = searchResult && searchResult.value; } else { - const { path: candidate } = normalizePathForCJSResolution(initialLocationForSecondaryLookup, typeReferenceDirectiveName); - result2 = nodeLoadModuleByRelativeName( - 4 /* Declaration */, - candidate, - /*onlyRecordFailures*/ - false, - moduleResolutionState, - /*considerPackageJson*/ - true - ); + const { + path: candidate + } = normalizePathForCJSResolution(initialLocationForSecondaryLookup, typeReferenceDirectiveName); + result2 = nodeLoadModuleByRelativeName(4 /* Declaration */, candidate, /*onlyRecordFailures*/ + false, moduleResolutionState, /*considerPackageJson*/ + true); } } else if (traceEnabled) { trace(host, Diagnostics.Resolving_type_reference_directive_for_program_that_specifies_custom_typeRoots_skipping_lookup_in_node_modules_folder); @@ -39701,11 +37855,13 @@ ${lanes.join("\n")} } else if (options.resolvePackageJsonExports === false) { features &= ~8 /* Exports */; } + if (options.resolvePackageJsonImports) { features |= 2 /* Imports */; } else if (options.resolvePackageJsonImports === false) { features &= ~2 /* Imports */; } + return features; } function getConditions(options, resolutionMode) { @@ -39728,16 +37884,12 @@ ${lanes.join("\n")} } function resolvePackageNameToPackageJson(packageName, containingDirectory, options, host, cache) { const moduleResolutionState = getTemporaryModuleResolutionState(cache == null ? void 0 : cache.getPackageJsonInfoCache(), host, options); - return forEachAncestorDirectory(containingDirectory, (ancestorDirectory) => { + return forEachAncestorDirectory(containingDirectory, ancestorDirectory => { if (getBaseFileName(ancestorDirectory) !== "node_modules") { const nodeModulesFolder = combinePaths(ancestorDirectory, "node_modules"); const candidate = combinePaths(nodeModulesFolder, packageName); - return getPackageJsonInfo( - candidate, - /*onlyRecordFailures*/ - false, - moduleResolutionState - ); + return getPackageJsonInfo(candidate, /*onlyRecordFailures*/ + false, moduleResolutionState); } }); } @@ -39774,7 +37926,7 @@ ${lanes.join("\n")} return "" + value; } if (isArray(value)) { - return `[${(_a = value.map((e) => compilerOptionValueToString(e))) == null ? void 0 : _a.join(",")}]`; + return `[${(_a = value.map(e => compilerOptionValueToString(e))) == null ? void 0 : _a.join(",")}]`; } let str = "{"; for (const key in value) { @@ -39785,14 +37937,13 @@ ${lanes.join("\n")} return str + "}"; } function getKeyForCompilerOptions(options, affectingOptionDeclarations) { - return affectingOptionDeclarations.map((option) => compilerOptionValueToString(getCompilerOptionValue(options, option))).join("|") + `|${options.pathsBasePath}`; + return affectingOptionDeclarations.map(option => compilerOptionValueToString(getCompilerOptionValue(options, option))).join("|") + `|${options.pathsBasePath}`; } 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); + const redirectsMap = /* @__PURE__ */new Map(); + const redirectsKeyToMap = /* @__PURE__ */new Map(); + let ownMap = /* @__PURE__ */new Map(); + if (ownOptions) redirectsMap.set(ownOptions, ownMap); return { getMapOfCacheRedirects, getOrCreateMapOfCacheRedirects, @@ -39801,53 +37952,35 @@ ${lanes.join("\n")} getOwnMap: () => ownMap }; function getMapOfCacheRedirects(redirectedReference) { - return redirectedReference ? getOrCreateMap( - redirectedReference.commandLine.options, - /*create*/ - false - ) : ownMap; + return redirectedReference ? getOrCreateMap(redirectedReference.commandLine.options, /*create*/ + false) : ownMap; } function getOrCreateMapOfCacheRedirects(redirectedReference) { - return redirectedReference ? getOrCreateMap( - redirectedReference.commandLine.options, - /*create*/ - true - ) : ownMap; + return redirectedReference ? getOrCreateMap(redirectedReference.commandLine.options, /*create*/ + true) : ownMap; } 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) { + var _result2; if (ownOptions) { const ownKey = getRedirectsCacheKey(ownOptions); - if (ownKey === key) - result = ownMap; - else if (!redirectsKeyToMap.has(ownKey)) - redirectsKeyToMap.set(ownKey, ownMap); + 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 (create) (_result2 = result) !== null && _result2 !== void 0 ? _result2 : result = /* @__PURE__ */new Map(); + if (result) redirectsKeyToMap.set(key, result); } - if (result) - redirectsMap.set(redirectOptions, result); + if (result) redirectsMap.set(redirectOptions, result); return result; } function clear2() { @@ -39857,8 +37990,7 @@ ${lanes.join("\n")} optionsToRedirectsKey.clear(); redirectsKeyToMap.clear(); if (ownOptions) { - if (ownKey) - optionsToRedirectsKey.set(ownOptions, ownKey); + if (ownKey) optionsToRedirectsKey.set(ownOptions, ownKey); redirectsMap.set(ownOptions, ownMap); } } @@ -39872,12 +38004,18 @@ ${lanes.join("\n")} } function createPackageJsonInfoCache(currentDirectory, getCanonicalFileName) { let cache; - return { getPackageJsonInfo: getPackageJsonInfo2, setPackageJsonInfo, clear: clear2, entries, getInternalMap }; + return { + getPackageJsonInfo: getPackageJsonInfo2, + setPackageJsonInfo, + clear: clear2, + entries, + getInternalMap + }; function getPackageJsonInfo2(packageJsonPath) { return cache == null ? void 0 : cache.get(toPath(packageJsonPath, currentDirectory, getCanonicalFileName)); } function setPackageJsonInfo(packageJsonPath, info) { - (cache || (cache = /* @__PURE__ */ new Map())).set(toPath(packageJsonPath, currentDirectory, getCanonicalFileName), info); + (cache || (cache = /* @__PURE__ */new Map())).set(toPath(packageJsonPath, currentDirectory, getCanonicalFileName), info); } function clear2() { cache = void 0; @@ -39928,8 +38066,8 @@ ${lanes.join("\n")} return mode === void 0 ? specifier : `${mode}|${specifier}`; } function createModeAwareCache() { - const underlying = /* @__PURE__ */ new Map(); - const memoizedReverseKeys = /* @__PURE__ */ new Map(); + const underlying = /* @__PURE__ */new Map(); + const memoizedReverseKeys = /* @__PURE__ */new Map(); const cache = { get(specifier, mode) { return underlying.get(getUnderlyingCacheKey(specifier, mode)); @@ -39992,8 +38130,11 @@ ${lanes.join("\n")} return getOrCreateCache(moduleNameToDirectoryMap, redirectedReference, createModeAwareCacheKey(nonRelativeModuleName, mode), createPerModuleNameCache); } function createPerModuleNameCache() { - const directoryPathMap = /* @__PURE__ */ new Map(); - return { get, set }; + const directoryPathMap = /* @__PURE__ */new Map(); + return { + get, + set + }; function get(directory) { return directoryPathMap.get(toPath(directory, currentDirectory, getCanonicalFileName)); } @@ -40038,21 +38179,11 @@ ${lanes.join("\n")} } } function createModuleOrTypeReferenceResolutionCache(currentDirectory, getCanonicalFileName, options, packageJsonInfoCache, getResolvedFileName, optionsToRedirectsKey) { - optionsToRedirectsKey ?? (optionsToRedirectsKey = /* @__PURE__ */ new Map()); - const perDirectoryResolutionCache = createPerDirectoryResolutionCache( - currentDirectory, - getCanonicalFileName, - options, - optionsToRedirectsKey - ); - const nonRelativeNameResolutionCache = createNonRelativeNameResolutionCache( - currentDirectory, - getCanonicalFileName, - options, - getResolvedFileName, - optionsToRedirectsKey - ); - packageJsonInfoCache ?? (packageJsonInfoCache = createPackageJsonInfoCache(currentDirectory, getCanonicalFileName)); + var _optionsToRedirectsKe, _packageJsonInfoCache; + (_optionsToRedirectsKe = optionsToRedirectsKey) !== null && _optionsToRedirectsKe !== void 0 ? _optionsToRedirectsKe : optionsToRedirectsKey = /* @__PURE__ */new Map(); + const perDirectoryResolutionCache = createPerDirectoryResolutionCache(currentDirectory, getCanonicalFileName, options, optionsToRedirectsKey); + const nonRelativeNameResolutionCache = createNonRelativeNameResolutionCache(currentDirectory, getCanonicalFileName, options, getResolvedFileName, optionsToRedirectsKey); + (_packageJsonInfoCache = packageJsonInfoCache) !== null && _packageJsonInfoCache !== void 0 ? _packageJsonInfoCache : packageJsonInfoCache = createPackageJsonInfoCache(currentDirectory, getCanonicalFileName); return { ...packageJsonInfoCache, ...perDirectoryResolutionCache, @@ -40077,42 +38208,26 @@ ${lanes.join("\n")} } } function createModuleResolutionCache(currentDirectory, getCanonicalFileName, options, packageJsonInfoCache, optionsToRedirectsKey) { - const result = createModuleOrTypeReferenceResolutionCache( - currentDirectory, - getCanonicalFileName, - options, - packageJsonInfoCache, - getOriginalOrResolvedModuleFileName, - optionsToRedirectsKey - ); + const result = createModuleOrTypeReferenceResolutionCache(currentDirectory, getCanonicalFileName, options, packageJsonInfoCache, getOriginalOrResolvedModuleFileName, optionsToRedirectsKey); result.getOrCreateCacheForModuleName = (nonRelativeName, mode, redirectedReference) => result.getOrCreateCacheForNonRelativeName(nonRelativeName, mode, redirectedReference); return result; } function createTypeReferenceDirectiveResolutionCache(currentDirectory, getCanonicalFileName, options, packageJsonInfoCache, optionsToRedirectsKey) { - return createModuleOrTypeReferenceResolutionCache( - currentDirectory, - getCanonicalFileName, - options, - packageJsonInfoCache, - getOriginalOrResolvedTypeReferenceFileName, - optionsToRedirectsKey - ); + return createModuleOrTypeReferenceResolutionCache(currentDirectory, getCanonicalFileName, options, packageJsonInfoCache, getOriginalOrResolvedTypeReferenceFileName, optionsToRedirectsKey); } function getOptionsForLibraryResolution(options) { - return { moduleResolution: 2 /* Node10 */, traceResolution: options.traceResolution }; + return { + moduleResolution: 2 /* Node10 */, + traceResolution: options.traceResolution + }; } function resolveLibrary(libraryName, resolveFrom, compilerOptions, host, cache) { return resolveModuleName(libraryName, resolveFrom, getOptionsForLibraryResolution(compilerOptions), host, cache); } function resolveModuleNameFromCache(moduleName, containingFile, cache, mode) { const containingDirectory = getDirectoryPath(containingFile); - return cache.getFromDirectoryCache( - moduleName, - mode, - containingDirectory, - /*redirectedReference*/ - void 0 - ); + return cache.getFromDirectoryCache(moduleName, mode, containingDirectory, /*redirectedReference*/ + void 0); } function resolveModuleName(moduleName, containingFile, compilerOptions, host, cache, redirectedReference, resolutionMode) { var _a, _b, _c; @@ -40177,8 +38292,7 @@ ${lanes.join("\n")} 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); @@ -40202,8 +38316,7 @@ ${lanes.join("\n")} } 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 { @@ -40212,7 +38325,11 @@ ${lanes.join("\n")} } function tryLoadModuleUsingPathsIfEligible(extensions, moduleName, loader, state) { var _a; - const { baseUrl, paths, configFile } = state.compilerOptions; + const { + baseUrl, + paths, + configFile + } = state.compilerOptions; if (paths && !pathIsRelative(moduleName)) { if (state.traceEnabled) { if (baseUrl) { @@ -40222,17 +38339,8 @@ ${lanes.join("\n")} } const baseDirectory = getPathsBasePath(state.compilerOptions, state.host); const pathPatterns = (configFile == null ? void 0 : configFile.configFileSpecs) ? (_a = configFile.configFileSpecs).pathPatterns || (_a.pathPatterns = tryParsePatterns(paths)) : void 0; - return tryLoadModuleUsingPaths( - extensions, - moduleName, - baseDirectory, - paths, - pathPatterns, - loader, - /*onlyRecordFailures*/ - false, - state - ); + return tryLoadModuleUsingPaths(extensions, moduleName, baseDirectory, paths, pathPatterns, loader, /*onlyRecordFailures*/ + false, state); } } function tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, state) { @@ -40295,7 +38403,9 @@ ${lanes.join("\n")} return void 0; } function tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, state) { - const { baseUrl } = state.compilerOptions; + const { + baseUrl + } = state.compilerOptions; if (!baseUrl) { return void 0; } @@ -40309,35 +38419,20 @@ ${lanes.join("\n")} return loader(extensions, candidate, !directoryProbablyExists(getDirectoryPath(candidate), state.host), state); } function resolveJSModule(moduleName, initialDir, host) { - const { resolvedModule, failedLookupLocations } = tryResolveJSModuleWorker(moduleName, initialDir, host); + const { + resolvedModule, + failedLookupLocations + } = tryResolveJSModuleWorker(moduleName, initialDir, host); if (!resolvedModule) { throw new Error(`Could not resolve JS module '${moduleName}' starting at '${initialDir}'. Looked in: ${failedLookupLocations == null ? void 0 : failedLookupLocations.join(", ")}`); } return resolvedModule.resolvedFileName; } function node16ModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference, resolutionMode) { - return nodeNextModuleNameResolverWorker( - 30 /* Node16Default */, - moduleName, - containingFile, - compilerOptions, - host, - cache, - redirectedReference, - resolutionMode - ); + return nodeNextModuleNameResolverWorker(30 /* Node16Default */, moduleName, containingFile, compilerOptions, host, cache, redirectedReference, resolutionMode); } function nodeNextModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference, resolutionMode) { - return nodeNextModuleNameResolverWorker( - 30 /* NodeNextDefault */, - moduleName, - containingFile, - compilerOptions, - host, - cache, - redirectedReference, - resolutionMode - ); + return nodeNextModuleNameResolverWorker(30 /* NodeNextDefault */, moduleName, containingFile, compilerOptions, host, cache, redirectedReference, resolutionMode); } function nodeNextModuleNameResolverWorker(features, moduleName, containingFile, compilerOptions, host, cache, redirectedReference, resolutionMode, conditions) { const containingDirectory = getDirectoryPath(containingFile); @@ -40346,37 +38441,19 @@ ${lanes.join("\n")} if (getResolveJsonModule(compilerOptions)) { extensions |= 8 /* Json */; } - return nodeModuleNameResolverWorker( - features | esmMode, - moduleName, - containingDirectory, - compilerOptions, - host, - cache, - extensions, - /*isConfigLookup*/ - false, - redirectedReference, - conditions - ); + + return nodeModuleNameResolverWorker(features | esmMode, moduleName, containingDirectory, compilerOptions, host, cache, extensions, /*isConfigLookup*/ + false, redirectedReference, conditions); } function tryResolveJSModuleWorker(moduleName, initialDir, host) { - return nodeModuleNameResolverWorker( - 0 /* None */, - moduleName, - initialDir, - { moduleResolution: 2 /* Node10 */, allowJs: true }, - host, - /*cache*/ - void 0, - 2 /* JavaScript */, - /*isConfigLookup*/ - false, - /*redirectedReference*/ - void 0, - /*conditions*/ - void 0 - ); + return nodeModuleNameResolverWorker(0 /* None */, moduleName, initialDir, { + moduleResolution: 2 /* Node10 */, + allowJs: true + }, host, /*cache*/ + void 0, 2 /* JavaScript */, /*isConfigLookup*/ + false, /*redirectedReference*/ + void 0, /*conditions*/ + void 0); } function bundlerModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference, conditions) { const containingDirectory = getDirectoryPath(containingFile); @@ -40384,19 +38461,9 @@ ${lanes.join("\n")} if (getResolveJsonModule(compilerOptions)) { extensions |= 8 /* Json */; } - return nodeModuleNameResolverWorker( - getNodeResolutionFeatures(compilerOptions), - moduleName, - containingDirectory, - compilerOptions, - host, - cache, - extensions, - /*isConfigLookup*/ - false, - redirectedReference, - conditions - ); + + return nodeModuleNameResolverWorker(getNodeResolutionFeatures(compilerOptions), moduleName, containingDirectory, compilerOptions, host, cache, extensions, /*isConfigLookup*/ + false, redirectedReference, conditions); } function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference, conditions, isConfigLookup) { let extensions; @@ -40404,41 +38471,31 @@ ${lanes.join("\n")} 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 */; } + return nodeModuleNameResolverWorker(conditions ? 30 /* AllFeatures */ : 0 /* None */, moduleName, getDirectoryPath(containingFile), compilerOptions, host, cache, extensions, !!isConfigLookup, redirectedReference, conditions); } function nodeNextJsonConfigResolver(moduleName, containingFile, host) { - return nodeModuleNameResolverWorker( - 30 /* NodeNextDefault */, - moduleName, - getDirectoryPath(containingFile), - { moduleResolution: 99 /* NodeNext */ }, - host, - /*cache*/ - void 0, - 8 /* Json */, - /*isConfigLookup*/ - true, - /*redirectedReference*/ - void 0, - /*conditions*/ - void 0 - ); + return nodeModuleNameResolverWorker(30 /* NodeNextDefault */, moduleName, getDirectoryPath(containingFile), { + moduleResolution: 99 /* NodeNext */ + }, host, /*cache*/ + void 0, 8 /* Json */, /*isConfigLookup*/ + true, /*redirectedReference*/ + void 0, /*conditions*/ + void 0); } function nodeModuleNameResolverWorker(features, moduleName, containingDirectory, compilerOptions, host, cache, extensions, isConfigLookup, redirectedReference, conditions) { + var _conditions, _conditions2; var _a, _b, _c, _d; const traceEnabled = isTraceEnabled(compilerOptions, host); const failedLookupLocations = []; const affectingLocations = []; const moduleResolution = getEmitModuleResolutionKind(compilerOptions); - conditions ?? (conditions = getConditions( - compilerOptions, - moduleResolution === 100 /* Bundler */ || moduleResolution === 2 /* Node10 */ ? void 0 : features & 32 /* EsmMode */ ? 99 /* ESNext */ : 1 /* CommonJS */ - )); + (_conditions = conditions) !== null && _conditions !== void 0 ? _conditions : conditions = getConditions(compilerOptions, moduleResolution === 100 /* Bundler */ || moduleResolution === 2 /* Node10 */ ? void 0 : features & 32 /* EsmMode */ ? 99 /* ESNext */ : 1 /* CommonJS */); + const diagnostics = []; const state = { compilerOptions, @@ -40448,14 +38505,14 @@ ${lanes.join("\n")} affectingLocations, packageJsonInfoCache: cache, features, - conditions: conditions ?? emptyArray, + conditions: (_conditions2 = conditions) !== null && _conditions2 !== void 0 ? _conditions2 : emptyArray, requestContainingDirectory: containingDirectory, - reportDiagnostic: (diag2) => void diagnostics.push(diag2), + reportDiagnostic: diag2 => void diagnostics.push(diag2), isConfigLookup, candidateIsFromPackageJsonField: false }; if (traceEnabled && moduleResolutionSupportsPackageJsonExportsAndImports(moduleResolution)) { - trace(host, Diagnostics.Resolving_in_0_mode_with_conditions_1, features & 32 /* EsmMode */ ? "ESM" : "CJS", state.conditions.map((c) => `'${c}'`).join(", ")); + trace(host, Diagnostics.Resolving_in_0_mode_with_conditions_1, features & 32 /* EsmMode */ ? "ESM" : "CJS", state.conditions.map(c => `'${c}'`).join(", ")); } let result; if (moduleResolution === 2 /* Node10 */) { @@ -40478,29 +38535,16 @@ ${lanes.join("\n")} legacyResult = diagnosticResult.value.resolved.path; } } - return createResolvedModuleWithFailedLookupLocationsHandlingSymlink( - moduleName, - (_c = result == null ? void 0 : result.value) == null ? void 0 : _c.resolved, - (_d = result == null ? void 0 : result.value) == null ? void 0 : _d.isExternalLibraryImport, - failedLookupLocations, - affectingLocations, - diagnostics, - state, - cache, - legacyResult - ); + return createResolvedModuleWithFailedLookupLocationsHandlingSymlink(moduleName, (_c = result == null ? void 0 : result.value) == null ? void 0 : _c.resolved, (_d = result == null ? void 0 : result.value) == null ? void 0 : _d.isExternalLibraryImport, failedLookupLocations, affectingLocations, diagnostics, state, cache, legacyResult); function tryResolve(extensions2, state2) { - const loader = (extensions3, candidate, onlyRecordFailures, state3) => nodeLoadModuleByRelativeName( - extensions3, - candidate, - onlyRecordFailures, - state3, - /*considerPackageJson*/ - true - ); + const loader = (extensions3, candidate, onlyRecordFailures, state3) => nodeLoadModuleByRelativeName(extensions3, candidate, onlyRecordFailures, state3, /*considerPackageJson*/ + true); const resolved = tryLoadModuleUsingOptionalResolutionSettings(extensions2, moduleName, containingDirectory, loader, state2); if (resolved) { - return toSearchResult({ resolved, isExternalLibraryImport: pathContainsNodeModules(resolved.path) }); + return toSearchResult({ + resolved, + isExternalLibraryImport: pathContainsNodeModules(resolved.path) + }); } if (!isExternalModuleNameRelative(moduleName)) { let resolved2; @@ -40523,21 +38567,27 @@ ${lanes.join("\n")} resolved2 = loadModuleFromNearestNodeModulesDirectory(extensions2, moduleName, containingDirectory, state2, cache, redirectedReference); } if (extensions2 & 4 /* Declaration */) { - resolved2 ?? (resolved2 = resolveFromTypeRoot(moduleName, state2)); + var _resolved; + (_resolved = resolved2) !== null && _resolved !== void 0 ? _resolved : resolved2 = resolveFromTypeRoot(moduleName, state2); } - return resolved2 && { value: resolved2.value && { resolved: resolved2.value, isExternalLibraryImport: true } }; + return resolved2 && { + value: resolved2.value && { + resolved: resolved2.value, + isExternalLibraryImport: true + } + }; } else { - const { path: candidate, parts } = normalizePathForCJSResolution(containingDirectory, moduleName); - const resolved2 = nodeLoadModuleByRelativeName( - extensions2, - candidate, - /*onlyRecordFailures*/ - false, - state2, - /*considerPackageJson*/ - true - ); - return resolved2 && toSearchResult({ resolved: resolved2, isExternalLibraryImport: contains(parts, "node_modules") }); + const { + path: candidate, + parts + } = normalizePathForCJSResolution(containingDirectory, moduleName); + const resolved2 = nodeLoadModuleByRelativeName(extensions2, candidate, /*onlyRecordFailures*/ + false, state2, /*considerPackageJson*/ + true); + return resolved2 && toSearchResult({ + resolved: resolved2, + isExternalLibraryImport: contains(parts, "node_modules") + }); } } } @@ -40546,7 +38596,10 @@ ${lanes.join("\n")} const parts = getPathComponents(combined); const lastPart = lastOrUndefined(parts); const path = lastPart === "." || lastPart === ".." ? ensureTrailingDirectorySeparator(normalizePath(combined)) : normalizePath(combined); - return { path, parts }; + return { + path, + parts + }; } function realPath(path, host, traceEnabled) { if (!host.realpath) { @@ -40575,12 +38628,8 @@ ${lanes.join("\n")} const resolvedFromFile = loadModuleFromFile(extensions, candidate, onlyRecordFailures, state); if (resolvedFromFile) { const packageDirectory = considerPackageJson ? parseNodeModuleFromPath(resolvedFromFile.path) : void 0; - const packageInfo = packageDirectory ? getPackageJsonInfo( - packageDirectory, - /*onlyRecordFailures*/ - false, - state - ) : void 0; + const packageInfo = packageDirectory ? getPackageJsonInfo(packageDirectory, /*onlyRecordFailures*/ + false, state) : void 0; return withPackageId(packageInfo, resolvedFromFile); } } @@ -40651,11 +38700,19 @@ ${lanes.join("\n")} function loadFileNameFromPackageJsonField(extensions, candidate, onlyRecordFailures, state) { if (extensions & 1 /* TypeScript */ && fileExtensionIsOneOf(candidate, supportedTSImplementationExtensions) || extensions & 4 /* Declaration */ && fileExtensionIsOneOf(candidate, supportedDeclarationExtensions)) { const result = tryFile(candidate, onlyRecordFailures, state); - return result !== void 0 ? { path: candidate, ext: tryExtractTSExtension(candidate), resolvedUsingTsExtension: void 0 } : void 0; + return result !== void 0 ? { + path: candidate, + ext: tryExtractTSExtension(candidate), + resolvedUsingTsExtension: void 0 + } : void 0; } if (state.isConfigLookup && extensions === 8 /* Json */ && fileExtensionIs(candidate, ".json" /* Json */)) { const result = tryFile(candidate, onlyRecordFailures, state); - return result !== void 0 ? { path: candidate, ext: ".json" /* Json */, resolvedUsingTsExtension: void 0 } : void 0; + return result !== void 0 ? { + path: candidate, + ext: ".json" /* Json */, + resolvedUsingTsExtension: void 0 + } : void 0; } return loadModuleFromFileNoImplicitExtensions(extensions, candidate, onlyRecordFailures, state); } @@ -40690,17 +38747,22 @@ ${lanes.join("\n")} } function tryExtension(ext, resolvedUsingTsExtension) { const path = tryFile(candidate + ext, onlyRecordFailures, state); - return path === void 0 ? void 0 : { path, ext, resolvedUsingTsExtension: !state.candidateIsFromPackageJsonField && resolvedUsingTsExtension }; + return path === void 0 ? void 0 : { + path, + ext, + resolvedUsingTsExtension: !state.candidateIsFromPackageJsonField && resolvedUsingTsExtension + }; } } function tryFile(fileName, onlyRecordFailures, state) { + var _tryGetExtensionFromP; var _a; if (!((_a = state.compilerOptions.moduleSuffixes) == null ? void 0 : _a.length)) { return tryFileLookup(fileName, onlyRecordFailures, state); } - const ext = tryGetExtensionFromPath2(fileName) ?? ""; + const ext = (_tryGetExtensionFromP = tryGetExtensionFromPath2(fileName)) !== null && _tryGetExtensionFromP !== void 0 ? _tryGetExtensionFromP : ""; const fileNameNoExtension = ext ? removeExtension(fileName, ext) : fileName; - return forEach(state.compilerOptions.moduleSuffixes, (suffix) => tryFileLookup(fileNameNoExtension + suffix + ext, onlyRecordFailures, state)); + return forEach(state.compilerOptions.moduleSuffixes, suffix => tryFileLookup(fileNameNoExtension + suffix + ext, onlyRecordFailures, state)); } function tryFileLookup(fileName, onlyRecordFailures, state) { var _a; @@ -40735,29 +38797,19 @@ ${lanes.join("\n")} const loadPackageJsonMainState = getTemporaryModuleResolutionState(cache == null ? void 0 : cache.getPackageJsonInfoCache(), host, options); loadPackageJsonMainState.conditions = getConditions(options); loadPackageJsonMainState.requestContainingDirectory = packageJsonInfo.packageDirectory; - const mainResolution = loadNodeModuleFromDirectoryWorker( - extensions, - packageJsonInfo.packageDirectory, - /*onlyRecordFailures*/ - false, - loadPackageJsonMainState, - packageJsonInfo.contents.packageJsonContent, - getVersionPathsOfPackageJsonInfo(packageJsonInfo, loadPackageJsonMainState) - ); + const mainResolution = loadNodeModuleFromDirectoryWorker(extensions, packageJsonInfo.packageDirectory, /*onlyRecordFailures*/ + false, loadPackageJsonMainState, packageJsonInfo.contents.packageJsonContent, getVersionPathsOfPackageJsonInfo(packageJsonInfo, loadPackageJsonMainState)); entrypoints = append(entrypoints, mainResolution == null ? void 0 : mainResolution.path); if (features & 8 /* Exports */ && packageJsonInfo.contents.packageJsonContent.exports) { - const conditionSets = deduplicate( - [getConditions(options, 99 /* ESNext */), getConditions(options, 1 /* CommonJS */)], - arrayIsEqualTo - ); + const conditionSets = deduplicate([getConditions(options, 99 /* ESNext */), getConditions(options, 1 /* CommonJS */)], arrayIsEqualTo); for (const conditions of conditionSets) { - const loadPackageJsonExportsState = { ...loadPackageJsonMainState, failedLookupLocations: [], conditions, host }; - const exportResolutions = loadEntrypointsFromExportMap( - packageJsonInfo, - packageJsonInfo.contents.packageJsonContent.exports, - loadPackageJsonExportsState, - extensions - ); + const loadPackageJsonExportsState = { + ...loadPackageJsonMainState, + failedLookupLocations: [], + conditions, + host + }; + const exportResolutions = loadEntrypointsFromExportMap(packageJsonInfo, packageJsonInfo.contents.packageJsonContent.exports, loadPackageJsonExportsState, extensions); if (exportResolutions) { for (const resolution of exportResolutions) { entrypoints = appendIfUnique(entrypoints, resolution.path); @@ -40788,15 +38840,8 @@ ${lanes.join("\n")} if (target.indexOf("*") !== target.lastIndexOf("*")) { return false; } - state.host.readDirectory( - scope.packageDirectory, - extensionsToExtensionsArray(extensions), - /*excludes*/ - void 0, - [ - isDeclarationFileName(target) ? target.replace("*", "**/*") : changeAnyExtension(target.replace("*", "**/*"), getDeclarationEmitExtensionForPath(target)) - ] - ).forEach((entry) => { + state.host.readDirectory(scope.packageDirectory, extensionsToExtensionsArray(extensions), /*excludes*/ + void 0, [isDeclarationFileName(target) ? target.replace("*", "**/*") : changeAnyExtension(target.replace("*", "**/*"), getDeclarationEmitExtensionForPath(target))]).forEach(entry => { entrypoints = appendIfUnique(entrypoints, { path: entry, ext: getAnyExtensionFromPath(entry), @@ -40810,13 +38855,8 @@ ${lanes.join("\n")} } const resolvedTarget = combinePaths(scope.packageDirectory, target); const finalPath = getNormalizedAbsolutePath(resolvedTarget, (_b = (_a = state.host).getCurrentDirectory) == null ? void 0 : _b.call(_a)); - const result = loadFileNameFromPackageJsonField( - extensions, - finalPath, - /*onlyRecordFailures*/ - false, - state - ); + const result = loadFileNameFromPackageJsonField(extensions, finalPath, /*onlyRecordFailures*/ + false, state); if (result) { entrypoints = appendIfUnique(entrypoints, result, (a, b) => a.path === b.path); return true; @@ -40830,7 +38870,7 @@ ${lanes.join("\n")} } } } else if (typeof target === "object" && target !== null) { - return forEach(getOwnKeys(target), (key) => { + return forEach(getOwnKeys(target), key => { if (key === "default" || contains(state.conditions, key) || isApplicableVersionedTypesKey(state.conditions, key)) { loadEntrypointsFromTargetExports(target[key]); return true; @@ -40859,12 +38899,8 @@ ${lanes.join("\n")} const parts = getPathComponents(fileName); parts.pop(); while (parts.length > 0) { - const pkg = getPackageJsonInfo( - getPathFromPathComponents(parts), - /*onlyRecordFailures*/ - false, - state - ); + const pkg = getPackageJsonInfo(getPathFromPathComponents(parts), /*onlyRecordFailures*/ + false, state); if (pkg) { return pkg; } @@ -40880,7 +38916,10 @@ ${lanes.join("\n")} } function getPackageJsonInfo(packageDirectory, onlyRecordFailures, state) { var _a, _b, _c, _d, _e, _f; - const { host, traceEnabled } = state; + const { + host, + traceEnabled + } = state; const packageJsonPath = combinePaths(packageDirectory, "package.json"); if (onlyRecordFailures) { (_a = state.failedLookupLocations) == null ? void 0 : _a.push(packageJsonPath); @@ -40889,13 +38928,14 @@ ${lanes.join("\n")} const existing = (_b = state.packageJsonInfoCache) == null ? void 0 : _b.getPackageJsonInfo(packageJsonPath); if (existing !== void 0) { if (typeof existing !== "boolean") { - if (traceEnabled) - trace(host, Diagnostics.File_0_exists_according_to_earlier_cached_lookups, packageJsonPath); + 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 }; + return existing.packageDirectory === packageDirectory ? existing : { + packageDirectory, + contents: existing.contents + }; } else { - if (existing && traceEnabled) - trace(host, Diagnostics.File_0_does_not_exist_according_to_earlier_cached_lookups, packageJsonPath); + if (existing && 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; } @@ -40906,17 +38946,22 @@ ${lanes.join("\n")} if (traceEnabled) { trace(host, Diagnostics.Found_package_json_at_0, packageJsonPath); } - const result = { packageDirectory, contents: { packageJsonContent, versionPaths: void 0, resolvedEntrypoints: void 0 } }; - if (state.packageJsonInfoCache && !state.packageJsonInfoCache.isReadonly) - state.packageJsonInfoCache.setPackageJsonInfo(packageJsonPath, result); + const result = { + packageDirectory, + contents: { + packageJsonContent, + versionPaths: void 0, + resolvedEntrypoints: void 0 + } + }; + 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, directoryExists); + if (state.packageJsonInfoCache && !state.packageJsonInfoCache.isReadonly) state.packageJsonInfoCache.setPackageJsonInfo(packageJsonPath, directoryExists); (_f = state.failedLookupLocations) == null ? void 0 : _f.push(packageJsonPath); } } @@ -40947,14 +38992,9 @@ ${lanes.join("\n")} if ((jsonContent == null ? void 0 : jsonContent.type) !== "module") { state2.features &= ~32 /* EsmMode */; } - const result = nodeLoadModuleByRelativeName( - expandedExtensions, - candidate2, - onlyRecordFailures2, - state2, - /*considerPackageJson*/ - false - ); + + const result = nodeLoadModuleByRelativeName(expandedExtensions, candidate2, onlyRecordFailures2, state2, /*considerPackageJson*/ + false); state2.features = features; state2.candidateIsFromPackageJsonField = candidateIsFromPackageJsonField; return result; @@ -40963,40 +39003,30 @@ ${lanes.join("\n")} const onlyRecordFailuresForIndex = onlyRecordFailures || !directoryProbablyExists(candidate, state.host); const indexPath = combinePaths(candidate, state.isConfigLookup ? "tsconfig" : "index"); if (versionPaths && (!packageFile || containsPath(candidate, packageFile))) { - const moduleName = getRelativePathFromDirectory( - candidate, - packageFile || indexPath, - /*ignoreCase*/ - false - ); + const moduleName = getRelativePathFromDirectory(candidate, packageFile || indexPath, /*ignoreCase*/ + false); if (state.traceEnabled) { trace(state.host, Diagnostics.package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2, versionPaths.version, version, moduleName); } - const result = tryLoadModuleUsingPaths( - extensions, - moduleName, - candidate, - versionPaths.paths, - /*pathPatterns*/ - void 0, - loader, - onlyRecordFailuresForPackageFile || onlyRecordFailuresForIndex, - state - ); + const result = tryLoadModuleUsingPaths(extensions, moduleName, candidate, versionPaths.paths, /*pathPatterns*/ + void 0, loader, onlyRecordFailuresForPackageFile || onlyRecordFailuresForIndex, state); if (result) { return removeIgnoredPackageId(result.value); } } 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); } } function resolvedIfExtensionMatches(extensions, path, resolvedUsingTsExtension) { const ext = tryGetExtensionFromPath2(path); - return ext !== void 0 && extensionIsOk(extensions, ext) ? { path, ext, resolvedUsingTsExtension } : void 0; + return ext !== void 0 && extensionIsOk(extensions, ext) ? { + path, + ext, + resolvedUsingTsExtension + } : void 0; } function extensionIsOk(extensions, extension) { return extensions & 2 /* JavaScript */ && (extension === ".js" /* Js */ || extension === ".jsx" /* Jsx */ || extension === ".mjs" /* Mjs */ || extension === ".cjs" /* Cjs */) || extensions & 1 /* TypeScript */ && (extension === ".ts" /* Ts */ || extension === ".tsx" /* Tsx */ || extension === ".mts" /* Mts */ || extension === ".cts" /* Cts */) || extensions & 4 /* Declaration */ && (extension === ".d.ts" /* Dts */ || extension === ".d.mts" /* Dmts */ || extension === ".d.cts" /* Dcts */) || extensions & 8 /* Json */ && extension === ".json" /* Json */ || false; @@ -41006,13 +39036,19 @@ ${lanes.join("\n")} if (moduleName[0] === "@") { idx = moduleName.indexOf(directorySeparator, idx + 1); } - return idx === -1 ? { packageName: moduleName, rest: "" } : { packageName: moduleName.slice(0, idx), rest: moduleName.slice(idx + 1) }; + return idx === -1 ? { + packageName: moduleName, + rest: "" + } : { + packageName: moduleName.slice(0, idx), + rest: moduleName.slice(idx + 1) + }; } function allKeysStartWithDot(obj) { - return every(getOwnKeys(obj), (k) => startsWith(k, ".")); + return every(getOwnKeys(obj), k => startsWith(k, ".")); } function noKeyStartsWithDot(obj) { - return !some(getOwnKeys(obj), (k) => startsWith(k, ".")); + return !some(getOwnKeys(obj), k => startsWith(k, ".")); } function loadModuleFromSelfNameReference(extensions, moduleName, directory, state, cache, redirectedReference) { var _a, _b; @@ -41050,45 +39086,21 @@ ${lanes.join("\n")} mainExport = scope.contents.packageJsonContent.exports["."]; } if (mainExport) { - const loadModuleFromTargetImportOrExport = getLoadModuleFromTargetImportOrExport( - extensions, - state, - cache, - redirectedReference, - subpath, - scope, - /*isImports*/ - false - ); - return loadModuleFromTargetImportOrExport( - mainExport, - "", - /*pattern*/ - false, - "." - ); + const loadModuleFromTargetImportOrExport = getLoadModuleFromTargetImportOrExport(extensions, state, cache, redirectedReference, subpath, scope, /*isImports*/ + false); + return loadModuleFromTargetImportOrExport(mainExport, "", /*pattern*/ + false, "."); } } else if (allKeysStartWithDot(scope.contents.packageJsonContent.exports)) { if (typeof scope.contents.packageJsonContent.exports !== "object") { if (state.traceEnabled) { trace(state.host, Diagnostics.Export_specifier_0_does_not_exist_in_package_json_scope_at_path_1, subpath, scope.packageDirectory); } - return toSearchResult( - /*value*/ - void 0 - ); + return toSearchResult( /*value*/ + void 0); } - const result = loadModuleFromImportsOrExports( - extensions, - state, - cache, - redirectedReference, - subpath, - scope.contents.packageJsonContent.exports, - scope, - /*isImports*/ - false - ); + const result = loadModuleFromImportsOrExports(extensions, state, cache, redirectedReference, subpath, scope.contents.packageJsonContent.exports, scope, /*isImports*/ + false); if (result) { return result; } @@ -41096,10 +39108,8 @@ ${lanes.join("\n")} if (state.traceEnabled) { trace(state.host, Diagnostics.Export_specifier_0_does_not_exist_in_package_json_scope_at_path_1, subpath, scope.packageDirectory); } - return toSearchResult( - /*value*/ - void 0 - ); + return toSearchResult( /*value*/ + void 0); } function loadModuleFromImports(extensions, moduleName, directory, state, cache, redirectedReference) { var _a, _b; @@ -41107,10 +39117,8 @@ ${lanes.join("\n")} if (state.traceEnabled) { trace(state.host, Diagnostics.Invalid_import_specifier_0_has_no_possible_resolutions, moduleName); } - return toSearchResult( - /*value*/ - void 0 - ); + return toSearchResult( /*value*/ + void 0); } const directoryPath = getNormalizedAbsolutePath(combinePaths(directory, "dummy"), (_b = (_a = state.host).getCurrentDirectory) == null ? void 0 : _b.call(_a)); const scope = getPackageScopeForPath(directoryPath, state); @@ -41118,115 +39126,72 @@ ${lanes.join("\n")} if (state.traceEnabled) { trace(state.host, Diagnostics.Directory_0_has_no_containing_package_json_scope_Imports_will_not_resolve, directoryPath); } - return toSearchResult( - /*value*/ - void 0 - ); + return toSearchResult( /*value*/ + void 0); } if (!scope.contents.packageJsonContent.imports) { if (state.traceEnabled) { trace(state.host, Diagnostics.package_json_scope_0_has_no_imports_defined, scope.packageDirectory); } - return toSearchResult( - /*value*/ - void 0 - ); + return toSearchResult( /*value*/ + void 0); } - const result = loadModuleFromImportsOrExports( - extensions, - state, - cache, - redirectedReference, - moduleName, - scope.contents.packageJsonContent.imports, - scope, - /*isImports*/ - true - ); + const result = loadModuleFromImportsOrExports(extensions, state, cache, redirectedReference, moduleName, scope.contents.packageJsonContent.imports, scope, /*isImports*/ + true); if (result) { return result; } if (state.traceEnabled) { trace(state.host, Diagnostics.Import_specifier_0_does_not_exist_in_package_json_scope_at_path_1, moduleName, scope.packageDirectory); } - return toSearchResult( - /*value*/ - void 0 - ); + return toSearchResult( /*value*/ + void 0); } function comparePatternKeys(a, b) { const aPatternIndex = a.indexOf("*"); 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) { const loadModuleFromTargetImportOrExport = getLoadModuleFromTargetImportOrExport(extensions, state, cache, redirectedReference, moduleName, scope, isImports); if (!endsWith(moduleName, directorySeparator) && !moduleName.includes("*") && hasProperty(lookupTable, moduleName)) { const target = lookupTable[moduleName]; - return loadModuleFromTargetImportOrExport( - target, - /*subpath*/ - "", - /*pattern*/ - false, - moduleName - ); + return loadModuleFromTargetImportOrExport(target, /*subpath*/ + "", /*pattern*/ + false, moduleName); } - const expandingKeys = sort(filter(getOwnKeys(lookupTable), (k) => k.includes("*") || endsWith(k, "/")), comparePatternKeys); + const expandingKeys = sort(filter(getOwnKeys(lookupTable), k => k.includes("*") || endsWith(k, "/")), comparePatternKeys); for (const potentialTarget of expandingKeys) { if (state.features & 16 /* ExportsPatternTrailers */ && matchesPatternWithTrailer(potentialTarget, moduleName)) { const target = lookupTable[potentialTarget]; const starPos = potentialTarget.indexOf("*"); const subpath = moduleName.substring(potentialTarget.substring(0, starPos).length, moduleName.length - (potentialTarget.length - 1 - starPos)); - return loadModuleFromTargetImportOrExport( - target, - subpath, - /*pattern*/ - true, - potentialTarget - ); + return loadModuleFromTargetImportOrExport(target, subpath, /*pattern*/ + true, potentialTarget); } else if (endsWith(potentialTarget, "*") && startsWith(moduleName, potentialTarget.substring(0, potentialTarget.length - 1))) { const target = lookupTable[potentialTarget]; const subpath = moduleName.substring(potentialTarget.length - 1); - return loadModuleFromTargetImportOrExport( - target, - subpath, - /*pattern*/ - true, - potentialTarget - ); + return loadModuleFromTargetImportOrExport(target, subpath, /*pattern*/ + true, potentialTarget); } else if (startsWith(moduleName, potentialTarget)) { const target = lookupTable[potentialTarget]; const subpath = moduleName.substring(potentialTarget.length); - return loadModuleFromTargetImportOrExport( - target, - subpath, - /*pattern*/ - false, - potentialTarget - ); + return loadModuleFromTargetImportOrExport(target, subpath, /*pattern*/ + false, potentialTarget); } } 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)); } } @@ -41238,46 +39203,29 @@ ${lanes.join("\n")} if (state.traceEnabled) { trace(state.host, Diagnostics.package_json_scope_0_has_invalid_type_for_target_of_specifier_1, scope.packageDirectory, moduleName); } - return toSearchResult( - /*value*/ - void 0 - ); + return toSearchResult( /*value*/ + void 0); } if (!startsWith(target, "./")) { if (isImports && !startsWith(target, "../") && !startsWith(target, "/") && !isRootedDiskPath(target)) { const combinedLookup = pattern ? target.replace(/\*/g, subpath) : target + subpath; traceIfEnabled(state, Diagnostics.Using_0_subpath_1_with_target_2, "imports", key, combinedLookup); traceIfEnabled(state, Diagnostics.Resolving_module_0_from_1, combinedLookup, scope.packageDirectory + "/"); - const result = nodeModuleNameResolverWorker( - state.features, - combinedLookup, - scope.packageDirectory + "/", - state.compilerOptions, - state.host, - cache, - extensions, - /*isConfigLookup*/ - false, - redirectedReference, - state.conditions - ); - return toSearchResult( - result.resolvedModule ? { - path: result.resolvedModule.resolvedFileName, - extension: result.resolvedModule.extension, - packageId: result.resolvedModule.packageId, - originalPath: result.resolvedModule.originalPath, - resolvedUsingTsExtension: result.resolvedModule.resolvedUsingTsExtension - } : void 0 - ); + const result = nodeModuleNameResolverWorker(state.features, combinedLookup, scope.packageDirectory + "/", state.compilerOptions, state.host, cache, extensions, /*isConfigLookup*/ + false, redirectedReference, state.conditions); + return toSearchResult(result.resolvedModule ? { + path: result.resolvedModule.resolvedFileName, + extension: result.resolvedModule.extension, + packageId: result.resolvedModule.packageId, + originalPath: result.resolvedModule.originalPath, + resolvedUsingTsExtension: result.resolvedModule.resolvedUsingTsExtension + } : void 0); } if (state.traceEnabled) { trace(state.host, Diagnostics.package_json_scope_0_has_invalid_type_for_target_of_specifier_1, scope.packageDirectory, moduleName); } - return toSearchResult( - /*value*/ - void 0 - ); + return toSearchResult( /*value*/ + void 0); } const parts = pathIsRelative(target) ? getPathComponents(target).slice(1) : getPathComponents(target); const partsAfterFirst = parts.slice(1); @@ -41285,10 +39233,8 @@ ${lanes.join("\n")} if (state.traceEnabled) { trace(state.host, Diagnostics.package_json_scope_0_has_invalid_type_for_target_of_specifier_1, scope.packageDirectory, moduleName); } - return toSearchResult( - /*value*/ - void 0 - ); + return toSearchResult( /*value*/ + void 0); } const resolvedTarget = combinePaths(scope.packageDirectory, target); const subpathParts = getPathComponents(subpath); @@ -41296,25 +39242,17 @@ ${lanes.join("\n")} if (state.traceEnabled) { trace(state.host, Diagnostics.package_json_scope_0_has_invalid_type_for_target_of_specifier_1, scope.packageDirectory, moduleName); } - return toSearchResult( - /*value*/ - void 0 - ); + return toSearchResult( /*value*/ + void 0); } if (state.traceEnabled) { trace(state.host, Diagnostics.Using_0_subpath_1_with_target_2, isImports ? "imports" : "exports", key, pattern ? target.replace(/\*/g, subpath) : target + subpath); } 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; - return toSearchResult(withPackageId(scope, loadFileNameFromPackageJsonField( - extensions, - finalPath, - /*onlyRecordFailures*/ - false, - state - ))); + if (inputLink) return inputLink; + return toSearchResult(withPackageId(scope, loadFileNameFromPackageJsonField(extensions, finalPath, /*onlyRecordFailures*/ + false, state))); } else if (typeof target === "object" && target !== null) { if (!Array.isArray(target)) { traceIfEnabled(state, Diagnostics.Entering_conditional_exports); @@ -41341,10 +39279,8 @@ ${lanes.join("\n")} if (state.traceEnabled) { trace(state.host, Diagnostics.package_json_scope_0_has_invalid_type_for_target_of_specifier_1, scope.packageDirectory, moduleName); } - return toSearchResult( - /*value*/ - void 0 - ); + return toSearchResult( /*value*/ + void 0); } for (const elem of target) { const result = loadModuleFromTargetImportOrExport(elem, subpath, pattern, key); @@ -41357,22 +39293,17 @@ ${lanes.join("\n")} if (state.traceEnabled) { trace(state.host, Diagnostics.package_json_scope_0_explicitly_maps_specifier_1_to_null, scope.packageDirectory, moduleName); } - return toSearchResult( - /*value*/ - void 0 - ); + return toSearchResult( /*value*/ + void 0); } if (state.traceEnabled) { trace(state.host, Diagnostics.package_json_scope_0_has_invalid_type_for_target_of_specifier_1, scope.packageDirectory, moduleName); } - return toSearchResult( - /*value*/ - void 0 - ); + return toSearchResult( /*value*/ + void 0); 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) { @@ -41381,7 +39312,9 @@ ${lanes.join("\n")} function tryLoadInputFileForPath(finalPath, entry, packagePath, isImports2) { var _a, _b, _c, _d; if (!state.isConfigLookup && (state.compilerOptions.declarationDir || state.compilerOptions.outDir) && !finalPath.includes("/node_modules/") && (state.compilerOptions.configFile ? containsPath(scope.packageDirectory, toAbsolutePath(state.compilerOptions.configFile.fileName), !useCaseSensitiveFileNames(state)) : true)) { - const getCanonicalFileName = hostGetCanonicalFileName({ useCaseSensitiveFileNames: () => useCaseSensitiveFileNames(state) }); + const getCanonicalFileName = hostGetCanonicalFileName({ + useCaseSensitiveFileNames: () => useCaseSensitiveFileNames(state) + }); const commonSourceDirGuesses = []; if (state.compilerOptions.rootDir || state.compilerOptions.composite && state.compilerOptions.configFilePath) { const commonDir = toAbsolutePath(getCommonSourceDirectory(state.compilerOptions, () => [], ((_b = (_a = state.host).getCurrentDirectory) == null ? void 0 : _b.call(_a)) || "", getCanonicalFileName)); @@ -41400,12 +39333,9 @@ ${lanes.join("\n")} } } if (commonSourceDirGuesses.length > 1) { - state.reportDiagnostic(createCompilerDiagnostic( - isImports2 ? Diagnostics.The_project_root_is_ambiguous_but_is_required_to_resolve_import_map_entry_0_in_file_1_Supply_the_rootDir_compiler_option_to_disambiguate : Diagnostics.The_project_root_is_ambiguous_but_is_required_to_resolve_export_map_entry_0_in_file_1_Supply_the_rootDir_compiler_option_to_disambiguate, - entry === "" ? "." : entry, - // replace empty string with `.` - the reverse of the operation done when entries are built - so main entrypoint errors don't look weird - packagePath - )); + state.reportDiagnostic(createCompilerDiagnostic(isImports2 ? Diagnostics.The_project_root_is_ambiguous_but_is_required_to_resolve_import_map_entry_0_in_file_1_Supply_the_rootDir_compiler_option_to_disambiguate : Diagnostics.The_project_root_is_ambiguous_but_is_required_to_resolve_export_map_entry_0_in_file_1_Supply_the_rootDir_compiler_option_to_disambiguate, entry === "" ? "." : entry, + // replace empty string with `.` - the reverse of the operation done when entries are built - so main entrypoint errors don't look weird + packagePath)); } for (const commonSourceDirGuess of commonSourceDirGuesses) { const candidateDirectories = getOutputDirectoriesForBaseDirectory(commonSourceDirGuess); @@ -41418,17 +39348,11 @@ ${lanes.join("\n")} 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( - extensions, - possibleInputWithInputExtension, - /*onlyRecordFailures*/ - false, - state - ))); + return toSearchResult(withPackageId(scope, loadFileNameFromPackageJsonField(extensions, possibleInputWithInputExtension, /*onlyRecordFailures*/ + false, state))); } } } @@ -41454,40 +39378,21 @@ ${lanes.join("\n")} } } 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) { - return loadModuleFromNearestNodeModulesDirectoryWorker( - extensions, - moduleName, - directory, - state, - /*typesScopeOnly*/ - false, - cache, - redirectedReference - ); + return loadModuleFromNearestNodeModulesDirectoryWorker(extensions, moduleName, directory, state, /*typesScopeOnly*/ + false, cache, redirectedReference); } function loadModuleFromNearestNodeModulesDirectoryTypesScope(moduleName, directory, state) { - return loadModuleFromNearestNodeModulesDirectoryWorker( - 4 /* Declaration */, - moduleName, - directory, - state, - /*typesScopeOnly*/ - true, - /*cache*/ - void 0, - /*redirectedReference*/ - void 0 - ); + return loadModuleFromNearestNodeModulesDirectoryWorker(4 /* Declaration */, moduleName, directory, state, /*typesScopeOnly*/ + true, /*cache*/ + void 0, /*redirectedReference*/ + void 0); } function loadModuleFromNearestNodeModulesDirectoryWorker(extensions, moduleName, directory, state, typesScopeOnly, cache, redirectedReference) { const mode = state.features === 0 ? void 0 : state.features & 32 /* EsmMode */ ? 99 /* ESNext */ : 1 /* CommonJS */; @@ -41496,15 +39401,14 @@ ${lanes.join("\n")} 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)); return lookup(secondaryExtensions); } function lookup(extensions2) { - return forEachAncestorDirectory(normalizeSlashes(directory), (ancestorDirectory) => { + return forEachAncestorDirectory(normalizeSlashes(directory), ancestorDirectory => { if (getBaseFileName(ancestorDirectory) !== "node_modules") { const resolutionFromCache = tryFindNonRelativeModuleNameInCache(cache, moduleName, mode, ancestorDirectory, redirectedReference, state); if (resolutionFromCache) { @@ -41540,43 +39444,34 @@ ${lanes.join("\n")} } } function loadModuleFromSpecificNodeModulesDirectory(extensions, moduleName, nodeModulesDirectory, nodeModulesDirectoryExists, state, cache, redirectedReference) { + var _ref9; var _a, _b; const candidate = normalizePath(combinePaths(nodeModulesDirectory, moduleName)); - const { packageName, rest } = parsePackageName(moduleName); + const { + packageName, + rest + } = parsePackageName(moduleName); const packageDirectory = combinePaths(nodeModulesDirectory, packageName); let rootPackageInfo; let packageInfo = getPackageJsonInfo(candidate, !nodeModulesDirectoryExists, state); - if (rest !== "" && packageInfo && (!(state.features & 8 /* Exports */) || !hasProperty(((_a = rootPackageInfo = getPackageJsonInfo(packageDirectory, !nodeModulesDirectoryExists, state)) == null ? void 0 : _a.contents.packageJsonContent) ?? emptyArray, "exports"))) { + if (rest !== "" && packageInfo && (!(state.features & 8 /* Exports */) || !hasProperty((_ref9 = (_a = rootPackageInfo = getPackageJsonInfo(packageDirectory, !nodeModulesDirectoryExists, state)) == null ? void 0 : _a.contents.packageJsonContent) !== null && _ref9 !== void 0 ? _ref9 : emptyArray, "exports"))) { const fromFile = loadModuleFromFile(extensions, candidate, !nodeModulesDirectoryExists, state); if (fromFile) { return noPackageId(fromFile); } - const fromDirectory = loadNodeModuleFromDirectoryWorker( - extensions, - candidate, - !nodeModulesDirectoryExists, - state, - packageInfo.contents.packageJsonContent, - getVersionPathsOfPackageJsonInfo(packageInfo, state) - ); + const fromDirectory = loadNodeModuleFromDirectoryWorker(extensions, candidate, !nodeModulesDirectoryExists, state, packageInfo.contents.packageJsonContent, getVersionPathsOfPackageJsonInfo(packageInfo, state)); return withPackageId(packageInfo, fromDirectory); } const loader = (extensions2, candidate2, onlyRecordFailures, state2) => { - let pathAndExtension = (rest || !(state2.features & 32 /* EsmMode */)) && loadModuleFromFile(extensions2, candidate2, onlyRecordFailures, state2) || loadNodeModuleFromDirectoryWorker( - extensions2, - candidate2, - onlyRecordFailures, - state2, - packageInfo && packageInfo.contents.packageJsonContent, - packageInfo && getVersionPathsOfPackageJsonInfo(packageInfo, state2) - ); + let pathAndExtension = (rest || !(state2.features & 32 /* EsmMode */)) && loadModuleFromFile(extensions2, candidate2, onlyRecordFailures, state2) || loadNodeModuleFromDirectoryWorker(extensions2, candidate2, onlyRecordFailures, state2, packageInfo && packageInfo.contents.packageJsonContent, packageInfo && getVersionPathsOfPackageJsonInfo(packageInfo, state2)); if (!pathAndExtension && packageInfo && (packageInfo.contents.packageJsonContent.exports === void 0 || packageInfo.contents.packageJsonContent.exports === null) && state2.features & 32 /* EsmMode */) { pathAndExtension = loadModuleFromFile(extensions2, combinePaths(candidate2, "index.js"), onlyRecordFailures, state2); } return withPackageId(packageInfo, pathAndExtension); }; if (rest !== "") { - packageInfo = rootPackageInfo ?? getPackageJsonInfo(packageDirectory, !nodeModulesDirectoryExists, state); + var _rootPackageInfo; + packageInfo = (_rootPackageInfo = rootPackageInfo) !== null && _rootPackageInfo !== void 0 ? _rootPackageInfo : getPackageJsonInfo(packageDirectory, !nodeModulesDirectoryExists, state); } if (packageInfo && packageInfo.contents.packageJsonContent.exports && state.features & 8 /* Exports */) { return (_b = loadModuleFromExports(packageInfo, extensions, combinePaths(".", rest), state, cache, redirectedReference)) == null ? void 0 : _b.value; @@ -41587,17 +39482,8 @@ ${lanes.join("\n")} trace(state.host, Diagnostics.package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2, versionPaths.version, version, rest); } const packageDirectoryExists = nodeModulesDirectoryExists && directoryProbablyExists(packageDirectory, state.host); - const fromPaths = tryLoadModuleUsingPaths( - extensions, - rest, - packageDirectory, - versionPaths.paths, - /*pathPatterns*/ - void 0, - loader, - !packageDirectoryExists, - state - ); + const fromPaths = tryLoadModuleUsingPaths(extensions, rest, packageDirectory, versionPaths.paths, /*pathPatterns*/ + void 0, loader, !packageDirectoryExists, state); if (fromPaths) { return fromPaths.value; } @@ -41613,7 +39499,7 @@ ${lanes.join("\n")} if (state.traceEnabled) { trace(state.host, Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText); } - const resolved = forEach(paths[matchedPatternText], (subst) => { + const resolved = forEach(paths[matchedPatternText], subst => { const path = matchedStar ? subst.replace("*", matchedStar) : subst; const candidate = normalizePath(combinePaths(baseDirectory, path)); if (state.traceEnabled) { @@ -41623,12 +39509,18 @@ ${lanes.join("\n")} if (extension !== void 0) { const path2 = tryFile(candidate, onlyRecordFailures, state); if (path2 !== void 0) { - return noPackageId({ path: path2, ext: extension, resolvedUsingTsExtension: void 0 }); + return noPackageId({ + path: path2, + ext: extension, + resolvedUsingTsExtension: void 0 + }); } } return loader(extensions, candidate, onlyRecordFailures || !directoryProbablyExists(getDirectoryPath(candidate), state.host), state); }); - return { value: resolved }; + return { + value: resolved + }; } } function mangleScopedPackageNameWithTrace(packageName, state) { @@ -41694,72 +39586,46 @@ ${lanes.join("\n")} features: 0 /* None */, conditions: [], requestContainingDirectory: containingDirectory, - reportDiagnostic: (diag2) => void diagnostics.push(diag2), + reportDiagnostic: diag2 => void diagnostics.push(diag2), isConfigLookup: false, candidateIsFromPackageJsonField: false }; const resolved = tryResolve(1 /* TypeScript */ | 4 /* Declaration */) || tryResolve(2 /* JavaScript */ | (compilerOptions.resolveJsonModule ? 8 /* Json */ : 0)); - return createResolvedModuleWithFailedLookupLocationsHandlingSymlink( - moduleName, - resolved && resolved.value, - (resolved == null ? void 0 : resolved.value) && pathContainsNodeModules(resolved.value.path), - failedLookupLocations, - affectingLocations, - diagnostics, - state, - cache - ); + return createResolvedModuleWithFailedLookupLocationsHandlingSymlink(moduleName, resolved && resolved.value, (resolved == null ? void 0 : resolved.value) && pathContainsNodeModules(resolved.value.path), failedLookupLocations, affectingLocations, diagnostics, state, cache); function tryResolve(extensions) { const resolvedUsingSettings = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loadModuleFromFileNoPackageId, state); if (resolvedUsingSettings) { - return { value: resolvedUsingSettings }; + return { + value: resolvedUsingSettings + }; } if (!isExternalModuleNameRelative(moduleName)) { - const resolved2 = forEachAncestorDirectory(containingDirectory, (directory) => { - const resolutionFromCache = tryFindNonRelativeModuleNameInCache( - cache, - moduleName, - /*mode*/ - void 0, - directory, - redirectedReference, - state - ); + const resolved2 = forEachAncestorDirectory(containingDirectory, directory => { + const resolutionFromCache = tryFindNonRelativeModuleNameInCache(cache, moduleName, /*mode*/ + void 0, directory, redirectedReference, state); if (resolutionFromCache) { return resolutionFromCache; } const searchName = normalizePath(combinePaths(directory, moduleName)); - return toSearchResult(loadModuleFromFileNoPackageId( - extensions, - searchName, - /*onlyRecordFailures*/ - false, - state - )); + return toSearchResult(loadModuleFromFileNoPackageId(extensions, searchName, /*onlyRecordFailures*/ + false, state)); }); - if (resolved2) - return resolved2; + if (resolved2) return resolved2; if (extensions & (1 /* TypeScript */ | 4 /* Declaration */)) { + var _resolved2; let resolved3 = loadModuleFromNearestNodeModulesDirectoryTypesScope(moduleName, containingDirectory, state); - if (extensions & 4 /* Declaration */) - resolved3 ?? (resolved3 = resolveFromTypeRoot(moduleName, state)); + if (extensions & 4 /* Declaration */) (_resolved2 = resolved3) !== null && _resolved2 !== void 0 ? _resolved2 : resolved3 = resolveFromTypeRoot(moduleName, state); return resolved3; } } else { const candidate = normalizePath(combinePaths(containingDirectory, moduleName)); - return toSearchResult(loadModuleFromFileNoPackageId( - extensions, - candidate, - /*onlyRecordFailures*/ - false, - state - )); + return toSearchResult(loadModuleFromFileNoPackageId(extensions, candidate, /*onlyRecordFailures*/ + false, state)); } } } 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); @@ -41769,17 +39635,12 @@ ${lanes.join("\n")} const resolvedFromFile = loadModuleFromFile(4 /* Declaration */, candidate, !directoryExists, state); if (resolvedFromFile) { const packageDirectory = parseNodeModuleFromPath(resolvedFromFile.path); - const packageInfo = packageDirectory ? getPackageJsonInfo( - packageDirectory, - /*onlyRecordFailures*/ - false, - state - ) : void 0; + const packageInfo = packageDirectory ? getPackageJsonInfo(packageDirectory, /*onlyRecordFailures*/ + false, state) : void 0; return toSearchResult(withPackageId(packageInfo, resolvedFromFile)); } const resolved = loadNodeModuleFromDirectory(4 /* Declaration */, candidate, !directoryExists, state); - if (resolved) - return toSearchResult(resolved); + if (resolved) return toSearchResult(resolved); } } function shouldAllowImportingTsExtension(compilerOptions, fromFileName) { @@ -41803,36 +39664,22 @@ ${lanes.join("\n")} features: 0 /* None */, conditions: [], requestContainingDirectory: void 0, - reportDiagnostic: (diag2) => void diagnostics.push(diag2), + reportDiagnostic: diag2 => void diagnostics.push(diag2), isConfigLookup: false, candidateIsFromPackageJsonField: false }; - const resolved = loadModuleFromImmediateNodeModulesDirectory( - 4 /* Declaration */, - moduleName, - globalCache, - state, - /*typesScopeOnly*/ - false, - /*cache*/ - void 0, - /*redirectedReference*/ - void 0 - ); - return createResolvedModuleWithFailedLookupLocations( - resolved, - /*isExternalLibraryImport*/ - true, - failedLookupLocations, - affectingLocations, - diagnostics, - state.resultFromCache, - /*cache*/ - void 0 - ); + const resolved = loadModuleFromImmediateNodeModulesDirectory(4 /* Declaration */, moduleName, globalCache, state, /*typesScopeOnly*/ + false, /*cache*/ + void 0, /*redirectedReference*/ + void 0); + return createResolvedModuleWithFailedLookupLocations(resolved, /*isExternalLibraryImport*/ + true, failedLookupLocations, affectingLocations, diagnostics, state.resultFromCache, /*cache*/ + void 0); } function toSearchResult(value) { - return value !== void 0 ? { value } : void 0; + return value !== void 0 ? { + value + } : void 0; } function traceIfEnabled(state, diagnostic, ...args) { if (state.traceEnabled) { @@ -41846,9 +39693,10 @@ ${lanes.join("\n")} var init_moduleNameResolver = __esm({ "src/compiler/moduleNameResolver.ts"() { "use strict"; + init_ts2(); nodeModulesAtTypes = combinePaths("node_modules", "@types"); - NodeResolutionFeatures = /* @__PURE__ */ ((NodeResolutionFeatures2) => { + NodeResolutionFeatures = /* @__PURE__ */(NodeResolutionFeatures2 => { NodeResolutionFeatures2[NodeResolutionFeatures2["None"] = 0] = "None"; NodeResolutionFeatures2[NodeResolutionFeatures2["Imports"] = 2] = "Imports"; NodeResolutionFeatures2[NodeResolutionFeatures2["SelfName"] = 4] = "SelfName"; @@ -41870,19 +39718,18 @@ ${lanes.join("\n")} function getModuleInstanceState(node, visited) { if (node.body && !node.body.parent) { setParent(node.body, node); - setParentRecursive( - node.body, - /*incremental*/ - false - ); + setParentRecursive(node.body, /*incremental*/ + false); } return node.body ? getModuleInstanceStateCached(node.body, visited) : 1 /* Instantiated */; } - function getModuleInstanceStateCached(node, visited = /* @__PURE__ */ new Map()) { + + function getModuleInstanceStateCached(node, visited = /* @__PURE__ */new Map()) { const nodeId = getNodeId(node); if (visited.has(nodeId)) { return visited.get(nodeId) || 0 /* NonInstantiated */; } + visited.set(nodeId, void 0); const result = getModuleInstanceStateWorker(node, visited); visited.set(nodeId, result); @@ -41897,12 +39744,14 @@ ${lanes.join("\n")} if (isEnumConst(node)) { return 2 /* ConstEnumOnly */; } + break; case 272 /* ImportDeclaration */: case 271 /* ImportEqualsDeclaration */: if (!hasSyntacticModifier(node, 32 /* Export */)) { return 0 /* NonInstantiated */; } + break; case 278 /* ExportDeclaration */: const exportDeclaration = node; @@ -41920,25 +39769,26 @@ ${lanes.join("\n")} return state; } break; - case 268 /* ModuleBlock */: { - let state = 0 /* NonInstantiated */; - forEachChild(node, (n) => { - const childState = getModuleInstanceStateCached(n, visited); - switch (childState) { - case 0 /* NonInstantiated */: - return; - case 2 /* ConstEnumOnly */: - state = 2 /* ConstEnumOnly */; - return; - case 1 /* Instantiated */: - state = 1 /* Instantiated */; - return true; - default: - Debug.assertNever(childState); - } - }); - return state; - } + case 268 /* ModuleBlock */: + { + let state = 0 /* NonInstantiated */; + forEachChild(node, n => { + const childState = getModuleInstanceStateCached(n, visited); + switch (childState) { + case 0 /* NonInstantiated */: + return; + case 2 /* ConstEnumOnly */: + state = 2 /* ConstEnumOnly */; + return; + case 1 /* Instantiated */: + state = 1 /* Instantiated */; + return true; + default: + Debug.assertNever(childState); + } + }); + return state; + } case 267 /* ModuleDeclaration */: return getModuleInstanceState(node, visited); case 80 /* Identifier */: @@ -41946,8 +39796,10 @@ ${lanes.join("\n")} return 0 /* NonInstantiated */; } } + return 1 /* Instantiated */; } + function getModuleInstanceStateForAliasTarget(specifier, visited) { const name = specifier.propertyName || specifier.name; let p = specifier.parent; @@ -41959,11 +39811,8 @@ ${lanes.join("\n")} if (nodeHasName(statement, name)) { if (!statement.parent) { setParent(statement, p); - setParentRecursive( - statement, - /*incremental*/ - false - ); + setParentRecursive(statement, /*incremental*/ + false); } const state = getModuleInstanceStateCached(statement, visited); if (found === void 0 || state > found) { @@ -41977,6 +39826,7 @@ ${lanes.join("\n")} } } } + if (found !== void 0) { return found; } @@ -41985,6 +39835,7 @@ ${lanes.join("\n")} } return 1 /* Instantiated */; } + function initFlowNode(node) { Debug.attachFlowNodeDebugInfo(node); return node; @@ -42025,8 +39876,12 @@ ${lanes.join("\n")} var symbolCount = 0; var Symbol47; var classifiableNames; - var unreachableFlow = { flags: 1 /* Unreachable */ }; - var reportedUnreachableFlow = { flags: 1 /* Unreachable */ }; + var unreachableFlow = { + flags: 1 /* Unreachable */ + }; + var reportedUnreachableFlow = { + flags: 1 /* Unreachable */ + }; var bindBinaryExpressionFlow = createBindBinaryExpressionFlow(); return bindSourceFile2; function createDiagnosticForNode2(node, message, ...args) { @@ -42038,19 +39893,16 @@ ${lanes.join("\n")} options = opts; languageVersion = getEmitScriptTarget(options); inStrictMode = bindInStrictMode(file, opts); - classifiableNames = /* @__PURE__ */ new Set(); + classifiableNames = /* @__PURE__ */new Set(); symbolCount = 0; Symbol47 = objectAllocator.getSymbolConstructor(); Debug.attachFlowNodeDebugInfo(unreachableFlow); Debug.attachFlowNodeDebugInfo(reportedUnreachableFlow); if (!file.locals) { - (_a = tracing) == null ? void 0 : _a.push( - tracing.Phase.Bind, - "bindSourceFile", - { path: file.path }, - /*separateBeginAndEnd*/ - true - ); + (_a = tracing) == null ? void 0 : _a.push(tracing.Phase.Bind, "bindSourceFile", { + path: file.path + }, /*separateBeginAndEnd*/ + true); bind(file); (_b = tracing) == null ? void 0 : _b.pop(); file.symbolCount = symbolCount; @@ -42079,6 +39931,7 @@ ${lanes.join("\n")} inAssignmentPattern = false; emitFlags = 0 /* None */; } + function bindInStrictMode(file2, opts) { if (getStrictOptionValue(opts, "alwaysStrict") && !file2.isDeclarationFile) { return true; @@ -42111,6 +39964,7 @@ ${lanes.join("\n")} if (node.kind === 277 /* ExportAssignment */) { return node.isExportEquals ? "export=" /* ExportEquals */ : "default" /* Default */; } + const name = getNameOfDeclaration(node); if (name) { if (isAmbientModule(node)) { @@ -42161,6 +40015,7 @@ ${lanes.join("\n")} if (getAssignmentDeclarationKind(node) === 2 /* ModuleExports */) { return "export=" /* ExportEquals */; } + Debug.fail("Unknown binary declaration kind"); break; case 324 /* JSDocFunctionType */: @@ -42189,8 +40044,7 @@ ${lanes.join("\n")} } 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) { @@ -42213,7 +40067,7 @@ ${lanes.join("\n")} messageNeedsName = false; multipleDefaultExports = true; } else { - if (symbol.declarations && symbol.declarations.length && (node.kind === 277 /* ExportAssignment */ && !node.isExportEquals)) { + if (symbol.declarations && symbol.declarations.length && node.kind === 277 /* ExportAssignment */ && !node.isExportEquals) { message = Diagnostics.A_module_cannot_have_multiple_default_exports; messageNeedsName = false; multipleDefaultExports = true; @@ -42228,9 +40082,7 @@ ${lanes.join("\n")} forEach(symbol.declarations, (declaration, index) => { const decl = getNameOfDeclaration(declaration) || declaration; const diag3 = messageNeedsName ? createDiagnosticForNode2(decl, message, getDisplayName(declaration)) : createDiagnosticForNode2(decl, message); - file.bindDiagnostics.push( - multipleDefaultExports ? addRelatedInfo(diag3, createDiagnosticForNode2(declarationName, index === 0 ? Diagnostics.Another_export_default_is_here : Diagnostics.and_here)) : diag3 - ); + file.bindDiagnostics.push(multipleDefaultExports ? addRelatedInfo(diag3, createDiagnosticForNode2(declarationName, index === 0 ? Diagnostics.Another_export_default_is_here : Diagnostics.and_here)) : diag3); if (multipleDefaultExports) { relatedInformation.push(createDiagnosticForNode2(decl, Diagnostics.The_first_export_default_is_here)); } @@ -42256,44 +40108,25 @@ ${lanes.join("\n")} return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); } else { Debug.assertNode(container, canHaveLocals); - return declareSymbol( - container.locals, - /*parent*/ - void 0, - node, - symbolFlags, - symbolExcludes - ); + return declareSymbol(container.locals, /*parent*/ + void 0, node, symbolFlags, symbolExcludes); } } 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); } const exportKind = symbolFlags & 111551 /* Value */ ? 1048576 /* ExportValue */ : 0; - const local = declareSymbol( - container.locals, - /*parent*/ - void 0, - node, - exportKind, - symbolExcludes - ); + const local = declareSymbol(container.locals, /*parent*/ + void 0, node, exportKind, symbolExcludes); local.exportSymbol = declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); node.localSymbol = local; return local; } else { Debug.assertNode(container, canHaveLocals); - return declareSymbol( - container.locals, - /*parent*/ - void 0, - node, - symbolFlags, - symbolExcludes - ); + return declareSymbol(container.locals, /*parent*/ + void 0, node, symbolFlags, symbolExcludes); } } } @@ -42301,17 +40134,12 @@ ${lanes.join("\n")} 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) { @@ -42343,7 +40171,9 @@ ${lanes.join("\n")} const saveHasExplicitReturn = hasExplicitReturn; const isImmediatelyInvoked = containerFlags & 16 /* IsFunctionExpression */ && !hasSyntacticModifier(node, 1024 /* Async */) && !node.asteriskToken && !!getImmediatelyInvokedFunctionExpression(node) || node.kind === 175 /* ClassStaticBlockDeclaration */; if (!isImmediatelyInvoked) { - currentFlow = initFlowNode({ flags: 2 /* Start */ }); + currentFlow = initFlowNode({ + flags: 2 /* Start */ + }); if (containerFlags & (16 /* IsFunctionExpression */ | 128 /* IsObjectLiteralOrClassExpressionMethodOrAccessor */)) { currentFlow.node = node; } @@ -42358,8 +40188,7 @@ ${lanes.join("\n")} 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 === 312 /* SourceFile */) { @@ -42395,8 +40224,8 @@ ${lanes.join("\n")} blockScopeContainer = savedBlockScopeContainer; } function bindEachFunctionsFirst(nodes) { - bindEach(nodes, (n) => n.kind === 262 /* FunctionDeclaration */ ? bind(n) : void 0); - bindEach(nodes, (n) => n.kind !== 262 /* FunctionDeclaration */ ? bind(n) : void 0); + bindEach(nodes, n => n.kind === 262 /* FunctionDeclaration */ ? bind(n) : void 0); + bindEach(nodes, n => n.kind !== 262 /* FunctionDeclaration */ ? bind(n) : void 0); } function bindEach(nodes, bindFunction = bind) { if (nodes === void 0) { @@ -42500,11 +40329,12 @@ ${lanes.join("\n")} case 347 /* JSDocEnumTag */: bindJSDocTypeAlias(node); break; - case 312 /* SourceFile */: { - bindEachFunctionsFirst(node.statements); - bind(node.endOfFileToken); - break; - } + case 312 /* SourceFile */: + { + bindEachFunctionsFirst(node.statements); + bind(node.endOfFileToken); + break; + } case 241 /* Block */: case 268 /* ModuleBlock */: bindEachFunctionsFirst(node.statements); @@ -42582,7 +40412,7 @@ ${lanes.join("\n")} case 36 /* ExclamationEqualsToken */: case 37 /* EqualsEqualsEqualsToken */: case 38 /* ExclamationEqualsEqualsToken */: - return isNarrowableOperand(expr.left) || isNarrowableOperand(expr.right) || isNarrowingTypeofOperands(expr.right, expr.left) || isNarrowingTypeofOperands(expr.left, expr.right) || (isBooleanLiteral(expr.right) && isNarrowingExpression(expr.left) || isBooleanLiteral(expr.left) && isNarrowingExpression(expr.right)); + return isNarrowableOperand(expr.left) || isNarrowableOperand(expr.right) || isNarrowingTypeofOperands(expr.right, expr.left) || isNarrowingTypeofOperands(expr.left, expr.right) || isBooleanLiteral(expr.right) && isNarrowingExpression(expr.left) || isBooleanLiteral(expr.left) && isNarrowingExpression(expr.right); case 104 /* InstanceOfKeyword */: return isNarrowableOperand(expr.left); case 103 /* InKeyword */: @@ -42607,17 +40437,29 @@ ${lanes.join("\n")} return containsNarrowableReference(expr); } function createBranchLabel() { - return initFlowNode({ flags: 4 /* BranchLabel */, antecedents: void 0 }); + return initFlowNode({ + flags: 4 /* BranchLabel */, + antecedents: void 0 + }); } function createLoopLabel() { - return initFlowNode({ flags: 8 /* LoopLabel */, antecedents: void 0 }); + return initFlowNode({ + flags: 8 /* LoopLabel */, + antecedents: void 0 + }); } function createReduceLabel(target, antecedents, antecedent) { - return initFlowNode({ flags: 1024 /* ReduceLabel */, target, antecedents, antecedent }); + return initFlowNode({ + flags: 1024 /* ReduceLabel */, + target, + antecedents, + antecedent + }); } function setFlowNodeReferenced(flow) { flow.flags |= flow.flags & 2048 /* Referenced */ ? 4096 /* Shared */ : 2048 /* Referenced */; } + function addAntecedent(label, antecedent) { if (!(antecedent.flags & 1 /* Unreachable */) && !contains(label.antecedents, antecedent)) { (label.antecedents || (label.antecedents = [])).push(antecedent); @@ -42638,15 +40480,29 @@ ${lanes.join("\n")} return antecedent; } setFlowNodeReferenced(antecedent); - return initFlowNode({ flags, antecedent, node: expression }); + return initFlowNode({ + flags, + antecedent, + node: expression + }); } function createFlowSwitchClause(antecedent, switchStatement, clauseStart, clauseEnd) { setFlowNodeReferenced(antecedent); - return initFlowNode({ flags: 128 /* SwitchClause */, antecedent, switchStatement, clauseStart, clauseEnd }); + return initFlowNode({ + flags: 128 /* SwitchClause */, + antecedent, + switchStatement, + clauseStart, + clauseEnd + }); } function createFlowMutation(flags, antecedent, node) { setFlowNodeReferenced(antecedent); - const result = initFlowNode({ flags, antecedent, node }); + const result = initFlowNode({ + flags, + antecedent, + node + }); if (currentExceptionTarget) { addAntecedent(currentExceptionTarget, result); } @@ -42654,7 +40510,11 @@ ${lanes.join("\n")} } function createFlowCall(antecedent, node) { setFlowNodeReferenced(antecedent); - return initFlowNode({ flags: 512 /* Call */, antecedent, node }); + return initFlowNode({ + flags: 512 /* Call */, + antecedent, + node + }); } function finishFlowLabel(flow) { const antecedents = flow.antecedents; @@ -42891,7 +40751,7 @@ ${lanes.join("\n")} preSwitchCaseFlow = currentFlow; bind(node.caseBlock); addAntecedent(postSwitchLabel, currentFlow); - const hasDefault = forEach(node.caseBlock.clauses, (c) => c.kind === 297 /* DefaultClause */); + const hasDefault = forEach(node.caseBlock.clauses, c => c.kind === 297 /* DefaultClause */); node.possiblyExhaustive = !hasDefault && !postSwitchLabel.antecedents; if (!hasDefault) { addAntecedent(postSwitchLabel, createFlowSwitchClause(preSwitchCaseFlow, node, 0, 0)); @@ -43045,15 +40905,8 @@ ${lanes.join("\n")} bindAssignmentTargetFlow(node.left); } function createBindBinaryExpressionFlow() { - return createBinaryExpressionTrampoline( - onEnter, - onLeft, - onOperator, - onRight, - onExit, - /*foldState*/ - void 0 - ); + return createBinaryExpressionTrampoline(onEnter, onLeft, onOperator, onRight, onExit, /*foldState*/ + void 0); function onEnter(node, state) { if (state) { state.stackIndex++; @@ -43209,11 +41062,8 @@ ${lanes.join("\n")} bind(node.tagName); if (node.kind !== 347 /* JSDocEnumTag */ && node.fullName) { setParent(node.fullName, node); - setParentRecursive( - node.fullName, - /*incremental*/ - false - ); + setParentRecursive(node.fullName, /*incremental*/ + false); } if (typeof node.comment !== "string") { bindEach(node.comment); @@ -43226,6 +41076,7 @@ ${lanes.join("\n")} addDeclarationToSymbol(host.symbol, host, 32 /* Class */); } } + function bindOptionalExpression(node, trueTarget, falseTarget) { doWithConditionalBranches(bind, node, trueTarget, falseTarget); if (!isOptionalChain(node) || isOutermostOptionalChain(node)) { @@ -43349,34 +41200,21 @@ ${lanes.join("\n")} case 175 /* ClassStaticBlockDeclaration */: case 265 /* TypeAliasDeclaration */: case 200 /* MappedType */: - if (container.locals) - Debug.assertNode(container, canHaveLocals); - return declareSymbol( - container.locals, - /*parent*/ - void 0, - node, - symbolFlags, - symbolExcludes - ); + if (container.locals) Debug.assertNode(container, canHaveLocals); + return declareSymbol(container.locals, /*parent*/ + void 0, node, symbolFlags, symbolExcludes); } } function declareClassMember(node, symbolFlags, symbolExcludes) { return isStatic(node) ? declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes) : declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes); } function declareSourceFileMember(node, symbolFlags, symbolExcludes) { - return isExternalModule(file) ? declareModuleMember(node, symbolFlags, symbolExcludes) : declareSymbol( - file.locals, - /*parent*/ - void 0, - node, - symbolFlags, - symbolExcludes - ); + return isExternalModule(file) ? declareModuleMember(node, symbolFlags, symbolExcludes) : declareSymbol(file.locals, /*parent*/ + void 0, node, symbolFlags, symbolExcludes); } function hasExportDeclarations(node) { const body = isSourceFile(node) ? node : tryCast(node.body, isModuleBlock); - return !!body && body.statements.some((s) => isExportDeclaration(s) || isExportAssignment(s)); + return !!body && body.statements.some(s => isExportDeclaration(s) || isExportAssignment(s)); } function setExportContextFlag(node) { if (node.flags & 33554432 /* Ambient */ && !hasExportDeclarations(node)) { @@ -43385,6 +41223,7 @@ ${lanes.join("\n")} node.flags &= ~128 /* ExportContext */; } } + function bindModuleDeclaration(node) { setExportContextFlag(node); if (isAmbientModule(node)) { @@ -43396,19 +41235,26 @@ ${lanes.join("\n")} } else { let pattern; if (node.name.kind === 11 /* StringLiteral */) { - const { text } = node.name; + const { + text + } = node.name; pattern = tryParsePattern(text); if (pattern === void 0) { errorOnFirstToken(node.name, Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, text); } } const symbol = declareSymbolAndAddToSymbolTable(node, 512 /* ValueModule */, 110735 /* ValueModuleExcludes */); - file.patternAmbientModules = append(file.patternAmbientModules, pattern && !isString(pattern) ? { pattern, symbol } : void 0); + file.patternAmbientModules = append(file.patternAmbientModules, pattern && !isString(pattern) ? { + pattern, + symbol + } : void 0); } } else { const state = declareModuleSymbol(node); if (state !== 0 /* NonInstantiated */) { - const { symbol } = node; + const { + symbol + } = node; symbol.constEnumOnlyModule = !(symbol.flags & (16 /* Function */ | 32 /* Class */ | 256 /* RegularEnum */)) && state === 2 /* ConstEnumOnly */ && symbol.constEnumOnlyModule !== false; } } @@ -43416,11 +41262,8 @@ ${lanes.join("\n")} function declareModuleSymbol(node) { const state = getModuleInstanceState(node); const instantiated = state !== 0 /* NonInstantiated */; - declareSymbolAndAddToSymbolTable( - node, - instantiated ? 512 /* ValueModule */ : 1024 /* NamespaceModule */, - instantiated ? 110735 /* ValueModuleExcludes */ : 0 /* NamespaceModuleExcludes */ - ); + declareSymbolAndAddToSymbolTable(node, instantiated ? 512 /* ValueModule */ : 1024 /* NamespaceModule */, instantiated ? 110735 /* ValueModuleExcludes */ : 0 /* NamespaceModuleExcludes */); + return state; } function bindFunctionOrConstructorType(node) { @@ -43434,9 +41277,11 @@ ${lanes.join("\n")} function bindObjectLiteralExpression(node) { return bindAnonymousDeclaration(node, 4096 /* ObjectLiteral */, "__object" /* Object */); } + function bindJsxAttributes(node) { return bindAnonymousDeclaration(node, 4096 /* ObjectLiteral */, "__jsxAttributes" /* JSXAttributes */); } + function bindJsxAttribute(node, symbolFlags, symbolExcludes) { return declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes); } @@ -43464,14 +41309,8 @@ ${lanes.join("\n")} blockScopeContainer.locals = createSymbolTable(); addToContainerChain(blockScopeContainer); } - declareSymbol( - blockScopeContainer.locals, - /*parent*/ - void 0, - node, - symbolFlags, - symbolExcludes - ); + declareSymbol(blockScopeContainer.locals, /*parent*/ + void 0, node, symbolFlags, symbolExcludes); } } function delayedBindJSDocTypedefTag() { @@ -43487,21 +41326,17 @@ ${lanes.join("\n")} const host = typeAlias.parent.parent; container = getEnclosingContainer(host) || file; blockScopeContainer = getEnclosingBlockScopeContainer(host) || file; - currentFlow = initFlowNode({ flags: 2 /* Start */ }); + currentFlow = initFlowNode({ + flags: 2 /* Start */ + }); parent2 = typeAlias; bind(typeAlias.typeExpression); const declName = getNameOfDeclaration(typeAlias); if ((isJSDocEnumTag(typeAlias) || !typeAlias.fullName) && declName && isPropertyAccessEntityNameExpression(declName.parent)) { const isTopLevel = isTopLevelNamespaceAssignment(declName.parent); if (isTopLevel) { - bindPotentiallyMissingNamespaces( - file.symbol, - declName.parent, - isTopLevel, - !!findAncestor(declName, (d) => isPropertyAccessExpression(d) && d.name.escapedText === "prototype"), - /*containerIsClass*/ - false - ); + bindPotentiallyMissingNamespaces(file.symbol, declName.parent, isTopLevel, !!findAncestor(declName, d => isPropertyAccessExpression(d) && d.name.escapedText === "prototype"), /*containerIsClass*/ + false); const oldContainer = container; switch (getAssignmentDeclarationPropertyAccessKind(declName.parent)) { case 1 /* ExportsProperty */: @@ -43527,6 +41362,7 @@ ${lanes.join("\n")} if (container) { declareModuleMember(typeAlias, 524288 /* TypeAlias */, 788968 /* TypeAliasExcludes */); } + container = oldContainer; } } else if (isJSDocEnumTag(typeAlias) || !typeAlias.fullName || typeAlias.fullName.kind === 80 /* Identifier */) { @@ -43668,23 +41504,29 @@ ${lanes.join("\n")} errorOrSuggestionOnRange(isError, node, node, message); } function errorOrSuggestionOnRange(isError, startNode2, endNode2, message) { - addErrorOrSuggestionDiagnostic(isError, { pos: getTokenPosOfNode(startNode2, file), end: endNode2.end }, message); + addErrorOrSuggestionDiagnostic(isError, { + pos: getTokenPosOfNode(startNode2, file), + end: endNode2.end + }, message); } function addErrorOrSuggestionDiagnostic(isError, range, message) { const diag2 = createFileDiagnostic(file, range.pos, range.end - range.pos, message); if (isError) { file.bindDiagnostics.push(diag2); } else { - file.bindSuggestionDiagnostics = append(file.bindSuggestionDiagnostics, { ...diag2, category: 2 /* Suggestion */ }); + file.bindSuggestionDiagnostics = append(file.bindSuggestionDiagnostics, { + ...diag2, + category: 2 /* Suggestion */ + }); } } + function bind(node) { if (!node) { 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 */) { @@ -43699,8 +41541,7 @@ ${lanes.join("\n")} parent2 = saveParent; } else { const saveParent = parent2; - if (node.kind === 1 /* EndOfFileToken */) - parent2 = node; + if (node.kind === 1 /* EndOfFileToken */) parent2 = node; bindJSDoc(node); parent2 = saveParent; } @@ -43715,11 +41556,8 @@ ${lanes.join("\n")} } else { for (const j of node.jsDoc) { setParent(j, node); - setParentRecursive( - j, - /*incremental*/ - false - ); + setParentRecursive(j, /*incremental*/ + false); } } } @@ -43778,15 +41616,10 @@ ${lanes.join("\n")} bindSpecialPropertyDeclaration(expr); } if (isInJSFile(expr) && file.commonJsModuleIndicator && isModuleExportsAccessExpression(expr) && !lookupSymbolForName(blockScopeContainer, "module")) { - declareSymbol( - file.locals, - /*parent*/ - void 0, - expr.expression, - 1 /* FunctionScopedVariable */ | 134217728 /* ModuleExports */, - 111550 /* FunctionScopedVariableExcludes */ - ); + declareSymbol(file.locals, /*parent*/ + void 0, expr.expression, 1 /* FunctionScopedVariable */ | 134217728 /* ModuleExports */, 111550 /* FunctionScopedVariableExcludes */); } + break; case 226 /* BinaryExpression */: const specialKind = getAssignmentDeclarationKind(node); @@ -43867,12 +41700,9 @@ ${lanes.join("\n")} case 262 /* FunctionDeclaration */: return bindFunctionDeclaration(node); case 176 /* Constructor */: - return declareSymbolAndAddToSymbolTable( - node, - 16384 /* Constructor */, - /*symbolExcludes:*/ - 0 /* None */ - ); + return declareSymbolAndAddToSymbolTable(node, 16384 /* Constructor */, /*symbolExcludes:*/ + 0 /* None */); + case 177 /* GetAccessor */: return bindPropertyOrMethodOrAccessor(node, 32768 /* GetAccessor */, 46015 /* GetAccessorExcludes */); case 178 /* SetAccessor */: @@ -43977,6 +41807,7 @@ ${lanes.join("\n")} function bindAnonymousTypeWorker(node) { return bindAnonymousDeclaration(node, 2048 /* TypeLiteral */, "__type" /* Type */); } + function bindSourceFileIfExternalModule() { setExportContextFlag(file); if (isExternalModule(file)) { @@ -44014,6 +41845,7 @@ ${lanes.join("\n")} declareSymbol(file.symbol.globalExports, file.symbol, node, 2097152 /* Alias */, 2097152 /* AliasExcludes */); } } + function bindExportDeclaration(node) { if (!container.symbol || !container.symbol.exports) { bindAnonymousDeclaration(node, 8388608 /* ExportStar */, getDeclarationName(node)); @@ -44024,11 +41856,13 @@ ${lanes.join("\n")} declareSymbol(container.symbol.exports, container.symbol, node.exportClause, 2097152 /* Alias */, 2097152 /* AliasExcludes */); } } + function bindImportClause(node) { if (node.name) { declareSymbolAndAddToSymbolTable(node, 2097152 /* Alias */, 2097152 /* AliasExcludes */); } } + function setCommonJsModuleIndicator(node) { if (file.externalModuleIndicator && file.externalModuleIndicator !== true) { return false; @@ -44045,37 +41879,32 @@ ${lanes.join("\n")} if (!setCommonJsModuleIndicator(node)) { return; } - const symbol = forEachIdentifierInEntityName( - node.arguments[0], - /*parent*/ - void 0, - (id, symbol2) => { - if (symbol2) { - addDeclarationToSymbol(symbol2, id, 1536 /* Module */ | 67108864 /* Assignment */); - } - return symbol2; + const symbol = forEachIdentifierInEntityName(node.arguments[0], /*parent*/ + void 0, (id, symbol2) => { + if (symbol2) { + addDeclarationToSymbol(symbol2, id, 1536 /* Module */ | 67108864 /* Assignment */); } - ); + + return symbol2; + }); if (symbol) { const flags = 4 /* Property */ | 1048576 /* ExportValue */; declareSymbol(symbol.exports, symbol, node, flags, 0 /* None */); } } + function bindExportsPropertyAssignment(node) { if (!setCommonJsModuleIndicator(node)) { return; } - const symbol = forEachIdentifierInEntityName( - node.left.expression, - /*parent*/ - void 0, - (id, symbol2) => { - if (symbol2) { - addDeclarationToSymbol(symbol2, id, 1536 /* Module */ | 67108864 /* Assignment */); - } - return symbol2; + const symbol = forEachIdentifierInEntityName(node.left.expression, /*parent*/ + void 0, (id, symbol2) => { + if (symbol2) { + addDeclarationToSymbol(symbol2, id, 1536 /* Module */ | 67108864 /* Assignment */); } - ); + + return symbol2; + }); if (symbol) { const isAlias = isAliasableExpression(node.right) && (isExportsIdentifier(node.left.expression) || isModuleExportsAccessExpression(node.left.expression)); const flags = isAlias ? 2097152 /* Alias */ : 4 /* Property */ | 1048576 /* ExportValue */; @@ -44083,6 +41912,7 @@ ${lanes.join("\n")} declareSymbol(symbol.exports, symbol, node.left, flags, 0 /* None */); } } + function bindModuleExportsAssignment(node) { if (!setCommonJsModuleIndicator(node)) { return; @@ -44102,19 +41932,16 @@ ${lanes.join("\n")} function bindExportAssignedObjectMemberAlias(node) { declareSymbol(file.symbol.exports, file.symbol, node, 2097152 /* Alias */ | 67108864 /* Assignment */, 0 /* None */); } + function bindThisPropertyAssignment(node) { Debug.assert(isInJSFile(node)); const hasPrivateIdentifier = isBinaryExpression(node) && isPropertyAccessExpression(node.left) && isPrivateIdentifier(node.left.name) || isPropertyAccessExpression(node) && isPrivateIdentifier(node.name); if (hasPrivateIdentifier) { return; } - const thisContainer = getThisContainer( - node, - /*includeArrowFunctions*/ - false, - /*includeClassComputedPropertyName*/ - false - ); + const thisContainer = getThisContainer(node, /*includeArrowFunctions*/ + false, /*includeClassComputedPropertyName*/ + false); switch (thisContainer.kind) { case 262 /* FunctionDeclaration */: case 218 /* FunctionExpression */: @@ -44132,8 +41959,10 @@ ${lanes.join("\n")} } else { declareSymbol(constructorSymbol.members, constructorSymbol, node, 4 /* Property */ | 67108864 /* Assignment */, 0 /* PropertyExcludes */ & ~4 /* Property */); } + addDeclarationToSymbol(constructorSymbol, constructorSymbol.valueDeclaration, 32 /* Class */); } + break; case 176 /* Constructor */: case 172 /* PropertyDeclaration */: @@ -44146,15 +41975,8 @@ ${lanes.join("\n")} if (hasDynamicName(node)) { bindDynamicallyNamedThisPropertyAssignment(node, containingClass.symbol, symbolTable); } else { - declareSymbol( - symbolTable, - containingClass.symbol, - node, - 4 /* Property */ | 67108864 /* Assignment */, - 0 /* None */, - /*isReplaceableByMethod*/ - true - ); + declareSymbol(symbolTable, containingClass.symbol, node, 4 /* Property */ | 67108864 /* Assignment */, 0 /* None */, /*isReplaceableByMethod*/ + true); } break; case 312 /* SourceFile */: @@ -44165,6 +41987,7 @@ ${lanes.join("\n")} } else { declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 111550 /* FunctionScopedVariableExcludes */); } + break; case 267 /* ModuleDeclaration */: break; @@ -44173,22 +41996,14 @@ ${lanes.join("\n")} } } function bindDynamicallyNamedThisPropertyAssignment(node, symbol, symbolTable) { - declareSymbol( - symbolTable, - symbol, - node, - 4 /* Property */, - 0 /* None */, - /*isReplaceableByMethod*/ - true, - /*isComputedName*/ - true - ); + declareSymbol(symbolTable, symbol, node, 4 /* Property */, 0 /* None */, /*isReplaceableByMethod*/ + true, /*isComputedName*/ + true); addLateBoundAssignmentDeclarationToSymbol(node, symbol); } function addLateBoundAssignmentDeclarationToSymbol(node, symbol) { if (symbol) { - (symbol.assignmentDeclarationMembers || (symbol.assignmentDeclarationMembers = /* @__PURE__ */ new Map())).set(getNodeId(node), node); + (symbol.assignmentDeclarationMembers || (symbol.assignmentDeclarationMembers = /* @__PURE__ */new Map())).set(getNodeId(node), node); } } function bindSpecialPropertyDeclaration(node) { @@ -44205,26 +42020,18 @@ ${lanes.join("\n")} function bindPrototypeAssignment(node) { setParent(node.left, node); setParent(node.right, node); - bindPropertyAssignment( - node.left.expression, - node.left, - /*isPrototypeProperty*/ - false, - /*containerIsClass*/ - true - ); + bindPropertyAssignment(node.left.expression, node.left, /*isPrototypeProperty*/ + false, /*containerIsClass*/ + true); } function bindObjectDefinePrototypeProperty(node) { const namespaceSymbol = lookupSymbolForPropertyAccess(node.arguments[0].expression); if (namespaceSymbol && namespaceSymbol.valueDeclaration) { addDeclarationToSymbol(namespaceSymbol, namespaceSymbol.valueDeclaration, 32 /* Class */); } - bindPotentiallyNewExpandoMemberToNamespace( - node, - namespaceSymbol, - /*isPrototypeProperty*/ - true - ); + + bindPotentiallyNewExpandoMemberToNamespace(node, namespaceSymbol, /*isPrototypeProperty*/ + true); } function bindPrototypePropertyAssignment(lhs, parent3) { const classPrototype = lhs.expression; @@ -44232,33 +42039,18 @@ ${lanes.join("\n")} setParent(constructorFunction, classPrototype); setParent(classPrototype, lhs); setParent(lhs, parent3); - bindPropertyAssignment( - constructorFunction, - lhs, - /*isPrototypeProperty*/ - true, - /*containerIsClass*/ - true - ); + bindPropertyAssignment(constructorFunction, lhs, /*isPrototypeProperty*/ + true, /*containerIsClass*/ + true); } function bindObjectDefinePropertyAssignment(node) { let namespaceSymbol = lookupSymbolForPropertyAccess(node.arguments[0]); const isToplevel = node.parent.parent.kind === 312 /* SourceFile */; - namespaceSymbol = bindPotentiallyMissingNamespaces( - namespaceSymbol, - node.arguments[0], - isToplevel, - /*isPrototypeProperty*/ - false, - /*containerIsClass*/ - false - ); - bindPotentiallyNewExpandoMemberToNamespace( - node, - namespaceSymbol, - /*isPrototypeProperty*/ - false - ); + namespaceSymbol = bindPotentiallyMissingNamespaces(namespaceSymbol, node.arguments[0], isToplevel, /*isPrototypeProperty*/ + false, /*containerIsClass*/ + false); + bindPotentiallyNewExpandoMemberToNamespace(node, namespaceSymbol, /*isPrototypeProperty*/ + false); } function bindSpecialPropertyAssignment(node) { var _a; @@ -44276,15 +42068,9 @@ ${lanes.join("\n")} bindExportsPropertyAssignment(node); } else if (hasDynamicName(node)) { bindAnonymousDeclaration(node, 4 /* Property */ | 67108864 /* Assignment */, "__computed" /* Computed */); - const sym = bindPotentiallyMissingNamespaces( - parentSymbol, - node.left.expression, - isTopLevelNamespaceAssignment(node.left), - /*isPrototypeProperty*/ - false, - /*containerIsClass*/ - false - ); + const sym = bindPotentiallyMissingNamespaces(parentSymbol, node.left.expression, isTopLevelNamespaceAssignment(node.left), /*isPrototypeProperty*/ + false, /*containerIsClass*/ + false); addLateBoundAssignmentDeclarationToSymbol(node, sym); } else { bindStaticPropertyAssignment(cast(node.left, isBindableStaticNameExpression)); @@ -44293,14 +42079,9 @@ ${lanes.join("\n")} function bindStaticPropertyAssignment(node) { Debug.assert(!isIdentifier(node)); setParent(node.expression, node); - bindPropertyAssignment( - node.expression, - node, - /*isPrototypeProperty*/ - false, - /*containerIsClass*/ - false - ); + bindPropertyAssignment(node.expression, node, /*isPrototypeProperty*/ + false, /*containerIsClass*/ + false); } function bindPotentiallyMissingNamespaces(namespaceSymbol, entityName, isToplevel, isPrototypeProperty, containerIsClass) { if ((namespaceSymbol == null ? void 0 : namespaceSymbol.flags) & 2097152 /* Alias */) { @@ -44322,6 +42103,7 @@ ${lanes.join("\n")} if (containerIsClass && namespaceSymbol && namespaceSymbol.valueDeclaration) { addDeclarationToSymbol(namespaceSymbol, namespaceSymbol.valueDeclaration, 32 /* Class */); } + return namespaceSymbol; } function bindPotentiallyNewExpandoMemberToNamespace(declaration, namespaceSymbol, isPrototypeProperty) { @@ -44335,14 +42117,15 @@ ${lanes.join("\n")} includes = 8192 /* Method */; excludes = 103359 /* MethodExcludes */; } else if (isCallExpression(declaration) && isBindableObjectDefinePropertyCall(declaration)) { - if (some(declaration.arguments[2].properties, (p) => { + if (some(declaration.arguments[2].properties, p => { const id = getNameOfDeclaration(p); return !!id && isIdentifier(id) && idText(id) === "set"; })) { includes |= 65536 /* SetAccessor */ | 4 /* Property */; excludes |= 78783 /* SetAccessorExcludes */; } - if (some(declaration.arguments[2].properties, (p) => { + + if (some(declaration.arguments[2].properties, p => { const id = getNameOfDeclaration(p); return !!id && isIdentifier(id) && idText(id) === "get"; })) { @@ -44350,15 +42133,19 @@ ${lanes.join("\n")} excludes |= 46015 /* GetAccessorExcludes */; } } + if (includes === 0 /* None */) { includes = 4 /* Property */; excludes = 0 /* PropertyExcludes */; } + declareSymbol(symbolTable, namespaceSymbol, declaration, includes | 67108864 /* Assignment */, excludes & ~67108864 /* Assignment */); } + function isTopLevelNamespaceAssignment(propertyAccess) { return isBinaryExpression(propertyAccess.parent) ? getParentOfBinaryExpression(propertyAccess.parent).parent.kind === 312 /* SourceFile */ : propertyAccess.parent.parent.kind === 312 /* SourceFile */; } + function bindPropertyAssignment(name, propertyAccess, isPrototypeProperty, containerIsClass) { let namespaceSymbol = lookupSymbolForPropertyAccess(name, container) || lookupSymbolForPropertyAccess(name, blockScopeContainer); const isToplevel = isTopLevelNamespaceAssignment(propertyAccess); @@ -44410,11 +42197,8 @@ ${lanes.join("\n")} } } function bindCallExpression(node) { - if (!file.commonJsModuleIndicator && isRequireCall( - node, - /*requireStringLiteralLikeArgument*/ - false - )) { + if (!file.commonJsModuleIndicator && isRequireCall(node, /*requireStringLiteralLikeArgument*/ + false)) { setCommonJsModuleIndicator(node); } } @@ -44428,7 +42212,9 @@ ${lanes.join("\n")} classifiableNames.add(node.name.escapedText); } } - const { symbol } = node; + const { + symbol + } = node; const prototypeSymbol = createSymbol(4 /* Property */ | 4194304 /* Prototype */, "prototype"); const symbolExport = symbol.exports.get(prototypeSymbol.escapedName); if (symbolExport) { @@ -44443,6 +42229,7 @@ ${lanes.join("\n")} function bindEnumDeclaration(node) { return isEnumConst(node) ? bindBlockScopedDeclaration(node, 128 /* ConstEnum */, 899967 /* ConstEnumExcludes */) : bindBlockScopedDeclaration(node, 256 /* RegularEnum */, 899327 /* RegularEnumExcludes */); } + function bindVariableDeclarationOrBindingElement(node) { if (inStrictMode) { checkStrictModeEvalOrArguments(node, node.name); @@ -44460,6 +42247,7 @@ ${lanes.join("\n")} } } } + function bindParameter(node) { if (node.kind === 348 /* JSDocParameterTag */ && container.kind !== 330 /* JSDocSignature */) { return; @@ -44472,17 +42260,20 @@ ${lanes.join("\n")} } else { declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 111551 /* ParameterExcludes */); } + if (isParameterPropertyDeclaration(node, node.parent)) { const classDeclaration = node.parent.parent; declareSymbol(classDeclaration.symbol.members, classDeclaration.symbol, node, 4 /* Property */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), 0 /* PropertyExcludes */); } } + function bindFunctionDeclaration(node) { if (!file.isDeclarationFile && !(node.flags & 33554432 /* Ambient */)) { if (isAsyncFunction(node)) { emitFlags |= 4096 /* HasAsyncFunctions */; } } + checkStrictModeFunctionName(node); if (inStrictMode) { checkStrictModeFunctionDeclaration(node); @@ -44491,12 +42282,14 @@ ${lanes.join("\n")} declareSymbolAndAddToSymbolTable(node, 16 /* Function */, 110991 /* FunctionExcludes */); } } + function bindFunctionExpression(node) { if (!file.isDeclarationFile && !(node.flags & 33554432 /* Ambient */)) { if (isAsyncFunction(node)) { emitFlags |= 4096 /* HasAsyncFunctions */; } } + if (currentFlow) { node.flowNode = currentFlow; } @@ -44508,45 +42301,36 @@ ${lanes.join("\n")} if (!file.isDeclarationFile && !(node.flags & 33554432 /* Ambient */) && isAsyncFunction(node)) { emitFlags |= 4096 /* HasAsyncFunctions */; } + if (currentFlow && isObjectLiteralOrClassExpressionMethodOrAccessor(node)) { node.flowNode = currentFlow; } return hasDynamicName(node) ? bindAnonymousDeclaration(node, symbolFlags, "__computed" /* Computed */) : declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes); } function getInferTypeContainer(node) { - const extendsType = findAncestor(node, (n) => n.parent && isConditionalTypeNode(n.parent) && n.parent.extendsType === n); + const extendsType = findAncestor(node, n => n.parent && isConditionalTypeNode(n.parent) && n.parent.extendsType === n); return extendsType && extendsType.parent; } function bindTypeParameter(node) { if (isJSDocTemplateTag(node.parent)) { const container2 = getEffectiveContainerForJSDocTemplateTag(node.parent); if (container2) { + var _container2$locals; Debug.assertNode(container2, canHaveLocals); - container2.locals ?? (container2.locals = createSymbolTable()); - declareSymbol( - container2.locals, - /*parent*/ - void 0, - node, - 262144 /* TypeParameter */, - 526824 /* TypeParameterExcludes */ - ); + (_container2$locals = container2.locals) !== null && _container2$locals !== void 0 ? _container2$locals : container2.locals = createSymbolTable(); + declareSymbol(container2.locals, /*parent*/ + void 0, node, 262144 /* TypeParameter */, 526824 /* TypeParameterExcludes */); } else { declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 526824 /* TypeParameterExcludes */); } } else if (node.parent.kind === 195 /* InferType */) { const container2 = getInferTypeContainer(node.parent); if (container2) { + var _container2$locals2; Debug.assertNode(container2, canHaveLocals); - container2.locals ?? (container2.locals = createSymbolTable()); - declareSymbol( - container2.locals, - /*parent*/ - void 0, - node, - 262144 /* TypeParameter */, - 526824 /* TypeParameterExcludes */ - ); + (_container2$locals2 = container2.locals) !== null && _container2$locals2 !== void 0 ? _container2$locals2 : container2.locals = createSymbolTable(); + declareSymbol(container2.locals, /*parent*/ + void 0, node, 262144 /* TypeParameter */, 526824 /* TypeParameterExcludes */); } else { bindAnonymousDeclaration(node, 262144 /* TypeParameter */, getDeclarationName(node)); } @@ -44554,6 +42338,7 @@ ${lanes.join("\n")} declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 526824 /* TypeParameterExcludes */); } } + function shouldReportErrorOnModuleDeclaration(node) { const instanceState = getModuleInstanceState(node); return instanceState === 1 /* Instantiated */ || instanceState === 2 /* ConstEnumOnly */ && shouldPreserveConstEnums(options); @@ -44563,16 +42348,17 @@ ${lanes.join("\n")} return false; } if (currentFlow === unreachableFlow) { - const reportError = ( - // report error on all statements except empty ones - isStatementButNotDeclaration(node) && node.kind !== 242 /* EmptyStatement */ || // report error on class declarations - node.kind === 263 /* ClassDeclaration */ || // report error on instantiated modules or const-enums only modules if preserveConstEnums is set - node.kind === 267 /* ModuleDeclaration */ && shouldReportErrorOnModuleDeclaration(node) - ); + const reportError = + // report error on all statements except empty ones + isStatementButNotDeclaration(node) && node.kind !== 242 /* EmptyStatement */ || + // report error on class declarations + node.kind === 263 /* ClassDeclaration */ || + // report error on instantiated modules or const-enums only modules if preserveConstEnums is set + node.kind === 267 /* ModuleDeclaration */ && shouldReportErrorOnModuleDeclaration(node); if (reportError) { currentFlow = reportedUnreachableFlow; if (!options.allowUnreachableCode) { - const isError = unreachableCodeIsError(options) && !(node.flags & 33554432 /* Ambient */) && (!isVariableStatement(node) || !!(getCombinedNodeFlags(node.declarationList) & 7 /* BlockScoped */) || node.declarationList.declarations.some((d) => !!d.initializer)); + const isError = unreachableCodeIsError(options) && !(node.flags & 33554432 /* Ambient */) && (!isVariableStatement(node) || !!(getCombinedNodeFlags(node.declarationList) & 7 /* BlockScoped */) || node.declarationList.declarations.some(d => !!d.initializer)); eachUnreachableRange(node, (start, end) => errorOrSuggestionOnRange(isError, start, end, Diagnostics.Unreachable_code_detected)); } } @@ -44582,7 +42368,9 @@ ${lanes.join("\n")} } function eachUnreachableRange(node, cb) { if (isStatement(node) && isExecutableStatement(node) && isBlock(node.parent)) { - const { statements } = node.parent; + const { + statements + } = node.parent; const slice = sliceAfter(statements, node); getRangesWhere(slice, isExecutableStatement, (start, afterEnd) => cb(slice[start], slice[afterEnd - 1])); } else { @@ -44590,8 +42378,9 @@ ${lanes.join("\n")} } } function isExecutableStatement(s) { - return !isFunctionDeclaration(s) && !isPurelyTypeDeclaration(s) && !isEnumDeclaration(s) && // `var x;` may declare a variable used above - !(isVariableStatement(s) && !(getCombinedNodeFlags(s) & 7 /* BlockScoped */) && s.declarationList.declarations.some((d) => !d.initializer)); + return !isFunctionDeclaration(s) && !isPurelyTypeDeclaration(s) && !isEnumDeclaration(s) && + // `var x;` may declare a variable used above + !(isVariableStatement(s) && !(getCombinedNodeFlags(s) & 7 /* BlockScoped */) && s.declarationList.declarations.some(d => !d.initializer)); } function isPurelyTypeDeclaration(s) { switch (s.kind) { @@ -44620,11 +42409,8 @@ ${lanes.join("\n")} if (!!symbol && !!symbol.valueDeclaration && isVariableDeclaration(symbol.valueDeclaration) && !!symbol.valueDeclaration.initializer) { const init = symbol.valueDeclaration.initializer; q.enqueue(init); - if (isAssignmentExpression( - init, - /*excludeCompoundAssignment*/ - true - )) { + if (isAssignmentExpression(init, /*excludeCompoundAssignment*/ + true)) { q.enqueue(init.left); q.enqueue(init.right); } @@ -44658,6 +42444,7 @@ ${lanes.join("\n")} if (isObjectLiteralOrClassExpressionMethodOrAccessor(node)) { return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */ | 128 /* IsObjectLiteralOrClassExpressionMethodOrAccessor */; } + case 176 /* Constructor */: case 262 /* FunctionDeclaration */: case 173 /* MethodSignature */: @@ -44685,13 +42472,16 @@ ${lanes.join("\n")} case 241 /* Block */: return isFunctionLike(node.parent) || isClassStaticBlockDeclaration(node.parent) ? 0 /* None */ : 2 /* IsBlockScopedContainer */ | 32 /* HasLocals */; } + return 0 /* None */; } + function lookupSymbolForName(container, name) { var _a, _b, _c, _d; const local = (_b = (_a = tryCast(container, canHaveLocals)) == null ? void 0 : _a.locals) == null ? void 0 : _b.get(name); if (local) { - return local.exportSymbol ?? local; + var _local$exportSymbol; + return (_local$exportSymbol = local.exportSymbol) !== null && _local$exportSymbol !== void 0 ? _local$exportSymbol : local; } if (isSourceFile(container) && container.jsGlobalAugmentations && container.jsGlobalAugmentations.has(name)) { return container.jsGlobalAugmentations.get(name); @@ -44704,15 +42494,16 @@ ${lanes.join("\n")} var init_binder = __esm({ "src/compiler/binder.ts"() { "use strict"; + init_ts2(); init_ts_performance(); - ModuleInstanceState = /* @__PURE__ */ ((ModuleInstanceState2) => { + ModuleInstanceState = /* @__PURE__ */(ModuleInstanceState2 => { ModuleInstanceState2[ModuleInstanceState2["NonInstantiated"] = 0] = "NonInstantiated"; ModuleInstanceState2[ModuleInstanceState2["Instantiated"] = 1] = "Instantiated"; ModuleInstanceState2[ModuleInstanceState2["ConstEnumOnly"] = 2] = "ConstEnumOnly"; return ModuleInstanceState2; })(ModuleInstanceState || {}); - ContainerFlags = /* @__PURE__ */ ((ContainerFlags2) => { + ContainerFlags = /* @__PURE__ */(ContainerFlags2 => { ContainerFlags2[ContainerFlags2["None"] = 0] = "None"; ContainerFlags2[ContainerFlags2["IsContainer"] = 1] = "IsContainer"; ContainerFlags2[ContainerFlags2["IsBlockScopedContainer"] = 2] = "IsBlockScopedContainer"; @@ -44724,7 +42515,7 @@ ${lanes.join("\n")} ContainerFlags2[ContainerFlags2["IsObjectLiteralOrClassExpressionMethodOrAccessor"] = 128] = "IsObjectLiteralOrClassExpressionMethodOrAccessor"; return ContainerFlags2; })(ContainerFlags || {}); - binder = /* @__PURE__ */ createBinder(); + binder = /* @__PURE__ */createBinder(); } }); @@ -44735,19 +42526,25 @@ ${lanes.join("\n")} const visitedTypes = []; const visitedSymbols = []; return { - walkType: (type) => { + walkType: type => { try { visitType(type); - return { visitedTypes: getOwnValues(visitedTypes), visitedSymbols: getOwnValues(visitedSymbols) }; + return { + visitedTypes: getOwnValues(visitedTypes), + visitedSymbols: getOwnValues(visitedSymbols) + }; } finally { clear(visitedTypes); clear(visitedSymbols); } }, - walkSymbol: (symbol) => { + walkSymbol: symbol => { try { visitSymbol(symbol); - return { visitedTypes: getOwnValues(visitedTypes), visitedSymbols: getOwnValues(visitedSymbols) }; + return { + visitedTypes: getOwnValues(visitedTypes), + visitedSymbols: getOwnValues(visitedSymbols) + }; } finally { clear(visitedTypes); clear(visitedSymbols); @@ -44763,8 +42560,7 @@ ${lanes.join("\n")} } 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; @@ -44869,7 +42665,7 @@ ${lanes.join("\n")} if (symbol.exports) { symbol.exports.forEach(visitSymbol); } - forEach(symbol.declarations, (d) => { + forEach(symbol.declarations, d => { if (d.type && d.type.kind === 186 /* TypeQuery */) { const query = d.type; const entity = getResolvedSymbol(getFirstIdentifier2(query.exprName)); @@ -44883,25 +42679,32 @@ ${lanes.join("\n")} var init_symbolWalker = __esm({ "src/compiler/symbolWalker.ts"() { "use strict"; + init_ts2(); } }); // src/compiler/moduleSpecifiers.ts - function getPreferences({ importModuleSpecifierPreference, importModuleSpecifierEnding }, compilerOptions, importingSourceFile, oldImportSpecifier) { + function getPreferences({ + importModuleSpecifierPreference, + importModuleSpecifierEnding + }, compilerOptions, importingSourceFile, oldImportSpecifier) { const preferredEnding = getPreferredEnding(); return { relativePreference: oldImportSpecifier !== void 0 ? isExternalModuleNameRelative(oldImportSpecifier) ? 0 /* Relative */ : 1 /* NonRelative */ : importModuleSpecifierPreference === "relative" ? 0 /* Relative */ : importModuleSpecifierPreference === "non-relative" ? 1 /* NonRelative */ : importModuleSpecifierPreference === "project-relative" ? 3 /* ExternalNonRelative */ : 2 /* Shortest */, - getAllowedEndingsInPreferredOrder: (syntaxImpliedNodeFormat) => { - if ((syntaxImpliedNodeFormat ?? importingSourceFile.impliedNodeFormat) === 99 /* ESNext */) { + getAllowedEndingsInPreferredOrder: syntaxImpliedNodeFormat => { + if ((syntaxImpliedNodeFormat !== null && syntaxImpliedNodeFormat !== void 0 ? syntaxImpliedNodeFormat : importingSourceFile.impliedNodeFormat) === 99 /* ESNext */) { if (shouldAllowImportingTsExtension(compilerOptions, importingSourceFile.fileName)) { return [3 /* TsExtension */, 2 /* JsExtension */]; } + return [2 /* JsExtension */]; } + if (getEmitModuleResolutionKind(compilerOptions) === 1 /* Classic */) { return preferredEnding === 2 /* JsExtension */ ? [2 /* JsExtension */, 1 /* Index */] : [1 /* Index */, 2 /* JsExtension */]; } + const allowImportingTsExtension = shouldAllowImportingTsExtension(compilerOptions, importingSourceFile.fileName); switch (preferredEnding) { case 2 /* JsExtension */: @@ -44919,23 +42722,16 @@ ${lanes.join("\n")} }; function getPreferredEnding() { 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, - importingSourceFile.impliedNodeFormat, - compilerOptions, - importingSourceFile - ); + + return getModuleSpecifierEndingPreference(importModuleSpecifierEnding, importingSourceFile.impliedNodeFormat, compilerOptions, importingSourceFile); } } function updateModuleSpecifier(compilerOptions, importingSourceFile, importingSourceFileName, toFileName2, host, oldImportSpecifier, options = {}) { const res = getModuleSpecifierWorker(compilerOptions, importingSourceFile, importingSourceFileName, toFileName2, host, getPreferences({}, 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 = {}) { @@ -44944,41 +42740,17 @@ ${lanes.join("\n")} function getNodeModulesPackageName(compilerOptions, importingSourceFile, nodeModulesFileName, host, preferences, options = {}) { const info = getInfo(importingSourceFile.path, host); const modulePaths = getAllModulePaths(importingSourceFile.path, nodeModulesFileName, host, preferences, options); - return firstDefined(modulePaths, (modulePath) => tryGetModuleNameAsNodeModule( - modulePath, - info, - importingSourceFile, - host, - compilerOptions, - preferences, - /*packageNameOnly*/ - true, - options.overrideImportMode - )); + return firstDefined(modulePaths, modulePath => tryGetModuleNameAsNodeModule(modulePath, info, importingSourceFile, host, compilerOptions, preferences, /*packageNameOnly*/ + true, options.overrideImportMode)); } function getModuleSpecifierWorker(compilerOptions, importingSourceFile, importingSourceFileName, toFileName2, host, preferences, userPreferences, options = {}) { const info = getInfo(importingSourceFileName, host); const modulePaths = getAllModulePaths(importingSourceFileName, toFileName2, host, userPreferences, options); - return firstDefined(modulePaths, (modulePath) => tryGetModuleNameAsNodeModule( - modulePath, - info, - importingSourceFile, - host, - compilerOptions, - userPreferences, - /*packageNameOnly*/ - void 0, - options.overrideImportMode - )) || getLocalModuleSpecifier(toFileName2, info, compilerOptions, host, options.overrideImportMode || importingSourceFile.impliedNodeFormat, preferences); + return firstDefined(modulePaths, modulePath => tryGetModuleNameAsNodeModule(modulePath, info, importingSourceFile, host, compilerOptions, userPreferences, /*packageNameOnly*/ + void 0, options.overrideImportMode)) || getLocalModuleSpecifier(toFileName2, info, compilerOptions, host, options.overrideImportMode || importingSourceFile.impliedNodeFormat, preferences); } function tryGetModuleSpecifiersFromCache(moduleSymbol, importingSourceFile, host, userPreferences, options = {}) { - return tryGetModuleSpecifiersFromCacheWorker( - moduleSymbol, - importingSourceFile, - host, - userPreferences, - options - )[0]; + return tryGetModuleSpecifiersFromCacheWorker(moduleSymbol, importingSourceFile, host, userPreferences, options)[0]; } function tryGetModuleSpecifiersFromCacheWorker(moduleSymbol, importingSourceFile, host, userPreferences, options = {}) { var _a; @@ -44991,98 +42763,62 @@ ${lanes.join("\n")} return [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( - moduleSymbol, - checker, - compilerOptions, - importingSourceFile, - host, - userPreferences, - options, - /*forAutoImport*/ - false - ).moduleSpecifiers; + return getModuleSpecifiersWithCacheInfo(moduleSymbol, checker, compilerOptions, importingSourceFile, host, userPreferences, options, /*forAutoImport*/ + false).moduleSpecifiers; } 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( - moduleSymbol, - importingSourceFile, - host, - userPreferences, - options - ); - if (specifiers) - return { moduleSpecifiers: specifiers, computedWithoutCache }; - if (!moduleSourceFile) - return { moduleSpecifiers: emptyArray, computedWithoutCache }; + if (ambient) return { + moduleSpecifiers: [ambient], + computedWithoutCache + }; + let [specifiers, moduleSourceFile, modulePaths, cache] = tryGetModuleSpecifiersFromCacheWorker(moduleSymbol, importingSourceFile, host, userPreferences, options); + if (specifiers) return { + moduleSpecifiers: specifiers, + computedWithoutCache + }; + if (!moduleSourceFile) return { + moduleSpecifiers: emptyArray, + computedWithoutCache + }; computedWithoutCache = true; modulePaths || (modulePaths = getAllModulePathsWorker(importingSourceFile.path, moduleSourceFile.originalFileName, host)); - const result = computeModuleSpecifiers( - modulePaths, - compilerOptions, - importingSourceFile, - host, - userPreferences, - options, - forAutoImport - ); + const result = computeModuleSpecifiers(modulePaths, compilerOptions, importingSourceFile, host, userPreferences, options, forAutoImport); cache == null ? void 0 : cache.set(importingSourceFile.path, moduleSourceFile.path, userPreferences, options, modulePaths, result); - return { moduleSpecifiers: result, computedWithoutCache }; + return { + moduleSpecifiers: result, + computedWithoutCache + }; } function computeModuleSpecifiers(modulePaths, compilerOptions, importingSourceFile, host, userPreferences, options = {}, forAutoImport) { const info = getInfo(importingSourceFile.path, host); const preferences = getPreferences(userPreferences, compilerOptions, importingSourceFile); - const existingSpecifier = 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 (importingSourceFile.impliedNodeFormat && importingSourceFile.impliedNodeFormat !== getModeForResolutionAtIndex(importingSourceFile, reason.index)) - return void 0; - const specifier = getModuleNameStringLiteralAt(importingSourceFile, reason.index).text; - return preferences.relativePreference !== 1 /* NonRelative */ || !pathIsRelative(specifier) ? specifier : void 0; - } - )); + const existingSpecifier = 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 (importingSourceFile.impliedNodeFormat && importingSourceFile.impliedNodeFormat !== getModeForResolutionAtIndex(importingSourceFile, reason.index)) return void 0; + const specifier = getModuleNameStringLiteralAt(importingSourceFile, reason.index).text; + return preferences.relativePreference !== 1 /* NonRelative */ || !pathIsRelative(specifier) ? specifier : void 0; + })); if (existingSpecifier) { const moduleSpecifiers = [existingSpecifier]; return moduleSpecifiers; } - const importedFileIsInNodeModules = some(modulePaths, (p) => p.isInNodeModules); + const importedFileIsInNodeModules = some(modulePaths, p => p.isInNodeModules); let nodeModulesSpecifiers; let pathsSpecifiers; let redirectPathsSpecifiers; let relativeSpecifiers; for (const modulePath of modulePaths) { - const specifier = modulePath.isInNodeModules ? tryGetModuleNameAsNodeModule( - modulePath, - info, - importingSourceFile, - host, - compilerOptions, - userPreferences, - /*packageNameOnly*/ - void 0, - options.overrideImportMode - ) : void 0; + const specifier = modulePath.isInNodeModules ? tryGetModuleNameAsNodeModule(modulePath, info, importingSourceFile, host, compilerOptions, userPreferences, /*packageNameOnly*/ + void 0, options.overrideImportMode) : void 0; nodeModulesSpecifiers = append(nodeModulesSpecifiers, specifier); if (specifier && modulePath.isRedirect) { return nodeModulesSpecifiers; } if (!specifier) { - const local = getLocalModuleSpecifier( - modulePath.path, - info, - compilerOptions, - host, - options.overrideImportMode || importingSourceFile.impliedNodeFormat, - preferences, - /*pathsOnly*/ - modulePath.isRedirect - ); + const local = getLocalModuleSpecifier(modulePath.path, info, compilerOptions, host, options.overrideImportMode || importingSourceFile.impliedNodeFormat, preferences, /*pathsOnly*/ + modulePath.isRedirect); if (!local) { continue; } @@ -45100,14 +42836,28 @@ ${lanes.join("\n")} function getInfo(importingSourceFileName, host) { const getCanonicalFileName = createGetCanonicalFileName(host.useCaseSensitiveFileNames ? host.useCaseSensitiveFileNames() : true); const sourceDirectory = getDirectoryPath(importingSourceFileName); - return { getCanonicalFileName, importingSourceFileName, sourceDirectory }; + return { + getCanonicalFileName, + importingSourceFileName, + sourceDirectory + }; } - function getLocalModuleSpecifier(moduleFileName, info, compilerOptions, host, importMode, { getAllowedEndingsInPreferredOrder: getAllowedEndingsInPrefererredOrder, relativePreference }, pathsOnly) { - const { baseUrl, paths, rootDirs } = compilerOptions; + function getLocalModuleSpecifier(moduleFileName, info, compilerOptions, host, importMode, { + getAllowedEndingsInPreferredOrder: getAllowedEndingsInPrefererredOrder, + relativePreference + }, pathsOnly) { + const { + baseUrl, + paths, + rootDirs + } = compilerOptions; if (pathsOnly && !paths) { return void 0; } - const { sourceDirectory, getCanonicalFileName } = info; + const { + sourceDirectory, + getCanonicalFileName + } = info; const allowedEndings = getAllowedEndingsInPrefererredOrder(importMode); const relativePath = rootDirs && tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName, allowedEndings, compilerOptions) || processEnding(ensurePathIsNonModuleName(getRelativePathFromDirectory(sourceDirectory, moduleFileName, getCanonicalFileName)), allowedEndings, compilerOptions); if (!baseUrl && !paths || relativePreference === 0 /* Relative */) { @@ -45149,8 +42899,7 @@ ${lanes.join("\n")} 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; } @@ -45161,7 +42910,7 @@ ${lanes.join("\n")} if (host.getNearestAncestorDirectoryWithPackageJson) { return host.getNearestAncestorDirectoryWithPackageJson(fileName); } - return !!forEachAncestorDirectory(fileName, (directory) => { + return !!forEachAncestorDirectory(fileName, directory => { return host.fileExists(combinePaths(directory, "package.json")) ? true : void 0; }); } @@ -45172,24 +42921,22 @@ ${lanes.join("\n")} const referenceRedirect = host.isSourceOfProjectReferenceRedirect(importedFileName) ? host.getProjectReferenceRedirect(importedFileName) : void 0; const importedPath = toPath(importedFileName, cwd, getCanonicalFileName); const redirects = host.redirectTargetsMap.get(importedPath) || emptyArray; - const importedFileNames = [...referenceRedirect ? [referenceRedirect] : emptyArray, importedFileName, ...redirects]; - const targets = importedFileNames.map((f) => getNormalizedAbsolutePath(f, cwd)); + const importedFileNames = [...(referenceRedirect ? [referenceRedirect] : emptyArray), importedFileName, ...redirects]; + const targets = importedFileNames.map(f => getNormalizedAbsolutePath(f, cwd)); let shouldFilterIgnoredPaths = !every(targets, containsIgnoredPath); if (!preferSymlinks) { - const result2 = forEach(targets, (p) => !(shouldFilterIgnoredPaths && containsIgnoredPath(p)) && cb(p, referenceRedirect === p)); - if (result2) - return result2; + const result2 = forEach(targets, p => !(shouldFilterIgnoredPaths && containsIgnoredPath(p)) && cb(p, referenceRedirect === p)); + 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 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; } - return forEach(targets, (target) => { + return forEach(targets, target => { if (!startsWithDirectory(target, realPathDirectory, getCanonicalFileName)) { return; } @@ -45198,12 +42945,11 @@ ${lanes.join("\n")} const option = resolvePath(symlinkDirectory, relative); const result2 = cb(option, target === referenceRedirect); shouldFilterIgnoredPaths = true; - if (result2) - return result2; + if (result2) return result2; } }); }); - return result || (preferSymlinks ? forEach(targets, (p) => shouldFilterIgnoredPaths && containsIgnoredPath(p) ? void 0 : cb(p, p === referenceRedirect)) : void 0); + return result || (preferSymlinks ? forEach(targets, p => shouldFilterIgnoredPaths && containsIgnoredPath(p) ? void 0 : cb(p, p === referenceRedirect)) : void 0); } function getAllModulePaths(importingFilePath, importedFileName, host, preferences, options = {}) { var _a; @@ -45211,8 +42957,7 @@ ${lanes.join("\n")} 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(importingFilePath, importedFileName, host); if (cache) { @@ -45222,27 +42967,33 @@ ${lanes.join("\n")} } function getAllModulePathsWorker(importingFileName, importedFileName, host) { const getCanonicalFileName = hostGetCanonicalFileName(host); - const allFileNames = /* @__PURE__ */ new Map(); + const allFileNames = /* @__PURE__ */new Map(); let importedFileFromNodeModules = false; - forEachFileNameOfModule( - importingFileName, - importedFileName, - host, - /*preferSymlinks*/ - true, - (path, isRedirect) => { - const isInNodeModules = pathContainsNodeModules(path); - allFileNames.set(path, { path: getCanonicalFileName(path), isRedirect, isInNodeModules }); - importedFileFromNodeModules = importedFileFromNodeModules || isInNodeModules; - } - ); + forEachFileNameOfModule(importingFileName, importedFileName, host, /*preferSymlinks*/ + true, (path, isRedirect) => { + const isInNodeModules = pathContainsNodeModules(path); + allFileNames.set(path, { + path: getCanonicalFileName(path), + isRedirect, + isInNodeModules + }); + importedFileFromNodeModules = importedFileFromNodeModules || isInNodeModules; + }); const sortedPaths = []; - for (let directory = getDirectoryPath(importingFileName); allFileNames.size !== 0; ) { + for (let directory = getDirectoryPath(importingFileName); allFileNames.size !== 0;) { const directoryStart = ensureTrailingDirectorySeparator(directory); let pathsInDirectory; - allFileNames.forEach(({ path, isRedirect, isInNodeModules }, fileName) => { + allFileNames.forEach(({ + path, + isRedirect, + isInNodeModules + }, fileName) => { if (startsWith(path, directoryStart)) { - (pathsInDirectory || (pathsInDirectory = [])).push({ path: fileName, isRedirect, isInNodeModules }); + (pathsInDirectory || (pathsInDirectory = [])).push({ + path: fileName, + isRedirect, + isInNodeModules + }); allFileNames.delete(fileName); } }); @@ -45253,42 +43004,33 @@ ${lanes.join("\n")} sortedPaths.push(...pathsInDirectory); } const newDirectory = getDirectoryPath(directory); - if (newDirectory === directory) - break; + if (newDirectory === directory) break; directory = newDirectory; } if (allFileNames.size) { const remainingPaths = arrayFrom(allFileNames.values()); - if (remainingPaths.length > 1) - remainingPaths.sort(comparePathsByRedirectAndNumberOfDirectorySeparators); + if (remainingPaths.length > 1) remainingPaths.sort(comparePathsByRedirectAndNumberOfDirectorySeparators); sortedPaths.push(...remainingPaths); } return sortedPaths; } function tryGetModuleNameFromAmbientModule(moduleSymbol, checker) { var _a; - const decl = (_a = moduleSymbol.declarations) == null ? void 0 : _a.find( - (d) => isNonGlobalAmbientModule(d) && (!isExternalModuleAugmentation(d) || !isExternalModuleNameRelative(getTextOfIdentifierOrLiteral(d.name))) - ); + const decl = (_a = moduleSymbol.declarations) == null ? void 0 : _a.find(d => isNonGlobalAmbientModule(d) && (!isExternalModuleAugmentation(d) || !isExternalModuleNameRelative(getTextOfIdentifierOrLiteral(d.name)))); if (decl) { return decl.name.text; } - const ambientModuleDeclareCandidates = mapDefined(moduleSymbol.declarations, (d) => { + 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; @@ -45306,60 +43048,66 @@ ${lanes.join("\n")} for (const patternText2 of paths[key]) { const pattern = normalizePath(patternText2); const indexOfStar = pattern.indexOf("*"); - const candidates = allowedEndings.map((ending) => ({ + const candidates = allowedEndings.map(ending => ({ ending, value: processEnding(relativeToBaseUrl, [ending], compilerOptions) })); if (tryGetExtensionFromPath2(pattern)) { - candidates.push({ ending: void 0, value: relativeToBaseUrl }); + candidates.push({ + ending: void 0, + value: relativeToBaseUrl + }); } if (indexOfStar !== -1) { const prefix = pattern.substring(0, indexOfStar); const suffix = pattern.substring(indexOfStar + 1); - for (const { ending, value } of candidates) { - if (value.length >= prefix.length + suffix.length && startsWith(value, prefix) && endsWith(value, suffix) && validateEnding({ ending, value })) { + for (const { + ending, + value + } of candidates) { + if (value.length >= prefix.length + suffix.length && startsWith(value, prefix) && endsWith(value, suffix) && validateEnding({ + ending, + value + })) { const matchedStar = value.substring(prefix.length, value.length - suffix.length); if (!pathIsRelative(matchedStar)) { return key.replace("*", matchedStar); } } } - } else if (some(candidates, (c) => c.ending !== 0 /* Minimal */ && pattern === c.value) || some(candidates, (c) => c.ending === 0 /* Minimal */ && pattern === c.value && validateEnding(c))) { + } else if (some(candidates, c => c.ending !== 0 /* Minimal */ && pattern === c.value) || some(candidates, c => c.ending === 0 /* Minimal */ && pattern === c.value && validateEnding(c))) { return key; } } } - function validateEnding({ ending, value }) { + function validateEnding({ + ending, + value + }) { return ending !== 0 /* Minimal */ || value === processEnding(relativeToBaseUrl, [ending], compilerOptions, host); } } function tryGetModuleNameFromExports(options, targetFilePath, packageDirectory, packageName, exports, conditions, mode = 0 /* Exact */) { if (typeof exports === "string") { - const pathOrPattern = getNormalizedAbsolutePath( - combinePaths(packageDirectory, exports), - /*currentDirectory*/ - void 0 - ); + const pathOrPattern = getNormalizedAbsolutePath(combinePaths(packageDirectory, exports), /*currentDirectory*/ + void 0); const extensionSwappedTarget = hasTSFileExtension(targetFilePath) ? removeFileExtension(targetFilePath) + tryGetJSExtensionForFile(targetFilePath, options) : void 0; switch (mode) { case 0 /* Exact */: if (comparePaths(targetFilePath, pathOrPattern) === 0 /* EqualTo */ || extensionSwappedTarget && comparePaths(extensionSwappedTarget, pathOrPattern) === 0 /* EqualTo */) { - return { moduleFileToTry: packageName }; + return { + moduleFileToTry: packageName + }; } break; case 1 /* Directory */: if (containsPath(pathOrPattern, targetFilePath)) { - const fragment = getRelativePathFromDirectory( - pathOrPattern, - targetFilePath, - /*ignoreCase*/ - false - ); - return { moduleFileToTry: getNormalizedAbsolutePath( - combinePaths(combinePaths(packageName, exports), fragment), - /*currentDirectory*/ - void 0 - ) }; + const fragment = getRelativePathFromDirectory(pathOrPattern, targetFilePath, /*ignoreCase*/ + false); + return { + moduleFileToTry: getNormalizedAbsolutePath(combinePaths(combinePaths(packageName, exports), fragment), /*currentDirectory*/ + void 0) + }; } break; case 2 /* Pattern */: @@ -45368,24 +43116,25 @@ ${lanes.join("\n")} const trailingSlice = pathOrPattern.slice(starPos + 1); if (startsWith(targetFilePath, leadingSlice) && endsWith(targetFilePath, trailingSlice)) { const starReplacement = targetFilePath.slice(leadingSlice.length, targetFilePath.length - trailingSlice.length); - return { moduleFileToTry: packageName.replace("*", starReplacement) }; + return { + moduleFileToTry: packageName.replace("*", starReplacement) + }; } if (extensionSwappedTarget && startsWith(extensionSwappedTarget, leadingSlice) && endsWith(extensionSwappedTarget, trailingSlice)) { const starReplacement = extensionSwappedTarget.slice(leadingSlice.length, extensionSwappedTarget.length - trailingSlice.length); - return { moduleFileToTry: packageName.replace("*", starReplacement) }; + return { + moduleFileToTry: packageName.replace("*", starReplacement) + }; } break; } } else if (Array.isArray(exports)) { - return forEach(exports, (e) => tryGetModuleNameFromExports(options, targetFilePath, packageDirectory, packageName, e, conditions)); + return forEach(exports, e => tryGetModuleNameFromExports(options, targetFilePath, packageDirectory, packageName, e, conditions)); } else if (typeof exports === "object" && exports !== null) { if (allKeysStartWithDot(exports)) { - return forEach(getOwnKeys(exports), (k) => { - const subPackageName = getNormalizedAbsolutePath( - combinePaths(packageName, k), - /*currentDirectory*/ - void 0 - ); + return forEach(getOwnKeys(exports), k => { + const subPackageName = getNormalizedAbsolutePath(combinePaths(packageName, k), /*currentDirectory*/ + void 0); const mode2 = endsWith(k, "/") ? 1 /* Directory */ : k.includes("*") ? 2 /* Pattern */ : 0 /* Exact */; return tryGetModuleNameFromExports(options, targetFilePath, packageDirectory, subPackageName, exports[k], conditions, mode2); }); @@ -45409,8 +43158,8 @@ ${lanes.join("\n")} return void 0; } const normalizedSourcePaths = getPathsRelativeToRootDirs(sourceDirectory, rootDirs, getCanonicalFileName); - const relativePaths = flatMap(normalizedSourcePaths, (sourcePath) => { - return map(normalizedTargetPaths, (targetPath) => ensurePathIsNonModuleName(getRelativePathFromDirectory(sourcePath, targetPath, getCanonicalFileName))); + const relativePaths = flatMap(normalizedSourcePaths, sourcePath => { + return map(normalizedTargetPaths, targetPath => ensurePathIsNonModuleName(getRelativePathFromDirectory(sourcePath, targetPath, getCanonicalFileName))); }); const shortest = min(relativePaths, compareNumberOfDirectorySeparators); if (!shortest) { @@ -45418,7 +43167,13 @@ ${lanes.join("\n")} } return processEnding(shortest, allowedEndings, compilerOptions); } - function tryGetModuleNameAsNodeModule({ path, isRedirect }, { getCanonicalFileName, sourceDirectory }, importingSourceFile, host, options, userPreferences, packageNameOnly, overrideMode) { + function tryGetModuleNameAsNodeModule({ + path, + isRedirect + }, { + getCanonicalFileName, + sourceDirectory + }, importingSourceFile, host, options, userPreferences, packageNameOnly, overrideMode) { if (!host.fileExists || !host.readFile) { return void 0; } @@ -45434,7 +43189,12 @@ ${lanes.join("\n")} let packageRootIndex = parts.packageRootIndex; let moduleFileName; while (true) { - const { moduleFileToTry, packageRootPath, blockedByExports, verbatimFromExports } = tryDirectoryWithPackageJson(packageRootIndex); + const { + moduleFileToTry, + packageRootPath, + blockedByExports, + verbatimFromExports + } = tryDirectoryWithPackageJson(packageRootIndex); if (getEmitModuleResolutionKind(options) !== 1 /* Classic */) { if (blockedByExports) { return void 0; @@ -45448,8 +43208,7 @@ ${lanes.join("\n")} 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); @@ -45484,23 +43243,25 @@ ${lanes.join("\n")} const conditions = getConditions(options, importMode); const fromExports = packageJsonContent.exports ? tryGetModuleNameFromExports(options, path, packageRootPath, packageName2, packageJsonContent.exports, conditions) : void 0; if (fromExports) { - const withJsExtension = !hasTSFileExtension(fromExports.moduleFileToTry) ? fromExports : { moduleFileToTry: removeFileExtension(fromExports.moduleFileToTry) + tryGetJSExtensionForFile(fromExports.moduleFileToTry, options) }; - return { ...withJsExtension, verbatimFromExports: true }; + const withJsExtension = !hasTSFileExtension(fromExports.moduleFileToTry) ? fromExports : { + moduleFileToTry: removeFileExtension(fromExports.moduleFileToTry) + tryGetJSExtensionForFile(fromExports.moduleFileToTry, options) + }; + return { + ...withJsExtension, + verbatimFromExports: true + }; } if (packageJsonContent.exports) { - return { moduleFileToTry: path, blockedByExports: true }; + return { + moduleFileToTry: path, + blockedByExports: true + }; } } const versionPaths = packageJsonContent.typesVersions ? getPackageJsonTypesVersionsPaths(packageJsonContent.typesVersions) : void 0; if (versionPaths) { const subModuleName = path.slice(packageRootPath.length + 1); - const fromPaths = tryGetModuleNameFromPaths( - subModuleName, - versionPaths.paths, - allowedEndings, - host, - options - ); + const fromPaths = tryGetModuleNameFromPaths(subModuleName, versionPaths.paths, allowedEndings, host, options); if (fromPaths === void 0) { maybeBlockedByTypesVersions = true; } else { @@ -45512,24 +43273,43 @@ ${lanes.join("\n")} const mainExportFile = toPath(mainFileRelative, packageRootPath, getCanonicalFileName); const canonicalModuleFileToTry = getCanonicalFileName(moduleFileToTry); if (removeFileExtension(mainExportFile) === removeFileExtension(canonicalModuleFileToTry)) { - return { packageRootPath, moduleFileToTry }; + return { + packageRootPath, + moduleFileToTry + }; } else if (packageJsonContent.type !== "module" && !fileExtensionIsOneOf(canonicalModuleFileToTry, extensionsNotSupportingExtensionlessResolution) && startsWith(canonicalModuleFileToTry, mainExportFile) && getDirectoryPath(canonicalModuleFileToTry) === removeTrailingDirectorySeparator(mainExportFile) && removeFileExtension(getBaseFileName(canonicalModuleFileToTry)) === "index") { - return { packageRootPath, moduleFileToTry }; + return { + packageRootPath, + moduleFileToTry + }; } } } else { const fileName = getCanonicalFileName(moduleFileToTry.substring(parts.packageRootIndex + 1)); if (fileName === "index.d.ts" || fileName === "index.js" || fileName === "index.ts" || fileName === "index.tsx") { - return { moduleFileToTry, packageRootPath }; + return { + moduleFileToTry, + packageRootPath + }; } } - return { moduleFileToTry }; + return { + moduleFileToTry + }; } } function tryGetAnyFileFromPath(host, path) { - if (!host.fileExists) - return; - const extensions = flatten(getSupportedExtensions({ allowJs: true }, [{ extension: "node", isMixedContent: false }, { extension: "json", isMixedContent: false, scriptKind: 6 /* JSON */ }])); + 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; if (host.fileExists(fullPath)) { @@ -45538,7 +43318,7 @@ ${lanes.join("\n")} } } function getPathsRelativeToRootDirs(path, rootDirs, getCanonicalFileName) { - return mapDefined(rootDirs, (rootDir) => { + return mapDefined(rootDirs, rootDir => { const relativePath = getRelativePathIfInSameVolume(path, rootDir, getCanonicalFileName); return relativePath !== void 0 && isPathRelativeToParent(relativePath) ? void 0 : relativePath; }); @@ -45573,7 +43353,7 @@ ${lanes.join("\n")} return noExtension + getJSExtensionForFile(fileName, options); case 3 /* TsExtension */: if (isDeclarationFileName(fileName)) { - const extensionlessPriority = allowedEndings.findIndex((e) => e === 0 /* Minimal */ || e === 1 /* Index */); + const extensionlessPriority = allowedEndings.findIndex(e => e === 0 /* Minimal */ || e === 1 /* Index */); return extensionlessPriority !== -1 && extensionlessPriority < jsPriority ? noExtension : noExtension + getJSExtensionForFile(fileName, options); } return fileName; @@ -45583,14 +43363,14 @@ ${lanes.join("\n")} } 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; } function getJSExtensionForFile(fileName, options) { - return tryGetJSExtensionForFile(fileName, options) ?? Debug.fail(`Extension ${extensionFromPath(fileName)} is unsupported:: FileName:: ${fileName}`); + var _tryGetJSExtensionFor; + return (_tryGetJSExtensionFor = tryGetJSExtensionForFile(fileName, options)) !== null && _tryGetJSExtensionFor !== void 0 ? _tryGetJSExtensionFor : Debug.fail(`Extension ${extensionFromPath(fileName)} is unsupported:: FileName:: ${fileName}`); } function tryGetJSExtensionForFile(fileName, options) { const ext = tryGetExtensionFromPath2(fileName); @@ -45617,14 +43397,8 @@ ${lanes.join("\n")} } } function getRelativePathIfInSameVolume(path, directoryPath, getCanonicalFileName) { - const relativePath = getRelativePathToDirectoryOrUrl( - directoryPath, - path, - directoryPath, - getCanonicalFileName, - /*isAbsolutePathAnUrl*/ - false - ); + const relativePath = getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ + false); return isRootedDiskPath(relativePath) ? void 0 : relativePath; } function isPathRelativeToParent(path) { @@ -45633,6 +43407,7 @@ ${lanes.join("\n")} var init_moduleSpecifiers = __esm({ "src/compiler/moduleSpecifiers.ts"() { "use strict"; + init_ts2(); } }); @@ -45654,6 +43429,7 @@ ${lanes.join("\n")} var init_ts_moduleSpecifiers = __esm({ "src/compiler/_namespaces/ts.moduleSpecifiers.ts"() { "use strict"; + init_moduleSpecifiers(); } }); @@ -45662,6 +43438,7 @@ ${lanes.join("\n")} function NodeLinks() { this.flags = 0 /* None */; } + function getNodeId(node) { if (!node.id) { node.id = nextNodeId; @@ -45680,13 +43457,14 @@ ${lanes.join("\n")} const moduleState = getModuleInstanceState(node); return moduleState === 1 /* Instantiated */ || preserveConstEnums && moduleState === 2 /* ConstEnumOnly */; } + function createTypeChecker(host) { var deferredDiagnosticsCallbacks = []; - var addLazyDiagnostic = (arg) => { + var addLazyDiagnostic = arg => { deferredDiagnosticsCallbacks.push(arg); }; var cancellationToken; - var requestedExternalEmitHelperNames = /* @__PURE__ */ new Set(); + var requestedExternalEmitHelperNames = /* @__PURE__ */new Set(); var requestedExternalEmitHelpers; var externalHelpersModule; var Symbol47 = objectAllocator.getSymbolConstructor(); @@ -45752,9 +43530,9 @@ ${lanes.join("\n")} subtype: subtypeRelation.size, strictSubtype: strictSubtypeRelation.size }), - isUndefinedSymbol: (symbol) => symbol === undefinedSymbol, - isArgumentsSymbol: (symbol) => symbol === argumentsSymbol, - isUnknownSymbol: (symbol) => symbol === unknownSymbol, + isUndefinedSymbol: symbol => symbol === undefinedSymbol, + isArgumentsSymbol: symbol => symbol === argumentsSymbol, + isUnknownSymbol: symbol => symbol === unknownSymbol, getMergedSymbol, getDiagnostics: getDiagnostics2, getGlobalDiagnostics, @@ -45767,8 +43545,7 @@ ${lanes.join("\n")} 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)); }, @@ -45790,18 +43567,18 @@ ${lanes.join("\n")} getIndexInfosOfIndexSymbol, getSignaturesOfType, getIndexTypeOfType: (type, kind) => getIndexTypeOfType(type, kind === 0 /* String */ ? stringType : numberType), - getIndexType: (type) => getIndexType(type), + getIndexType: type => getIndexType(type), getBaseTypes, getBaseTypeOfLiteralType, getWidenedType, - getTypeFromTypeNode: (nodeIn) => { + getTypeFromTypeNode: nodeIn => { const node = getParseTreeNode(nodeIn, isTypeNode); return node ? getTypeFromTypeNode(node) : errorType; }, getParameterType: getTypeAtPosition, getParameterIdentifierInfoAtPosition, getPromisedTypeOfPromise, - getAwaitedType: (type) => getAwaitedType(type), + getAwaitedType: type => getAwaitedType(type), getReturnTypeOfSignature, isNullableType, getNullableType, @@ -45821,38 +43598,35 @@ ${lanes.join("\n")} const location = getParseTreeNode(locationIn); return location ? getSymbolsInScope(location, meaning) : []; }, - getSymbolAtLocation: (nodeIn) => { + getSymbolAtLocation: nodeIn => { const node = getParseTreeNode(nodeIn); - return node ? getSymbolAtLocation( - node, - /*ignoreErrors*/ - true - ) : void 0; + return node ? getSymbolAtLocation(node, /*ignoreErrors*/ + true) : void 0; }, - getIndexInfosAtLocation: (nodeIn) => { + getIndexInfosAtLocation: nodeIn => { const node = getParseTreeNode(nodeIn); return node ? getIndexInfosAtLocation(node) : void 0; }, - getShorthandAssignmentValueSymbol: (nodeIn) => { + getShorthandAssignmentValueSymbol: nodeIn => { const node = getParseTreeNode(nodeIn); return node ? getShorthandAssignmentValueSymbol(node) : void 0; }, - getExportSpecifierLocalTargetSymbol: (nodeIn) => { + getExportSpecifierLocalTargetSymbol: nodeIn => { const node = getParseTreeNode(nodeIn, isExportSpecifier); return node ? getExportSpecifierLocalTargetSymbol(node) : void 0; }, getExportSymbolOfSymbol(symbol) { return getMergedSymbol(symbol.exportSymbol || symbol); }, - getTypeAtLocation: (nodeIn) => { + getTypeAtLocation: nodeIn => { const node = getParseTreeNode(nodeIn); return node ? getTypeOfNode(node) : errorType; }, - getTypeOfAssignmentPattern: (nodeIn) => { + getTypeOfAssignmentPattern: nodeIn => { const node = getParseTreeNode(nodeIn, isAssignmentPattern); return node && getTypeOfAssignmentPattern(node) || errorType; }, - getPropertySymbolOfDestructuringAssignment: (locationIn) => { + getPropertySymbolOfDestructuringAssignment: locationIn => { const location = getParseTreeNode(locationIn, isIdentifier); return location ? getPropertySymbolOfDestructuringAssignment(location) : void 0; }, @@ -45893,25 +43667,19 @@ ${lanes.join("\n")} } return getContextualType2(node, contextFlags); }, - getContextualTypeForObjectLiteralElement: (nodeIn) => { + getContextualTypeForObjectLiteralElement: nodeIn => { const node = getParseTreeNode(nodeIn, isObjectLiteralElementLike); - return node ? getContextualTypeForObjectLiteralElement( - node, - /*contextFlags*/ - void 0 - ) : void 0; + return node ? getContextualTypeForObjectLiteralElement(node, /*contextFlags*/ + void 0) : void 0; }, getContextualTypeForArgumentAtIndex: (nodeIn, argIndex) => { const node = getParseTreeNode(nodeIn, isCallLikeExpression); return node && getContextualTypeForArgumentAtIndex(node, argIndex); }, - getContextualTypeForJsxAttribute: (nodeIn) => { + getContextualTypeForJsxAttribute: nodeIn => { const node = getParseTreeNode(nodeIn, isJsxAttributeLike); - return node && getContextualTypeForJsxAttribute( - node, - /*contextFlags*/ - void 0 - ); + return node && getContextualTypeForJsxAttribute(node, /*contextFlags*/ + void 0); }, isContextSensitive, getTypeOfPropertyOfContextualType, @@ -45922,7 +43690,7 @@ ${lanes.join("\n")} getExpandedParameters, hasEffectiveRestParameter, containsArgumentsReference, - getConstantValue: (nodeIn) => { + getConstantValue: nodeIn => { const node = getParseTreeNode(nodeIn, canHaveConstantValue); return node ? getConstantValue2(node) : void 0; }, @@ -45934,11 +43702,11 @@ ${lanes.join("\n")} const node = getParseTreeNode(nodeIn, isPropertyAccessExpression); return !!node && isValidPropertyAccessForCompletions(node, type, property); }, - getSignatureFromDeclaration: (declarationIn) => { + getSignatureFromDeclaration: declarationIn => { const declaration = getParseTreeNode(declarationIn, isFunctionLike); return declaration ? getSignatureFromDeclaration(declaration) : void 0; }, - isImplementationOfOverload: (nodeIn) => { + isImplementationOfOverload: nodeIn => { const node = getParseTreeNode(nodeIn, isFunctionLike); return node ? isImplementationOfOverload(node) : void 0; }, @@ -45948,37 +43716,20 @@ ${lanes.join("\n")} getExportsOfModule: getExportsOfModuleAsArray, getExportsAndPropertiesOfModule, forEachExportAndPropertyOfModule, - getSymbolWalker: createGetSymbolWalker( - getRestTypeOfSignature, - getTypePredicateOfSignature, - getReturnTypeOfSignature, - getBaseTypes, - resolveStructuredTypeMembers, - getTypeOfSymbol, - getResolvedSymbol, - getConstraintOfTypeParameter, - getFirstIdentifier, - getTypeArguments - ), + getSymbolWalker: createGetSymbolWalker(getRestTypeOfSignature, getTypePredicateOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getConstraintOfTypeParameter, getFirstIdentifier, getTypeArguments), getAmbientModules, getJsxIntrinsicTagNamesAt, - isOptionalParameter: (nodeIn) => { + isOptionalParameter: nodeIn => { const node = getParseTreeNode(nodeIn, isParameter); return node ? isOptionalParameter(node) : false; }, tryGetMemberInModuleExports: (name, symbol) => tryGetMemberInModuleExports(escapeLeadingUnderscores(name), symbol), tryGetMemberInModuleExportsAndProperties: (name, symbol) => tryGetMemberInModuleExportsAndProperties(escapeLeadingUnderscores(name), symbol), - tryFindAmbientModule: (moduleName) => tryFindAmbientModule( - moduleName, - /*withAugmentations*/ - true - ), - tryFindAmbientModuleWithoutAugmentations: (moduleName) => { - return tryFindAmbientModule( - moduleName, - /*withAugmentations*/ - false - ); + tryFindAmbientModule: moduleName => tryFindAmbientModule(moduleName, /*withAugmentations*/ + true), + tryFindAmbientModuleWithoutAugmentations: moduleName => { + return tryFindAmbientModule(moduleName, /*withAugmentations*/ + false); }, getApparentType, getUnionType, @@ -45997,29 +43748,22 @@ ${lanes.join("\n")} createArrayType, getElementTypeOfArrayType, getBooleanType: () => booleanType, - getFalseType: (fresh) => fresh ? falseType : regularFalseType, - getTrueType: (fresh) => fresh ? trueType : regularTrueType, + getFalseType: fresh => fresh ? falseType : regularFalseType, + getTrueType: fresh => fresh ? trueType : regularTrueType, getVoidType: () => voidType, getUndefinedType: () => undefinedType, getNullType: () => nullType, getESSymbolType: () => esSymbolType, getNeverType: () => neverType, getOptionalType: () => optionalType, - getPromiseType: () => getGlobalPromiseType( - /*reportErrors*/ - false - ), - getPromiseLikeType: () => getGlobalPromiseLikeType( - /*reportErrors*/ - false - ), + getPromiseType: () => getGlobalPromiseType( /*reportErrors*/ + false), + getPromiseLikeType: () => getGlobalPromiseLikeType( /*reportErrors*/ + false), getAsyncIterableType: () => { - const type = getGlobalAsyncIterableType( - /*reportErrors*/ - false - ); - if (type === emptyGenericType) - return void 0; + const type = getGlobalAsyncIterableType( /*reportErrors*/ + false); + if (type === emptyGenericType) return void 0; return type; }, isSymbolAccessible, @@ -46039,43 +43783,31 @@ ${lanes.join("\n")} getSuggestionForNonexistentExport, getSuggestedSymbolForNonexistentClassMember, getBaseConstraintOfType, - getDefaultFromTypeParameter: (type) => type && type.flags & 262144 /* TypeParameter */ ? getDefaultFromTypeParameter(type) : void 0, + getDefaultFromTypeParameter: type => type && type.flags & 262144 /* TypeParameter */ ? getDefaultFromTypeParameter(type) : void 0, resolveName(name, location, meaning, excludeGlobals) { - return resolveName( - location, - escapeLeadingUnderscores(name), - meaning, - /*nameNotFoundMessage*/ - void 0, - /*nameArg*/ - void 0, - /*isUse*/ - false, - excludeGlobals - ); + return resolveName(location, escapeLeadingUnderscores(name), meaning, /*nameNotFoundMessage*/ + void 0, /*nameArg*/ + void 0, /*isUse*/ + false, excludeGlobals); }, - getJsxNamespace: (n) => unescapeLeadingUnderscores(getJsxNamespace(n)), - getJsxFragmentFactory: (n) => { + getJsxNamespace: n => unescapeLeadingUnderscores(getJsxNamespace(n)), + getJsxFragmentFactory: n => { const jsxFragmentFactory = getJsxFragmentFactoryEntity(n); return jsxFragmentFactory && unescapeLeadingUnderscores(getFirstIdentifier(jsxFragmentFactory).escapedText); }, getAccessibleSymbolChain, getTypePredicateOfSignature, - resolveExternalModuleName: (moduleSpecifierIn) => { + resolveExternalModuleName: moduleSpecifierIn => { const moduleSpecifier = getParseTreeNode(moduleSpecifierIn, isExpression); - return moduleSpecifier && resolveExternalModuleName( - moduleSpecifier, - moduleSpecifier, - /*ignoreErrors*/ - true - ); + return moduleSpecifier && resolveExternalModuleName(moduleSpecifier, moduleSpecifier, /*ignoreErrors*/ + true); }, resolveExternalModuleSymbol, tryGetThisTypeAt: (nodeIn, includeGlobalThis, container) => { const node = getParseTreeNode(nodeIn); return node && tryGetThisTypeAt(node, includeGlobalThis, container); }, - getTypeArgumentConstraint: (nodeIn) => { + getTypeArgumentConstraint: nodeIn => { const node = getParseTreeNode(nodeIn, isTypeNode); return node && getTypeArgumentConstraint(node); }, @@ -46092,9 +43824,13 @@ ${lanes.join("\n")} diagnostics2 = addRange(diagnostics2, suggestionDiagnostics.getDiagnostics(file.fileName)); checkUnusedIdentifiers(getPotentiallyUnusedIdentifiers(file), (containingNode, kind, diag2) => { if (!containsParseError(containingNode) && !unusedIsError(kind, !!(containingNode.flags & 33554432 /* Ambient */))) { - (diagnostics2 || (diagnostics2 = [])).push({ ...diag2, category: 2 /* Suggestion */ }); + (diagnostics2 || (diagnostics2 = [])).push({ + ...diag2, + category: 2 /* Suggestion */ + }); } }); + return diagnostics2 || emptyArray; } finally { cancellationToken = void 0; @@ -46117,26 +43853,18 @@ ${lanes.join("\n")} typeHasCallOrConstructSignatures }; function getCandidateSignaturesForStringLiteralCompletions(call, editingArgument) { - const candidatesSet = /* @__PURE__ */ new Set(); + const candidatesSet = /* @__PURE__ */new Set(); const candidates = []; - runWithInferenceBlockedFromSourceNode(editingArgument, () => getResolvedSignatureWorker( - call, - candidates, - /*argumentCount*/ - void 0, - 0 /* Normal */ - )); + runWithInferenceBlockedFromSourceNode(editingArgument, () => getResolvedSignatureWorker(call, candidates, /*argumentCount*/ + void 0, 0 /* Normal */)); + for (const candidate of candidates) { candidatesSet.add(candidate); } candidates.length = 0; - runWithoutResolvedSignatureCaching(editingArgument, () => getResolvedSignatureWorker( - call, - candidates, - /*argumentCount*/ - void 0, - 0 /* Normal */ - )); + runWithoutResolvedSignatureCaching(editingArgument, () => getResolvedSignatureWorker(call, candidates, /*argumentCount*/ + void 0, 0 /* Normal */)); + for (const candidate of candidates) { candidatesSet.add(candidate); } @@ -46198,94 +43926,59 @@ ${lanes.join("\n")} apparentArgumentCount = void 0; return res; } - var tupleTypes = /* @__PURE__ */ new Map(); - var unionTypes = /* @__PURE__ */ new Map(); - var unionOfUnionTypes = /* @__PURE__ */ new Map(); - var intersectionTypes = /* @__PURE__ */ new Map(); - var stringLiteralTypes = /* @__PURE__ */ new Map(); - var numberLiteralTypes = /* @__PURE__ */ new Map(); - var bigIntLiteralTypes = /* @__PURE__ */ new Map(); - var enumLiteralTypes = /* @__PURE__ */ new Map(); - var indexedAccessTypes = /* @__PURE__ */ new Map(); - var templateLiteralTypes = /* @__PURE__ */ new Map(); - var stringMappingTypes = /* @__PURE__ */ new Map(); - var substitutionTypes = /* @__PURE__ */ new Map(); - var subtypeReductionCache = /* @__PURE__ */ new Map(); - var decoratorContextOverrideTypeCache = /* @__PURE__ */ new Map(); - var cachedTypes = /* @__PURE__ */ new Map(); + var tupleTypes = /* @__PURE__ */new Map(); + var unionTypes = /* @__PURE__ */new Map(); + var unionOfUnionTypes = /* @__PURE__ */new Map(); + var intersectionTypes = /* @__PURE__ */new Map(); + var stringLiteralTypes = /* @__PURE__ */new Map(); + var numberLiteralTypes = /* @__PURE__ */new Map(); + var bigIntLiteralTypes = /* @__PURE__ */new Map(); + var enumLiteralTypes = /* @__PURE__ */new Map(); + var indexedAccessTypes = /* @__PURE__ */new Map(); + var templateLiteralTypes = /* @__PURE__ */new Map(); + var stringMappingTypes = /* @__PURE__ */new Map(); + var substitutionTypes = /* @__PURE__ */new Map(); + var subtypeReductionCache = /* @__PURE__ */new Map(); + var decoratorContextOverrideTypeCache = /* @__PURE__ */new Map(); + var cachedTypes = /* @__PURE__ */new Map(); var evolvingArrayTypes = []; - var undefinedProperties = /* @__PURE__ */ new Map(); - var markerTypes = /* @__PURE__ */ new Set(); + var undefinedProperties = /* @__PURE__ */new Map(); + var markerTypes = /* @__PURE__ */new Set(); var unknownSymbol = createSymbol(4 /* Property */, "unknown"); var resolvingSymbol = createSymbol(0, "__resolving__" /* Resolving */); - var unresolvedSymbols = /* @__PURE__ */ new Map(); - var errorTypes = /* @__PURE__ */ new Map(); - var seenIntrinsicNames = /* @__PURE__ */ new Set(); + var unresolvedSymbols = /* @__PURE__ */new Map(); + var errorTypes = /* @__PURE__ */new Map(); + var seenIntrinsicNames = /* @__PURE__ */new Set(); var anyType = createIntrinsicType(1 /* Any */, "any"); var autoType = createIntrinsicType(1 /* Any */, "any", 262144 /* NonInferrableType */, "auto"); - var wildcardType = createIntrinsicType( - 1 /* Any */, - "any", - /*objectFlags*/ - void 0, - "wildcard" - ); - var blockedStringType = createIntrinsicType( - 1 /* Any */, - "any", - /*objectFlags*/ - void 0, - "blocked string" - ); + var wildcardType = createIntrinsicType(1 /* Any */, "any", /*objectFlags*/ + void 0, "wildcard"); + var blockedStringType = createIntrinsicType(1 /* Any */, "any", /*objectFlags*/ + void 0, "blocked string"); var errorType = createIntrinsicType(1 /* Any */, "error"); var unresolvedType = createIntrinsicType(1 /* Any */, "unresolved"); var nonInferrableAnyType = createIntrinsicType(1 /* Any */, "any", 65536 /* ContainsWideningType */, "non-inferrable"); var intrinsicMarkerType = createIntrinsicType(1 /* Any */, "intrinsic"); var unknownType = createIntrinsicType(2 /* Unknown */, "unknown"); - var nonNullUnknownType = createIntrinsicType( - 2 /* Unknown */, - "unknown", - /*objectFlags*/ - void 0, - "non-null" - ); + var nonNullUnknownType = createIntrinsicType(2 /* Unknown */, "unknown", /*objectFlags*/ + void 0, "non-null"); var undefinedType = createIntrinsicType(32768 /* Undefined */, "undefined"); var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(32768 /* Undefined */, "undefined", 65536 /* ContainsWideningType */, "widening"); - var missingType = createIntrinsicType( - 32768 /* Undefined */, - "undefined", - /*objectFlags*/ - void 0, - "missing" - ); + var missingType = createIntrinsicType(32768 /* Undefined */, "undefined", /*objectFlags*/ + void 0, "missing"); var undefinedOrMissingType = exactOptionalPropertyTypes ? missingType : undefinedType; - var optionalType = createIntrinsicType( - 32768 /* Undefined */, - "undefined", - /*objectFlags*/ - void 0, - "optional" - ); + var optionalType = createIntrinsicType(32768 /* Undefined */, "undefined", /*objectFlags*/ + void 0, "optional"); var nullType = createIntrinsicType(65536 /* Null */, "null"); var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(65536 /* Null */, "null", 65536 /* ContainsWideningType */, "widening"); var stringType = createIntrinsicType(4 /* String */, "string"); var numberType = createIntrinsicType(8 /* Number */, "number"); var bigintType = createIntrinsicType(64 /* BigInt */, "bigint"); - var falseType = createIntrinsicType( - 512 /* BooleanLiteral */, - "false", - /*objectFlags*/ - void 0, - "fresh" - ); + var falseType = createIntrinsicType(512 /* BooleanLiteral */, "false", /*objectFlags*/ + void 0, "fresh"); var regularFalseType = createIntrinsicType(512 /* BooleanLiteral */, "false"); - var trueType = createIntrinsicType( - 512 /* BooleanLiteral */, - "true", - /*objectFlags*/ - void 0, - "fresh" - ); + var trueType = createIntrinsicType(512 /* BooleanLiteral */, "true", /*objectFlags*/ + void 0, "fresh"); var regularTrueType = createIntrinsicType(512 /* BooleanLiteral */, "true"); trueType.regularType = regularTrueType; trueType.freshType = trueType; @@ -46300,20 +43993,10 @@ ${lanes.join("\n")} var voidType = createIntrinsicType(16384 /* Void */, "void"); var neverType = createIntrinsicType(131072 /* Never */, "never"); var silentNeverType = createIntrinsicType(131072 /* Never */, "never", 262144 /* NonInferrableType */, "silent"); - var implicitNeverType = createIntrinsicType( - 131072 /* Never */, - "never", - /*objectFlags*/ - void 0, - "implicit" - ); - var unreachableNeverType = createIntrinsicType( - 131072 /* Never */, - "never", - /*objectFlags*/ - void 0, - "unreachable" - ); + var implicitNeverType = createIntrinsicType(131072 /* Never */, "never", /*objectFlags*/ + void 0, "implicit"); + var unreachableNeverType = createIntrinsicType(131072 /* Never */, "never", /*objectFlags*/ + void 0, "unreachable"); var nonPrimitiveType = createIntrinsicType(67108864 /* NonPrimitive */, "object"); var stringOrNumberType = getUnionType([stringType, numberType]); var stringNumberSymbolType = getUnionType([stringType, numberType, esSymbolType]); @@ -46321,106 +44004,49 @@ ${lanes.join("\n")} var numberOrBigIntType = getUnionType([numberType, bigintType]); var templateConstraintType = getUnionType([stringType, numberType, booleanType, bigintType, nullType, undefinedType]); var numericStringType = getTemplateLiteralType(["", ""], [numberType]); - var restrictiveMapper = makeFunctionTypeMapper((t) => t.flags & 262144 /* TypeParameter */ ? getRestrictiveTypeParameter(t) : t, () => "(restrictive mapper)"); - var permissiveMapper = makeFunctionTypeMapper((t) => t.flags & 262144 /* TypeParameter */ ? wildcardType : t, () => "(permissive mapper)"); - var uniqueLiteralType = createIntrinsicType( - 131072 /* Never */, - "never", - /*objectFlags*/ - void 0, - "unique literal" - ); - var uniqueLiteralMapper = makeFunctionTypeMapper((t) => t.flags & 262144 /* TypeParameter */ ? uniqueLiteralType : t, () => "(unique literal mapper)"); + var restrictiveMapper = makeFunctionTypeMapper(t => t.flags & 262144 /* TypeParameter */ ? getRestrictiveTypeParameter(t) : t, () => "(restrictive mapper)"); + var permissiveMapper = makeFunctionTypeMapper(t => t.flags & 262144 /* TypeParameter */ ? wildcardType : t, () => "(permissive mapper)"); + var uniqueLiteralType = createIntrinsicType(131072 /* Never */, "never", /*objectFlags*/ + void 0, "unique literal"); + var uniqueLiteralMapper = makeFunctionTypeMapper(t => t.flags & 262144 /* TypeParameter */ ? uniqueLiteralType : t, () => "(unique literal mapper)"); var outofbandVarianceMarkerHandler; - var reportUnreliableMapper = makeFunctionTypeMapper((t) => { + var reportUnreliableMapper = makeFunctionTypeMapper(t => { if (outofbandVarianceMarkerHandler && (t === markerSuperType || t === markerSubType || t === markerOtherType)) { - outofbandVarianceMarkerHandler( - /*onlyUnreliable*/ - true - ); + outofbandVarianceMarkerHandler( /*onlyUnreliable*/ + true); } return t; }, () => "(unmeasurable reporter)"); - var reportUnmeasurableMapper = makeFunctionTypeMapper((t) => { + var reportUnmeasurableMapper = makeFunctionTypeMapper(t => { if (outofbandVarianceMarkerHandler && (t === markerSuperType || t === markerSubType || t === markerOtherType)) { - outofbandVarianceMarkerHandler( - /*onlyUnreliable*/ - false - ); + outofbandVarianceMarkerHandler( /*onlyUnreliable*/ + false); } return t; }, () => "(unreliable reporter)"); - var emptyObjectType = createAnonymousType( - /*symbol*/ - void 0, - emptySymbols, - emptyArray, - emptyArray, - emptyArray - ); - var emptyJsxObjectType = createAnonymousType( - /*symbol*/ - void 0, - emptySymbols, - emptyArray, - emptyArray, - emptyArray - ); + var emptyObjectType = createAnonymousType( /*symbol*/ + void 0, emptySymbols, emptyArray, emptyArray, emptyArray); + var emptyJsxObjectType = createAnonymousType( /*symbol*/ + void 0, emptySymbols, emptyArray, emptyArray, emptyArray); emptyJsxObjectType.objectFlags |= 2048 /* JsxAttributes */; var emptyTypeLiteralSymbol = createSymbol(2048 /* TypeLiteral */, "__type" /* Type */); emptyTypeLiteralSymbol.members = createSymbolTable(); var emptyTypeLiteralType = createAnonymousType(emptyTypeLiteralSymbol, emptySymbols, emptyArray, emptyArray, emptyArray); - var unknownEmptyObjectType = createAnonymousType( - /*symbol*/ - void 0, - emptySymbols, - emptyArray, - emptyArray, - emptyArray - ); + var unknownEmptyObjectType = createAnonymousType( /*symbol*/ + void 0, emptySymbols, emptyArray, emptyArray, emptyArray); var unknownUnionType = strictNullChecks ? getUnionType([undefinedType, nullType, unknownEmptyObjectType]) : unknownType; - var emptyGenericType = createAnonymousType( - /*symbol*/ - void 0, - emptySymbols, - emptyArray, - emptyArray, - emptyArray - ); - emptyGenericType.instantiations = /* @__PURE__ */ new Map(); - var anyFunctionType = createAnonymousType( - /*symbol*/ - void 0, - emptySymbols, - emptyArray, - emptyArray, - emptyArray - ); + var emptyGenericType = createAnonymousType( /*symbol*/ + void 0, emptySymbols, emptyArray, emptyArray, emptyArray); + emptyGenericType.instantiations = /* @__PURE__ */new Map(); + var anyFunctionType = createAnonymousType( /*symbol*/ + void 0, emptySymbols, emptyArray, emptyArray, emptyArray); anyFunctionType.objectFlags |= 262144 /* NonInferrableType */; - var noConstraintType = createAnonymousType( - /*symbol*/ - void 0, - emptySymbols, - emptyArray, - emptyArray, - emptyArray - ); - var circularConstraintType = createAnonymousType( - /*symbol*/ - void 0, - emptySymbols, - emptyArray, - emptyArray, - emptyArray - ); - var resolvingDefaultType = createAnonymousType( - /*symbol*/ - void 0, - emptySymbols, - emptyArray, - emptyArray, - emptyArray - ); + var noConstraintType = createAnonymousType( /*symbol*/ + void 0, emptySymbols, emptyArray, emptyArray, emptyArray); + var circularConstraintType = createAnonymousType( /*symbol*/ + void 0, emptySymbols, emptyArray, emptyArray, emptyArray); + var resolvingDefaultType = createAnonymousType( /*symbol*/ + void 0, emptySymbols, emptyArray, emptyArray, emptyArray); var markerSuperType = createTypeParameter(); var markerSubType = createTypeParameter(); markerSubType.constraint = markerSuperType; @@ -46429,69 +44055,33 @@ ${lanes.join("\n")} var markerSubTypeForCheck = createTypeParameter(); markerSubTypeForCheck.constraint = markerSuperTypeForCheck; var noTypePredicate = createTypePredicate(1 /* Identifier */, "<>", 0, anyType); - var anySignature = createSignature( - /*declaration*/ - void 0, - /*typeParameters*/ - void 0, - /*thisParameter*/ - void 0, - emptyArray, - anyType, - /*resolvedTypePredicate*/ - void 0, - 0, - 0 /* None */ - ); - var unknownSignature = createSignature( - /*declaration*/ - void 0, - /*typeParameters*/ - void 0, - /*thisParameter*/ - void 0, - emptyArray, - errorType, - /*resolvedTypePredicate*/ - void 0, - 0, - 0 /* None */ - ); - var resolvingSignature = createSignature( - /*declaration*/ - void 0, - /*typeParameters*/ - void 0, - /*thisParameter*/ - void 0, - emptyArray, - anyType, - /*resolvedTypePredicate*/ - void 0, - 0, - 0 /* None */ - ); - var silentNeverSignature = createSignature( - /*declaration*/ - void 0, - /*typeParameters*/ - void 0, - /*thisParameter*/ - void 0, - emptyArray, - silentNeverType, - /*resolvedTypePredicate*/ - void 0, - 0, - 0 /* None */ - ); - var enumNumberIndexInfo = createIndexInfo( - numberType, - stringType, - /*isReadonly*/ - true - ); - var iterationTypesCache = /* @__PURE__ */ new Map(); + var anySignature = createSignature( /*declaration*/ + void 0, /*typeParameters*/ + void 0, /*thisParameter*/ + void 0, emptyArray, anyType, /*resolvedTypePredicate*/ + void 0, 0, 0 /* None */); + + var unknownSignature = createSignature( /*declaration*/ + void 0, /*typeParameters*/ + void 0, /*thisParameter*/ + void 0, emptyArray, errorType, /*resolvedTypePredicate*/ + void 0, 0, 0 /* None */); + + var resolvingSignature = createSignature( /*declaration*/ + void 0, /*typeParameters*/ + void 0, /*thisParameter*/ + void 0, emptyArray, anyType, /*resolvedTypePredicate*/ + void 0, 0, 0 /* None */); + + var silentNeverSignature = createSignature( /*declaration*/ + void 0, /*typeParameters*/ + void 0, /*thisParameter*/ + void 0, emptyArray, silentNeverType, /*resolvedTypePredicate*/ + void 0, 0, 0 /* None */); + + var enumNumberIndexInfo = createIndexInfo(numberType, stringType, /*isReadonly*/ + true); + var iterationTypesCache = /* @__PURE__ */new Map(); var noIterationTypes = { get yieldType() { return Debug.fail("Not supported"); @@ -46533,7 +44123,7 @@ ${lanes.join("\n")} mustHaveAValueDiagnostic: Diagnostics.The_type_returned_by_the_0_method_of_an_iterator_must_have_a_value_property }; var amalgamatedDuplicates; - var reverseMappedCache = /* @__PURE__ */ new Map(); + var reverseMappedCache = /* @__PURE__ */new Map(); var homomorphicMappedTypeInferenceStack = []; var ambientModulesCache; var patternAmbientModules; @@ -46591,7 +44181,7 @@ ${lanes.join("\n")} var deferredGlobalClassAccessorDecoratorTargetType; var deferredGlobalClassAccessorDecoratorResultType; var deferredGlobalClassFieldDecoratorContextType; - var allPotentiallyUnusedIdentifiers = /* @__PURE__ */ new Map(); + var allPotentiallyUnusedIdentifiers = /* @__PURE__ */new Map(); var flowLoopStart = 0; var flowLoopCount = 0; var sharedFlowCount = 0; @@ -46609,7 +44199,10 @@ ${lanes.join("\n")} var inferenceContextCount = 0; var emptyStringType = getStringLiteralType(""); var zeroType = getNumberLiteralType(0); - var zeroBigIntType = getBigIntLiteralType({ negative: false, base10Value: "0" }); + var zeroBigIntType = getBigIntLiteralType({ + negative: false, + base10Value: "0" + }); var resolutionTargets = []; var resolutionResults = []; var resolutionPropertyNames = []; @@ -46639,33 +44232,22 @@ ${lanes.join("\n")} var typeofType = createTypeofType(); var _jsxNamespace; var _jsxFactoryEntity; - var subtypeRelation = /* @__PURE__ */ new Map(); - var strictSubtypeRelation = /* @__PURE__ */ new Map(); - var assignableRelation = /* @__PURE__ */ new Map(); - var comparableRelation = /* @__PURE__ */ new Map(); - var identityRelation = /* @__PURE__ */ new Map(); - var enumRelation = /* @__PURE__ */ new Map(); + var subtypeRelation = /* @__PURE__ */new Map(); + var strictSubtypeRelation = /* @__PURE__ */new Map(); + var assignableRelation = /* @__PURE__ */new Map(); + var comparableRelation = /* @__PURE__ */new Map(); + var identityRelation = /* @__PURE__ */new Map(); + var enumRelation = /* @__PURE__ */new Map(); var builtinGlobals = createSymbolTable(); builtinGlobals.set(undefinedSymbol.escapedName, undefinedSymbol); - var suggestedExtensions = [ - [".mts", ".mjs"], - [".ts", ".js"], - [".cts", ".cjs"], - [".mjs", ".mjs"], - [".js", ".js"], - [".cjs", ".cjs"], - [".tsx", compilerOptions.jsx === 1 /* Preserve */ ? ".jsx" : ".js"], - [".jsx", ".jsx"], - [".json", ".json"] - ]; + var suggestedExtensions = [[".mts", ".mjs"], [".ts", ".js"], [".cts", ".cjs"], [".mjs", ".mjs"], [".js", ".js"], [".cjs", ".cjs"], [".tsx", compilerOptions.jsx === 1 /* Preserve */ ? ".jsx" : ".js"], [".jsx", ".jsx"], [".json", ".json"]]; initializeTypeChecker(); return checker; function getCachedType(key) { 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) { @@ -46764,9 +44346,13 @@ ${lanes.join("\n")} if (isError) { diagnostics.add(diagnostic); } else { - suggestionDiagnostics.add({ ...diagnostic, category: 2 /* Suggestion */ }); + suggestionDiagnostics.add({ + ...diagnostic, + category: 2 /* Suggestion */ + }); } } + function errorOrSuggestion(isError, location, message, ...args) { if (location.pos < 0 || location.end < 0) { if (!isError) { @@ -46789,10 +44375,7 @@ ${lanes.join("\n")} function addDeprecatedSuggestionWorker(declarations, diagnostic) { const deprecatedTag = Array.isArray(declarations) ? forEach(declarations, getJSDocDeprecatedTag) : getJSDocDeprecatedTag(declarations); if (deprecatedTag) { - addRelatedInfo( - diagnostic, - createDiagnosticForNode(deprecatedTag, Diagnostics.The_declaration_was_marked_as_deprecated_here) - ); + addRelatedInfo(diagnostic, createDiagnosticForNode(deprecatedTag, Diagnostics.The_declaration_was_marked_as_deprecated_here)); } suggestionDiagnostics.add(diagnostic); return diagnostic; @@ -46807,6 +44390,7 @@ ${lanes.join("\n")} function isDeprecatedDeclaration2(declaration) { return !!(getCombinedNodeFlagsCached(declaration) & 536870912 /* Deprecated */); } + function addDeprecatedSuggestion(location, declarations, deprecatedEntity) { const diagnostic = createDiagnosticForNode(location, Diagnostics._0_is_deprecated, deprecatedEntity); return addDeprecatedSuggestionWorker(declarations, diagnostic); @@ -46834,38 +44418,22 @@ ${lanes.join("\n")} } 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) { @@ -46879,14 +44447,10 @@ ${lanes.join("\n")} 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; } @@ -46911,13 +44475,11 @@ ${lanes.join("\n")} } 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) { @@ -46925,11 +44487,7 @@ ${lanes.join("\n")} } } else if (target.flags & 1024 /* NamespaceModule */) { if (target !== globalThisSymbol) { - error2( - source.declarations && getNameOfDeclaration(source.declarations[0]), - Diagnostics.Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity, - symbolToString(target) - ); + error2(source.declarations && getNameOfDeclaration(source.declarations[0]), Diagnostics.Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity, symbolToString(target)); } } else { const isEitherEnum = !!(target.flags & 384 /* Enum */ || source.flags & 384 /* Enum */); @@ -46943,17 +44501,21 @@ ${lanes.join("\n")} 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); + 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); } else { - if (!isSourcePlainJs) - addDuplicateDeclarationErrorsForSymbols(source, message, symbolName2, target); - if (!isTargetPlainJs) - addDuplicateDeclarationErrorsForSymbols(target, message, symbolName2, source); + if (!isSourcePlainJs) addDuplicateDeclarationErrorsForSymbols(source, message, symbolName2, target); + if (!isTargetPlainJs) addDuplicateDeclarationErrorsForSymbols(target, message, symbolName2, source); } } return target; @@ -46966,38 +44528,28 @@ ${lanes.join("\n")} } } function addDuplicateDeclarationErrorsForSymbols(target, message, symbolName2, source) { - forEach(target.declarations, (node) => { + forEach(target.declarations, node => { addDuplicateDeclarationError(node, message, symbolName2, source.declarations); }); } function addDuplicateDeclarationError(node, message, symbolName2, relatedNodes) { - const errorNode = (getExpandoInitializer( - node, - /*isPrototypeAssignment*/ - false - ) ? getNameOfExpando(node) : getNameOfDeclaration(node)) || node; + const errorNode = (getExpandoInitializer(node, /*isPrototypeAssignment*/ + false) ? getNameOfExpando(node) : getNameOfDeclaration(node)) || node; const err = lookupOrIssueError(errorNode, message, symbolName2); for (const relatedNode of relatedNodes || emptyArray) { - const adjustedNode = (getExpandoInitializer( - relatedNode, - /*isPrototypeAssignment*/ - false - ) ? getNameOfExpando(relatedNode) : getNameOfDeclaration(relatedNode)) || relatedNode; - if (adjustedNode === errorNode) - continue; + const adjustedNode = (getExpandoInitializer(relatedNode, /*isPrototypeAssignment*/ + false) ? getNameOfExpando(relatedNode) : getNameOfDeclaration(relatedNode)) || relatedNode; + 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); @@ -47020,27 +44572,18 @@ ${lanes.join("\n")} mergeSymbolTable(globals, moduleAugmentation.symbol.exports); } else { const moduleNotFoundError = !(moduleName.parent.parent.flags & 33554432 /* Ambient */) ? Diagnostics.Invalid_module_name_in_augmentation_module_0_cannot_be_found : void 0; - let mainModule = resolveExternalModuleNameWorker( - moduleName, - moduleName, - moduleNotFoundError, - /*isForAugmentation*/ - true - ); + let mainModule = resolveExternalModuleNameWorker(moduleName, moduleName, moduleNotFoundError, /*isForAugmentation*/ + true); if (!mainModule) { return; } mainModule = resolveExternalModuleSymbol(mainModule); if (mainModule.flags & 1920 /* Namespace */) { - if (some(patternAmbientModules, (module2) => mainModule === module2.symbol)) { - const merged = mergeSymbol( - moduleAugmentation.symbol, - mainModule, - /*unidirectional*/ - true - ); + if (some(patternAmbientModules, module2 => mainModule === module2.symbol)) { + const merged = mergeSymbol(moduleAugmentation.symbol, mainModule, /*unidirectional*/ + true); if (!patternAmbientModuleAugmentations) { - patternAmbientModuleAugmentations = /* @__PURE__ */ new Map(); + patternAmbientModuleAugmentations = /* @__PURE__ */new Map(); } patternAmbientModuleAugmentations.set(moduleName.text, merged); } else { @@ -47069,14 +44612,14 @@ ${lanes.join("\n")} } }); function addDeclarationDiagnostic(id, message2) { - return (declaration) => diagnostics.add(createDiagnosticForNode(declaration, message2, id)); + return declaration => diagnostics.add(createDiagnosticForNode(declaration, message2, id)); } } function getSymbolLinks(symbol) { - if (symbol.flags & 33554432 /* Transient */) - return symbol.links; + var _symbolLinks$id; + if (symbol.flags & 33554432 /* Transient */) return symbol.links; const id = getSymbolId(symbol); - return symbolLinks[id] ?? (symbolLinks[id] = new SymbolLinks()); + return (_symbolLinks$id = symbolLinks[id]) !== null && _symbolLinks$id !== void 0 ? _symbolLinks$id : symbolLinks[id] = new SymbolLinks(); } function getNodeLinks(node) { const nodeId = getNodeId(node); @@ -47139,14 +44682,10 @@ ${lanes.join("\n")} } else if (declaration.kind === 260 /* VariableDeclaration */) { return !isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage); } else if (isClassDeclaration(declaration)) { - return !findAncestor(usage, (n) => isComputedPropertyName(n) && n.parent.parent === declaration); + return !findAncestor(usage, n => isComputedPropertyName(n) && n.parent.parent === declaration); } else if (isPropertyDeclaration(declaration)) { - return !isPropertyImmediatelyReferencedWithinDeclaration( - declaration, - usage, - /*stopAtAnyPropertyDeclaration*/ - false - ); + return !isPropertyImmediatelyReferencedWithinDeclaration(declaration, usage, /*stopAtAnyPropertyDeclaration*/ + false); } else if (isParameterPropertyDeclaration(declaration, declaration.parent)) { return !(emitStandardClassFields && getContainingClass(declaration) === getContainingClass(usage) && isUsedInFunctionOrInstanceProperty(usage, declaration)); } @@ -47160,12 +44699,8 @@ ${lanes.join("\n")} } if (isUsedInFunctionOrInstanceProperty(usage, declaration)) { if (emitStandardClassFields && getContainingClass(declaration) && (isPropertyDeclaration(declaration) || isParameterPropertyDeclaration(declaration, declaration.parent))) { - return !isPropertyImmediatelyReferencedWithinDeclaration( - declaration, - usage, - /*stopAtAnyPropertyDeclaration*/ - true - ); + return !isPropertyImmediatelyReferencedWithinDeclaration(declaration, usage, /*stopAtAnyPropertyDeclaration*/ + true); } else { return true; } @@ -47185,7 +44720,7 @@ ${lanes.join("\n")} return isForInOrOfStatement(grandparent) && isSameScopeDescendentOf(usage2, grandparent.expression, declContainer); } function isUsedInFunctionOrInstanceProperty(usage2, declaration2) { - return !!findAncestor(usage2, (current) => { + return !!findAncestor(usage2, current => { if (current === declContainer) { return "quit"; } @@ -47228,7 +44763,7 @@ ${lanes.join("\n")} if (usage2.end > declaration2.end) { return false; } - const ancestorChangingReferenceScope = findAncestor(usage2, (node) => { + const ancestorChangingReferenceScope = findAncestor(usage2, node => { if (node === declaration2) { return "quit"; } @@ -47290,11 +44825,12 @@ ${lanes.join("\n")} if (isNullishCoalesce(node) || isOptionalChain(node)) { return target < 7 /* ES2020 */; } + 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; } } @@ -47317,217 +44853,209 @@ ${lanes.join("\n")} const errorLocation = location; let grandparent; let isInExternalModule = false; - loop: - while (location) { - if (name === "const" && isConstAssertion(location)) { - return void 0; - } - if (isModuleOrEnumDeclaration(location) && lastLocation && location.name === lastLocation) { - lastLocation = location; - location = location.parent; - } - if (canHaveLocals(location) && location.locals && !isGlobalSourceFile(location)) { - if (result = lookup(location.locals, name, meaning)) { - let useResult = true; - if (isFunctionLike(location) && lastLocation && lastLocation !== location.body) { - if (meaning & result.flags & 788968 /* Type */ && lastLocation.kind !== 327 /* JSDoc */) { - useResult = result.flags & 262144 /* TypeParameter */ ? lastLocation === location.type || lastLocation.kind === 169 /* Parameter */ || lastLocation.kind === 348 /* JSDocParameterTag */ || lastLocation.kind === 349 /* JSDocReturnTag */ || lastLocation.kind === 168 /* TypeParameter */ : false; - } - if (meaning & result.flags & 3 /* Variable */) { - if (useOuterVariableScopeInParameter(result, location, lastLocation)) { - useResult = false; - } else if (result.flags & 1 /* FunctionScopedVariable */) { - useResult = lastLocation.kind === 169 /* Parameter */ || lastLocation === location.type && !!findAncestor(result.valueDeclaration, isParameter); - } - } - } else if (location.kind === 194 /* ConditionalType */) { - useResult = lastLocation === location.trueType; + loop: while (location) { + if (name === "const" && isConstAssertion(location)) { + return void 0; + } + if (isModuleOrEnumDeclaration(location) && lastLocation && location.name === lastLocation) { + lastLocation = location; + location = location.parent; + } + if (canHaveLocals(location) && location.locals && !isGlobalSourceFile(location)) { + if (result = lookup(location.locals, name, meaning)) { + let useResult = true; + if (isFunctionLike(location) && lastLocation && lastLocation !== location.body) { + if (meaning & result.flags & 788968 /* Type */ && lastLocation.kind !== 327 /* JSDoc */) { + useResult = result.flags & 262144 /* TypeParameter */ ? lastLocation === location.type || lastLocation.kind === 169 /* Parameter */ || lastLocation.kind === 348 /* JSDocParameterTag */ || lastLocation.kind === 349 /* JSDocReturnTag */ || lastLocation.kind === 168 /* TypeParameter */ : false; } - if (useResult) { - break loop; - } else { - result = void 0; + 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); + } } + } else if (location.kind === 194 /* ConditionalType */) { + useResult = lastLocation === location.trueType; + } + if (useResult) { + break loop; + } else { + result = void 0; } } - withinDeferredContext = withinDeferredContext || getIsDeferredContext(location, lastLocation); - switch (location.kind) { - case 312 /* SourceFile */: - if (!isExternalOrCommonJsModule(location)) - break; - isInExternalModule = true; - case 267 /* ModuleDeclaration */: - const moduleExports = ((_a = getSymbolOfDeclaration(location)) == null ? void 0 : _a.exports) || emptySymbols; - if (location.kind === 312 /* SourceFile */ || isModuleDeclaration(location) && location.flags & 33554432 /* Ambient */ && !isGlobalScopeAugmentation(location)) { - if (result = moduleExports.get("default" /* Default */)) { - const localSymbol = getLocalSymbolForExportDefault(result); - if (localSymbol && result.flags & meaning && localSymbol.escapedName === name) { - break loop; - } - result = void 0; - } - const moduleExport = moduleExports.get(name); - if (moduleExport && moduleExport.flags === 2097152 /* Alias */ && (getDeclarationOfKind(moduleExport, 281 /* ExportSpecifier */) || getDeclarationOfKind(moduleExport, 280 /* NamespaceExport */))) { - break; - } - } - if (name !== "default" /* Default */ && (result = lookup(moduleExports, name, meaning & 2623475 /* ModuleMember */))) { - if (isSourceFile(location) && location.commonJsModuleIndicator && !((_b = result.declarations) == null ? void 0 : _b.some(isJSDocTypeAlias))) { - result = void 0; - } else { - break loop; - } - } - break; - case 266 /* EnumDeclaration */: - if (result = lookup(((_c = getSymbolOfDeclaration(location)) == null ? void 0 : _c.exports) || emptySymbols, name, meaning & 8 /* EnumMember */)) { - if (nameNotFoundMessage && getIsolatedModules(compilerOptions) && !(location.flags & 33554432 /* Ambient */) && getSourceFileOfNode(location) !== getSourceFileOfNode(result.valueDeclaration)) { - error2( - errorLocation, - Diagnostics.Cannot_access_0_from_another_file_without_qualification_when_1_is_enabled_Use_2_instead, - unescapeLeadingUnderscores(name), - isolatedModulesLikeFlagName, - `${unescapeLeadingUnderscores(getSymbolOfNode(location).escapedName)}.${unescapeLeadingUnderscores(name)}` - ); - } - break loop; - } - break; - case 172 /* PropertyDeclaration */: - if (!isStatic(location)) { - const ctor = findConstructorDeclaration(location.parent); - if (ctor && ctor.locals) { - if (lookup(ctor.locals, name, meaning & 111551 /* Value */)) { - Debug.assertNode(location, isPropertyDeclaration); - propertyWithInvalidInitializer = location; - } - } - } - break; - case 263 /* ClassDeclaration */: - case 231 /* ClassExpression */: - case 264 /* InterfaceDeclaration */: - if (result = lookup(getSymbolOfDeclaration(location).members || emptySymbols, name, meaning & 788968 /* Type */)) { - if (!isTypeParameterSymbolDeclaredInContainer(result, location)) { - result = void 0; - break; - } - if (lastLocation && isStatic(lastLocation)) { - if (nameNotFoundMessage) { - error2(errorLocation, Diagnostics.Static_members_cannot_reference_class_type_parameters); - } - return void 0; - } - break loop; - } - if (isClassExpression(location) && meaning & 32 /* Class */) { - const className = location.name; - if (className && name === className.escapedText) { - result = location.symbol; - break loop; - } - } - break; - case 233 /* ExpressionWithTypeArguments */: - if (lastLocation === location.expression && location.parent.token === 96 /* ExtendsKeyword */) { - const container = location.parent.parent; - if (isClassLike(container) && (result = lookup(getSymbolOfDeclaration(container).members, name, meaning & 788968 /* Type */))) { - if (nameNotFoundMessage) { - error2(errorLocation, Diagnostics.Base_class_expressions_cannot_reference_class_type_parameters); - } - return void 0; - } - } - break; - case 167 /* ComputedPropertyName */: - grandparent = location.parent.parent; - if (isClassLike(grandparent) || grandparent.kind === 264 /* InterfaceDeclaration */) { - if (result = lookup(getSymbolOfDeclaration(grandparent).members, name, meaning & 788968 /* Type */)) { - if (nameNotFoundMessage) { - error2(errorLocation, Diagnostics.A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type); - } - return void 0; - } - } - break; - case 219 /* ArrowFunction */: - if (getEmitScriptTarget(compilerOptions) >= 2 /* ES2015 */) { - break; - } - case 174 /* MethodDeclaration */: - case 176 /* Constructor */: - case 177 /* GetAccessor */: - case 178 /* SetAccessor */: - case 262 /* FunctionDeclaration */: - if (meaning & 3 /* Variable */ && name === "arguments") { - result = argumentsSymbol; - break loop; - } - break; - case 218 /* FunctionExpression */: - if (meaning & 3 /* Variable */ && name === "arguments") { - result = argumentsSymbol; - break loop; - } - if (meaning & 16 /* Function */) { - const functionName = location.name; - if (functionName && name === functionName.escapedText) { - result = location.symbol; - break loop; - } - } - break; - case 170 /* Decorator */: - if (location.parent && location.parent.kind === 169 /* Parameter */) { - location = location.parent; - } - if (location.parent && (isClassElement(location.parent) || location.parent.kind === 263 /* ClassDeclaration */)) { - location = location.parent; - } - break; - case 353 /* JSDocTypedefTag */: - case 345 /* JSDocCallbackTag */: - case 347 /* JSDocEnumTag */: - const root = getJSDocRoot(location); - if (root) { - location = root.parent; - } - break; - case 169 /* Parameter */: - if (lastLocation && (lastLocation === location.initializer || lastLocation === location.name && isBindingPattern(lastLocation))) { - if (!associatedDeclarationForContainingInitializerOrBindingName) { - associatedDeclarationForContainingInitializerOrBindingName = location; - } - } - break; - case 208 /* BindingElement */: - if (lastLocation && (lastLocation === location.initializer || lastLocation === location.name && isBindingPattern(lastLocation))) { - if (isParameterDeclaration(location) && !associatedDeclarationForContainingInitializerOrBindingName) { - associatedDeclarationForContainingInitializerOrBindingName = location; - } - } - break; - case 195 /* InferType */: - if (meaning & 262144 /* TypeParameter */) { - const parameterName = location.typeParameter.name; - if (parameterName && name === parameterName.escapedText) { - result = location.typeParameter.symbol; - break loop; - } - } - break; - case 281 /* ExportSpecifier */: - if (lastLocation && lastLocation === location.propertyName && location.parent.parent.moduleSpecifier) { - location = location.parent.parent.parent; - } - break; - } - if (isSelfReferenceLocation(location)) { - lastSelfReferenceLocation = location; - } - lastLocation = location; - location = isJSDocTemplateTag(location) ? getEffectiveContainerForJSDocTemplateTag(location) || location.parent : isJSDocParameterTag(location) || isJSDocReturnTag(location) ? getHostSignatureFromJSDoc(location) || location.parent : location.parent; } + withinDeferredContext = withinDeferredContext || getIsDeferredContext(location, lastLocation); + switch (location.kind) { + case 312 /* SourceFile */: + if (!isExternalOrCommonJsModule(location)) break; + isInExternalModule = true; + case 267 /* ModuleDeclaration */: + const moduleExports = ((_a = getSymbolOfDeclaration(location)) == null ? void 0 : _a.exports) || emptySymbols; + if (location.kind === 312 /* SourceFile */ || isModuleDeclaration(location) && location.flags & 33554432 /* Ambient */ && !isGlobalScopeAugmentation(location)) { + if (result = moduleExports.get("default" /* Default */)) { + const localSymbol = getLocalSymbolForExportDefault(result); + if (localSymbol && result.flags & meaning && localSymbol.escapedName === name) { + break loop; + } + result = void 0; + } + const moduleExport = moduleExports.get(name); + if (moduleExport && moduleExport.flags === 2097152 /* Alias */ && (getDeclarationOfKind(moduleExport, 281 /* ExportSpecifier */) || getDeclarationOfKind(moduleExport, 280 /* NamespaceExport */))) { + break; + } + } + if (name !== "default" /* Default */ && (result = lookup(moduleExports, name, meaning & 2623475 /* ModuleMember */))) { + if (isSourceFile(location) && location.commonJsModuleIndicator && !((_b = result.declarations) == null ? void 0 : _b.some(isJSDocTypeAlias))) { + result = void 0; + } else { + break loop; + } + } + break; + case 266 /* EnumDeclaration */: + if (result = lookup(((_c = getSymbolOfDeclaration(location)) == null ? void 0 : _c.exports) || emptySymbols, name, meaning & 8 /* EnumMember */)) { + if (nameNotFoundMessage && getIsolatedModules(compilerOptions) && !(location.flags & 33554432 /* Ambient */) && getSourceFileOfNode(location) !== getSourceFileOfNode(result.valueDeclaration)) { + error2(errorLocation, Diagnostics.Cannot_access_0_from_another_file_without_qualification_when_1_is_enabled_Use_2_instead, unescapeLeadingUnderscores(name), isolatedModulesLikeFlagName, `${unescapeLeadingUnderscores(getSymbolOfNode(location).escapedName)}.${unescapeLeadingUnderscores(name)}`); + } + break loop; + } + break; + case 172 /* PropertyDeclaration */: + if (!isStatic(location)) { + const ctor = findConstructorDeclaration(location.parent); + if (ctor && ctor.locals) { + if (lookup(ctor.locals, name, meaning & 111551 /* Value */)) { + Debug.assertNode(location, isPropertyDeclaration); + propertyWithInvalidInitializer = location; + } + } + } + break; + case 263 /* ClassDeclaration */: + case 231 /* ClassExpression */: + case 264 /* InterfaceDeclaration */: + if (result = lookup(getSymbolOfDeclaration(location).members || emptySymbols, name, meaning & 788968 /* Type */)) { + if (!isTypeParameterSymbolDeclaredInContainer(result, location)) { + result = void 0; + break; + } + if (lastLocation && isStatic(lastLocation)) { + if (nameNotFoundMessage) { + error2(errorLocation, Diagnostics.Static_members_cannot_reference_class_type_parameters); + } + return void 0; + } + break loop; + } + if (isClassExpression(location) && meaning & 32 /* Class */) { + const className = location.name; + if (className && name === className.escapedText) { + result = location.symbol; + break loop; + } + } + break; + case 233 /* ExpressionWithTypeArguments */: + if (lastLocation === location.expression && location.parent.token === 96 /* ExtendsKeyword */) { + const container = location.parent.parent; + if (isClassLike(container) && (result = lookup(getSymbolOfDeclaration(container).members, name, meaning & 788968 /* Type */))) { + if (nameNotFoundMessage) { + error2(errorLocation, Diagnostics.Base_class_expressions_cannot_reference_class_type_parameters); + } + return void 0; + } + } + break; + case 167 /* ComputedPropertyName */: + grandparent = location.parent.parent; + if (isClassLike(grandparent) || grandparent.kind === 264 /* InterfaceDeclaration */) { + if (result = lookup(getSymbolOfDeclaration(grandparent).members, name, meaning & 788968 /* Type */)) { + if (nameNotFoundMessage) { + error2(errorLocation, Diagnostics.A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type); + } + return void 0; + } + } + break; + case 219 /* ArrowFunction */: + if (getEmitScriptTarget(compilerOptions) >= 2 /* ES2015 */) { + break; + } + case 174 /* MethodDeclaration */: + case 176 /* Constructor */: + case 177 /* GetAccessor */: + case 178 /* SetAccessor */: + case 262 /* FunctionDeclaration */: + if (meaning & 3 /* Variable */ && name === "arguments") { + result = argumentsSymbol; + break loop; + } + break; + case 218 /* FunctionExpression */: + if (meaning & 3 /* Variable */ && name === "arguments") { + result = argumentsSymbol; + break loop; + } + if (meaning & 16 /* Function */) { + const functionName = location.name; + if (functionName && name === functionName.escapedText) { + result = location.symbol; + break loop; + } + } + break; + case 170 /* Decorator */: + if (location.parent && location.parent.kind === 169 /* Parameter */) { + location = location.parent; + } + if (location.parent && (isClassElement(location.parent) || location.parent.kind === 263 /* ClassDeclaration */)) { + location = location.parent; + } + break; + case 353 /* JSDocTypedefTag */: + case 345 /* JSDocCallbackTag */: + case 347 /* JSDocEnumTag */: + const root = getJSDocRoot(location); + if (root) { + location = root.parent; + } + break; + case 169 /* Parameter */: + if (lastLocation && (lastLocation === location.initializer || lastLocation === location.name && isBindingPattern(lastLocation))) { + if (!associatedDeclarationForContainingInitializerOrBindingName) { + associatedDeclarationForContainingInitializerOrBindingName = location; + } + } + break; + case 208 /* BindingElement */: + if (lastLocation && (lastLocation === location.initializer || lastLocation === location.name && isBindingPattern(lastLocation))) { + if (isParameterDeclaration(location) && !associatedDeclarationForContainingInitializerOrBindingName) { + associatedDeclarationForContainingInitializerOrBindingName = location; + } + } + break; + case 195 /* InferType */: + if (meaning & 262144 /* TypeParameter */) { + const parameterName = location.typeParameter.name; + if (parameterName && name === parameterName.escapedText) { + result = location.typeParameter.symbol; + break loop; + } + } + break; + case 281 /* ExportSpecifier */: + if (lastLocation && lastLocation === location.propertyName && location.parent.parent.moduleSpecifier) { + location = location.parent.parent.parent; + } + break; + } + if (isSelfReferenceLocation(location)) { + lastSelfReferenceLocation = location; + } + lastLocation = location; + location = isJSDocTemplateTag(location) ? getEffectiveContainerForJSDocTemplateTag(location) || location.parent : isJSDocParameterTag(location) || isJSDocReturnTag(location) ? getHostSignatureFromJSDoc(location) || location.parent : location.parent; + } if (isUse && result && (!lastSelfReferenceLocation || result !== lastSelfReferenceLocation.symbol)) { result.isReferenced |= meaning; } @@ -47544,23 +45072,15 @@ ${lanes.join("\n")} } if (!result) { if (originalLocation && isInJSFile(originalLocation) && originalLocation.parent) { - if (isRequireCall( - originalLocation.parent, - /*requireStringLiteralLikeArgument*/ - false - )) { + if (isRequireCall(originalLocation.parent, /*requireStringLiteralLikeArgument*/ + false)) { return requireSymbol; } } } function checkAndReportErrorForInvalidInitializer() { if (propertyWithInvalidInitializer && !emitStandardClassFields) { - error2( - errorLocation, - errorLocation && propertyWithInvalidInitializer.type && textRangeContainsPositionInclusive(propertyWithInvalidInitializer.type, errorLocation.pos) ? Diagnostics.Type_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor : Diagnostics.Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor, - declarationNameToString(propertyWithInvalidInitializer.name), - diagnosticName(nameArg) - ); + error2(errorLocation, errorLocation && propertyWithInvalidInitializer.type && textRangeContainsPositionInclusive(propertyWithInvalidInitializer.type, errorLocation.pos) ? Diagnostics.Type_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor : Diagnostics.Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor, declarationNameToString(propertyWithInvalidInitializer.name), diagnosticName(nameArg)); return true; } return false; @@ -47568,7 +45088,8 @@ ${lanes.join("\n")} if (!result) { if (nameNotFoundMessage) { addLazyDiagnostic(() => { - if (!errorLocation || errorLocation.parent.kind !== 331 /* JSDocLink */ && !checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) && // TODO: GH#18217 + if (!errorLocation || errorLocation.parent.kind !== 331 /* JSDocLink */ && !checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) && + // TODO: GH#18217 !checkAndReportErrorForInvalidInitializer() && !checkAndReportErrorForExtendingInterface(errorLocation) && !checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) && !checkAndReportErrorForExportingPrimitiveType(errorLocation, name) && !checkAndReportErrorForUsingNamespaceAsTypeOrValue(errorLocation, name, meaning) && !checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) && !checkAndReportErrorForUsingValueAsType(errorLocation, name, meaning)) { let suggestion; let suggestedLib; @@ -47586,20 +45107,13 @@ ${lanes.join("\n")} } if (suggestion) { const suggestionName = symbolToString(suggestion); - const isUncheckedJS = isUncheckedJSSuggestion( - originalLocation, - suggestion, - /*excludeClasses*/ - false - ); + const isUncheckedJS = isUncheckedJSSuggestion(originalLocation, suggestion, /*excludeClasses*/ + false); 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); addErrorOrSuggestion(!isUncheckedJS, diagnostic); if (suggestion.valueDeclaration) { - addRelatedInfo( - diagnostic, - createDiagnosticForNode(suggestion.valueDeclaration, Diagnostics._0_is_declared_here, suggestionName) - ); + addRelatedInfo(diagnostic, createDiagnosticForNode(suggestion.valueDeclaration, Diagnostics._0_is_declared_here, suggestionName)); } } } @@ -47624,7 +45138,7 @@ ${lanes.join("\n")} } if (result && isInExternalModule && (meaning & 111551 /* Value */) === 111551 /* Value */ && !(originalLocation.flags & 16777216 /* JSDoc */)) { const merged = getMergedSymbol(result); - if (length(merged.declarations) && every(merged.declarations, (d) => isNamespaceExportDeclaration(d) || isSourceFile(d) && !!d.symbol.globalExports)) { + if (length(merged.declarations) && every(merged.declarations, d => isNamespaceExportDeclaration(d) || isSourceFile(d) && !!d.symbol.globalExports)) { errorOrSuggestion(!compilerOptions.allowUmdGlobalAccess, errorLocation, Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead, unescapeLeadingUnderscores(name)); } } @@ -47642,11 +45156,7 @@ ${lanes.join("\n")} if (typeOnlyDeclaration) { const message = typeOnlyDeclaration.kind === 281 /* ExportSpecifier */ || typeOnlyDeclaration.kind === 278 /* ExportDeclaration */ || typeOnlyDeclaration.kind === 280 /* NamespaceExport */ ? Diagnostics._0_cannot_be_used_as_a_value_because_it_was_exported_using_export_type : Diagnostics._0_cannot_be_used_as_a_value_because_it_was_imported_using_import_type; const unescapedName = unescapeLeadingUnderscores(name); - addTypeOnlyDeclarationRelatedInfo( - error2(errorLocation, message, unescapedName), - typeOnlyDeclaration, - unescapedName - ); + addTypeOnlyDeclarationRelatedInfo(error2(errorLocation, message, unescapedName), typeOnlyDeclaration, unescapedName); } } }); @@ -47654,16 +45164,8 @@ ${lanes.join("\n")} return result; } function addTypeOnlyDeclarationRelatedInfo(diagnostic, typeOnlyDeclaration, unescapedName) { - if (!typeOnlyDeclaration) - return diagnostic; - return addRelatedInfo( - diagnostic, - createDiagnosticForNode( - typeOnlyDeclaration, - typeOnlyDeclaration.kind === 281 /* ExportSpecifier */ || typeOnlyDeclaration.kind === 278 /* ExportDeclaration */ || typeOnlyDeclaration.kind === 280 /* NamespaceExport */ ? Diagnostics._0_was_exported_here : Diagnostics._0_was_imported_here, - unescapedName - ) - ); + if (!typeOnlyDeclaration) return diagnostic; + return addRelatedInfo(diagnostic, createDiagnosticForNode(typeOnlyDeclaration, typeOnlyDeclaration.kind === 281 /* ExportSpecifier */ || typeOnlyDeclaration.kind === 278 /* ExportDeclaration */ || typeOnlyDeclaration.kind === 280 /* NamespaceExport */ ? Diagnostics._0_was_exported_here : Diagnostics._0_was_imported_here, unescapedName)); } function getIsDeferredContext(location, lastLocation) { if (location.kind !== 219 /* ArrowFunction */ && location.kind !== 218 /* FunctionExpression */) { @@ -47710,13 +45212,9 @@ ${lanes.join("\n")} if (!isIdentifier(errorLocation) || errorLocation.escapedText !== name || isTypeReferenceIdentifier(errorLocation) || isInTypeQuery(errorLocation)) { return false; } - const container = getThisContainer( - errorLocation, - /*includeArrowFunctions*/ - false, - /*includeClassComputedPropertyName*/ - false - ); + const container = getThisContainer(errorLocation, /*includeArrowFunctions*/ + false, /*includeClassComputedPropertyName*/ + false); let location = container; while (location) { if (isClassLike(location.parent)) { @@ -47743,12 +45241,8 @@ ${lanes.join("\n")} } function checkAndReportErrorForExtendingInterface(errorLocation) { const expression = getEntityNameForExtendingInterface(errorLocation); - if (expression && resolveEntityName( - expression, - 64 /* Interface */, - /*ignoreErrors*/ - true - )) { + if (expression && resolveEntityName(expression, 64 /* Interface */, /*ignoreErrors*/ + true)) { error2(errorLocation, Diagnostics.Cannot_extend_an_interface_0_Did_you_mean_implements, getTextOfNode(expression)); return true; } @@ -47770,17 +45264,10 @@ ${lanes.join("\n")} function checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) { const namespaceMeaning = 1920 /* Namespace */ | (isInJSFile(errorLocation) ? 111551 /* Value */ : 0); if (meaning === namespaceMeaning) { - const symbol = resolveSymbol(resolveName( - errorLocation, - name, - 788968 /* Type */ & ~namespaceMeaning, - /*nameNotFoundMessage*/ - void 0, - /*nameArg*/ - void 0, - /*isUse*/ - false - )); + const symbol = resolveSymbol(resolveName(errorLocation, name, 788968 /* Type */ & ~namespaceMeaning, /*nameNotFoundMessage*/ + void 0, /*nameArg*/ + void 0, /*isUse*/ + false)); const parent2 = errorLocation.parent; if (symbol) { if (isQualifiedName(parent2)) { @@ -47788,12 +45275,7 @@ ${lanes.join("\n")} const propName = parent2.right.escapedText; const propType = getPropertyOfType(getDeclaredTypeOfSymbol(symbol), propName); if (propType) { - error2( - parent2, - Diagnostics.Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_property_1_in_0_with_0_1, - unescapeLeadingUnderscores(name), - unescapeLeadingUnderscores(propName) - ); + error2(parent2, Diagnostics.Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_property_1_in_0_with_0_1, unescapeLeadingUnderscores(name), unescapeLeadingUnderscores(propName)); return true; } } @@ -47805,17 +45287,10 @@ ${lanes.join("\n")} } function checkAndReportErrorForUsingValueAsType(errorLocation, name, meaning) { if (meaning & (788968 /* Type */ & ~1920 /* Namespace */)) { - const symbol = resolveSymbol(resolveName( - errorLocation, - name, - ~788968 /* Type */ & 111551 /* Value */, - /*nameNotFoundMessage*/ - void 0, - /*nameArg*/ - void 0, - /*isUse*/ - false - )); + const symbol = resolveSymbol(resolveName(errorLocation, name, ~788968 /* Type */ & 111551 /* Value */, /*nameNotFoundMessage*/ + void 0, /*nameArg*/ + void 0, /*isUse*/ + false)); if (symbol && !(symbol.flags & 1920 /* Namespace */)) { error2(errorLocation, Diagnostics._0_refers_to_a_value_but_is_being_used_as_a_type_here_Did_you_mean_typeof_0, unescapeLeadingUnderscores(name)); return true; @@ -47852,17 +45327,10 @@ ${lanes.join("\n")} } return true; } - const symbol = resolveSymbol(resolveName( - errorLocation, - name, - 788968 /* Type */ & ~111551 /* Value */, - /*nameNotFoundMessage*/ - void 0, - /*nameArg*/ - void 0, - /*isUse*/ - false - )); + const symbol = resolveSymbol(resolveName(errorLocation, name, 788968 /* Type */ & ~111551 /* Value */, /*nameNotFoundMessage*/ + void 0, /*nameArg*/ + void 0, /*isUse*/ + false)); const allFlags = symbol && getSymbolFlags(symbol); if (symbol && allFlags !== void 0 && !(allFlags & 111551 /* Value */)) { const rawName = unescapeLeadingUnderscores(name); @@ -47879,15 +45347,11 @@ ${lanes.join("\n")} return false; } function maybeMappedType(node, symbol) { - const container = findAncestor(node.parent, (n) => isComputedPropertyName(n) || isPropertySignature(n) ? false : isTypeLiteralNode(n) || "quit"); + const container = findAncestor(node.parent, n => isComputedPropertyName(n) || isPropertySignature(n) ? false : isTypeLiteralNode(n) || "quit"); if (container && container.members.length === 1) { const type = getDeclaredTypeOfSymbol(symbol); - return !!(type.flags & 1048576 /* Union */) && allTypesAssignableToKind( - type, - 384 /* StringOrNumberLiteral */, - /*strict*/ - true - ); + return !!(type.flags & 1048576 /* Union */) && allTypesAssignableToKind(type, 384 /* StringOrNumberLiteral */, /*strict*/ + true); } return false; } @@ -47905,37 +45369,19 @@ ${lanes.join("\n")} } function checkAndReportErrorForUsingNamespaceAsTypeOrValue(errorLocation, name, meaning) { if (meaning & (111551 /* Value */ & ~788968 /* Type */)) { - const symbol = resolveSymbol(resolveName( - errorLocation, - name, - 1024 /* NamespaceModule */, - /*nameNotFoundMessage*/ - void 0, - /*nameArg*/ - void 0, - /*isUse*/ - false - )); + const symbol = resolveSymbol(resolveName(errorLocation, name, 1024 /* NamespaceModule */, /*nameNotFoundMessage*/ + void 0, /*nameArg*/ + void 0, /*isUse*/ + false)); if (symbol) { - error2( - errorLocation, - Diagnostics.Cannot_use_namespace_0_as_a_value, - unescapeLeadingUnderscores(name) - ); + error2(errorLocation, Diagnostics.Cannot_use_namespace_0_as_a_value, unescapeLeadingUnderscores(name)); return true; } } else if (meaning & (788968 /* Type */ & ~111551 /* Value */)) { - const symbol = resolveSymbol(resolveName( - errorLocation, - name, - 1536 /* Module */, - /*nameNotFoundMessage*/ - void 0, - /*nameArg*/ - void 0, - /*isUse*/ - false - )); + const symbol = resolveSymbol(resolveName(errorLocation, name, 1536 /* Module */, /*nameNotFoundMessage*/ + void 0, /*nameArg*/ + void 0, /*isUse*/ + false)); if (symbol) { error2(errorLocation, Diagnostics.Cannot_use_namespace_0_as_a_type, unescapeLeadingUnderscores(name)); return true; @@ -47949,11 +45395,9 @@ ${lanes.join("\n")} if (result.flags & (16 /* Function */ | 1 /* FunctionScopedVariable */ | 67108864 /* Assignment */) && result.flags & 32 /* Class */) { return; } - 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"); + const declaration = (_a = result.declarations) == null ? void 0 : _a.find(d => isBlockOrCatchScoped(d) || isClassLike(d) || d.kind === 266 /* EnumDeclaration */); + + if (declaration === void 0) return Debug.fail("checkResolvedBlockScopedVariable could not find block-scoped declaration"); if (!(declaration.flags & 33554432 /* Ambient */) && !isBlockScopedNameDeclaredBeforeUse(declaration, errorLocation)) { let diagnosticMessage; const declarationName = declarationNameToString(getNameOfDeclaration(declaration)); @@ -47970,7 +45414,7 @@ ${lanes.join("\n")} } } function isSameScopeDescendentOf(initial, parent2, stopAt) { - return !!parent2 && !!findAncestor(initial, (n) => n === parent2 || (n === stopAt || isFunctionLike(n) && (!getImmediatelyInvokedFunctionExpression(n) || getFunctionFlags(n) & 3 /* AsyncGenerator */) ? "quit" : false)); + return !!parent2 && !!findAncestor(initial, n => n === parent2 || (n === stopAt || isFunctionLike(n) && (!getImmediatelyInvokedFunctionExpression(n) || getFunctionFlags(n) & 3 /* AsyncGenerator */) ? "quit" : false)); } function getAnyImportSyntax(node) { switch (node.kind) { @@ -48002,18 +45446,10 @@ ${lanes.join("\n")} return isIdentifier(commonJSPropertyAccess.name) ? resolveSymbol(getPropertyOfType(resolveExternalModuleTypeByLiteral(name), commonJSPropertyAccess.name.escapedText)) : void 0; } if (isVariableDeclaration(node) || node.moduleReference.kind === 283 /* ExternalModuleReference */) { - const immediate = resolveExternalModuleName( - node, - getExternalModuleRequireArgument(node) || getExternalModuleImportEqualsDeclarationExpression(node) - ); + const immediate = resolveExternalModuleName(node, getExternalModuleRequireArgument(node) || getExternalModuleImportEqualsDeclarationExpression(node)); const resolved2 = resolveExternalModuleSymbol(immediate); - markSymbolOfAliasDeclarationIfTypeOnly( - node, - immediate, - resolved2, - /*overwriteEmpty*/ - false - ); + markSymbolOfAliasDeclarationIfTypeOnly(node, immediate, resolved2, /*overwriteEmpty*/ + false); return resolved2; } const resolved = getSymbolOfPartOfRightHandSideOfImportEquals(node.moduleReference, dontResolveAlias); @@ -48021,14 +45457,9 @@ ${lanes.join("\n")} return resolved; } function checkAndReportErrorForResolvingImportAliasToTypeOnlySymbol(node, resolved) { - if (markSymbolOfAliasDeclarationIfTypeOnly( - node, - /*immediateTarget*/ - void 0, - resolved, - /*overwriteEmpty*/ - false - ) && !node.isTypeOnly) { + if (markSymbolOfAliasDeclarationIfTypeOnly(node, /*immediateTarget*/ + void 0, resolved, /*overwriteEmpty*/ + false) && !node.isTypeOnly) { const typeOnlyDeclaration = getTypeOnlyAliasDeclaration(getSymbolOfDeclaration(node)); const isExport = typeOnlyDeclaration.kind === 281 /* ExportSpecifier */ || typeOnlyDeclaration.kind === 278 /* ExportDeclaration */; const message = isExport ? Diagnostics.An_import_alias_cannot_reference_a_declaration_that_was_exported_using_export_type : Diagnostics.An_import_alias_cannot_reference_a_declaration_that_was_imported_using_import_type; @@ -48039,20 +45470,11 @@ ${lanes.join("\n")} } function resolveExportByName(moduleSymbol, name, sourceNode, dontResolveAlias) { const exportValue = moduleSymbol.exports.get("export=" /* ExportEquals */); - const exportSymbol = exportValue ? getPropertyOfType( - getTypeOfSymbol(exportValue), - name, - /*skipObjectFunctionPropertyAugment*/ - true - ) : moduleSymbol.exports.get(name); + const exportSymbol = exportValue ? getPropertyOfType(getTypeOfSymbol(exportValue), name, /*skipObjectFunctionPropertyAugment*/ + true) : moduleSymbol.exports.get(name); const resolved = resolveSymbol(exportSymbol, dontResolveAlias); - markSymbolOfAliasDeclarationIfTypeOnly( - sourceNode, - exportSymbol, - resolved, - /*overwriteEmpty*/ - false - ); + markSymbolOfAliasDeclarationIfTypeOnly(sourceNode, exportSymbol, resolved, /*overwriteEmpty*/ + false); return resolved; } function isSyntacticDefault(node) { @@ -48064,10 +45486,12 @@ ${lanes.join("\n")} function isESMFormatImportImportingCommonjsFormatFile(usageMode, targetMode) { return usageMode === 99 /* ESNext */ && targetMode === 1 /* CommonJS */; } + function isOnlyImportedAsDefault(usage) { const usageMode = getUsageModeForExpression(usage); return usageMode === 99 /* ESNext */ && endsWith(usage.text, ".json" /* Json */); } + function canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias, usage) { const usageMode = file && getUsageModeForExpression(usage); if (file && usageMode !== void 0) { @@ -48080,24 +45504,14 @@ ${lanes.join("\n")} return false; } if (!file || file.isDeclarationFile) { - const defaultExportSymbol = resolveExportByName( - moduleSymbol, - "default" /* Default */, - /*sourceNode*/ - void 0, - /*dontResolveAlias*/ - true - ); + const defaultExportSymbol = resolveExportByName(moduleSymbol, "default" /* Default */, /*sourceNode*/ + void 0, /*dontResolveAlias*/ + true); if (defaultExportSymbol && some(defaultExportSymbol.declarations, isSyntacticDefault)) { return false; } - if (resolveExportByName( - moduleSymbol, - escapeLeadingUnderscores("__esModule"), - /*sourceNode*/ - void 0, - dontResolveAlias - )) { + if (resolveExportByName(moduleSymbol, escapeLeadingUnderscores("__esModule"), /*sourceNode*/ + void 0, dontResolveAlias)) { return false; } return true; @@ -48105,13 +45519,8 @@ ${lanes.join("\n")} if (!isSourceFileJS(file)) { return hasExportAssignmentSymbol(moduleSymbol); } - return typeof file.externalModuleIndicator !== "object" && !resolveExportByName( - moduleSymbol, - escapeLeadingUnderscores("__esModule"), - /*sourceNode*/ - void 0, - dontResolveAlias - ); + return typeof file.externalModuleIndicator !== "object" && !resolveExportByName(moduleSymbol, escapeLeadingUnderscores("__esModule"), /*sourceNode*/ + void 0, dontResolveAlias); } function getTargetOfImportClause(node, dontResolveAlias) { const moduleSymbol = resolveExternalModuleName(node, node.parent.moduleSpecifier); @@ -48141,14 +45550,7 @@ ${lanes.join("\n")} const exportAssignment = exportEqualsSymbol.valueDeclaration; const err = error2(node.name, Diagnostics.Module_0_can_only_be_default_imported_using_the_1_flag, symbolToString(moduleSymbol), compilerOptionName); if (exportAssignment) { - addRelatedInfo( - err, - createDiagnosticForNode( - exportAssignment, - Diagnostics.This_module_is_declared_with_export_and_can_only_be_used_with_a_default_import_when_using_the_0_flag, - compilerOptionName - ) - ); + addRelatedInfo(err, createDiagnosticForNode(exportAssignment, Diagnostics.This_module_is_declared_with_export_and_can_only_be_used_with_a_default_import_when_using_the_0_flag, compilerOptionName)); } } else if (isImportClause(node)) { reportNonDefaultExport(moduleSymbol, node); @@ -48157,23 +45559,13 @@ ${lanes.join("\n")} } } else if (hasSyntheticDefault || hasDefaultOnly) { const resolved = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias); - markSymbolOfAliasDeclarationIfTypeOnly( - node, - moduleSymbol, - resolved, - /*overwriteEmpty*/ - false - ); + markSymbolOfAliasDeclarationIfTypeOnly(node, moduleSymbol, resolved, /*overwriteEmpty*/ + false); return resolved; } - markSymbolOfAliasDeclarationIfTypeOnly( - node, - exportDefaultSymbol, - /*finalTarget*/ - void 0, - /*overwriteEmpty*/ - false - ); + markSymbolOfAliasDeclarationIfTypeOnly(node, exportDefaultSymbol, /*finalTarget*/ + void 0, /*overwriteEmpty*/ + false); return exportDefaultSymbol; } function getModuleSpecifierForImportOrExport(node) { @@ -48195,22 +45587,16 @@ ${lanes.join("\n")} function reportNonDefaultExport(moduleSymbol, node) { var _a, _b, _c; if ((_a = moduleSymbol.exports) == null ? void 0 : _a.has(node.symbol.escapedName)) { - error2( - node.name, - Diagnostics.Module_0_has_no_default_export_Did_you_mean_to_use_import_1_from_0_instead, - symbolToString(moduleSymbol), - symbolToString(node.symbol) - ); + error2(node.name, Diagnostics.Module_0_has_no_default_export_Did_you_mean_to_use_import_1_from_0_instead, symbolToString(moduleSymbol), symbolToString(node.symbol)); } else { const diagnostic = error2(node.name, Diagnostics.Module_0_has_no_default_export, symbolToString(moduleSymbol)); const exportStar = (_b = moduleSymbol.exports) == null ? void 0 : _b.get("__export" /* ExportStar */); if (exportStar) { - const defaultExport = (_c = exportStar.declarations) == null ? void 0 : _c.find( - (decl) => { - var _a2, _b2; - return !!(isExportDeclaration(decl) && decl.moduleSpecifier && ((_b2 = (_a2 = resolveExternalModuleName(decl, decl.moduleSpecifier)) == null ? void 0 : _a2.exports) == null ? void 0 : _b2.has("default" /* Default */))); - } - ); + const defaultExport = (_c = exportStar.declarations) == null ? void 0 : _c.find(decl => { + var _a2, _b2; + return !!(isExportDeclaration(decl) && decl.moduleSpecifier && ((_b2 = (_a2 = resolveExternalModuleName(decl, decl.moduleSpecifier)) == null ? void 0 : _a2.exports) == null ? void 0 : _b2.has("default" /* Default */))); + }); + if (defaultExport) { addRelatedInfo(diagnostic, createDiagnosticForNode(defaultExport, Diagnostics.export_Asterisk_does_not_re_export_a_default)); } @@ -48220,39 +45606,19 @@ ${lanes.join("\n")} function getTargetOfNamespaceImport(node, dontResolveAlias) { const moduleSpecifier = node.parent.parent.moduleSpecifier; const immediate = resolveExternalModuleName(node, moduleSpecifier); - const resolved = resolveESModuleSymbol( - immediate, - moduleSpecifier, - dontResolveAlias, - /*suppressInteropError*/ - false - ); - markSymbolOfAliasDeclarationIfTypeOnly( - node, - immediate, - resolved, - /*overwriteEmpty*/ - false - ); + const resolved = resolveESModuleSymbol(immediate, moduleSpecifier, dontResolveAlias, /*suppressInteropError*/ + false); + markSymbolOfAliasDeclarationIfTypeOnly(node, immediate, resolved, /*overwriteEmpty*/ + false); return resolved; } function getTargetOfNamespaceExport(node, dontResolveAlias) { const moduleSpecifier = node.parent.moduleSpecifier; const immediate = moduleSpecifier && resolveExternalModuleName(node, moduleSpecifier); - const resolved = moduleSpecifier && resolveESModuleSymbol( - immediate, - moduleSpecifier, - dontResolveAlias, - /*suppressInteropError*/ - false - ); - markSymbolOfAliasDeclarationIfTypeOnly( - node, - immediate, - resolved, - /*overwriteEmpty*/ - false - ); + const resolved = moduleSpecifier && resolveESModuleSymbol(immediate, moduleSpecifier, dontResolveAlias, /*suppressInteropError*/ + false); + markSymbolOfAliasDeclarationIfTypeOnly(node, immediate, resolved, /*overwriteEmpty*/ + false); return resolved; } function combineValueAndTypeSymbols(valueSymbol, typeSymbol) { @@ -48266,12 +45632,9 @@ ${lanes.join("\n")} 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) { @@ -48280,15 +45643,8 @@ ${lanes.join("\n")} const exportSymbol = getExportsOfSymbol(symbol).get(name.escapedText); const resolved = resolveSymbol(exportSymbol, dontResolveAlias); const exportStarDeclaration = (_a = getSymbolLinks(symbol).typeOnlyExportStarMap) == null ? void 0 : _a.get(name.escapedText); - markSymbolOfAliasDeclarationIfTypeOnly( - specifier, - exportSymbol, - resolved, - /*overwriteEmpty*/ - false, - exportStarDeclaration, - name.escapedText - ); + markSymbolOfAliasDeclarationIfTypeOnly(specifier, exportSymbol, resolved, /*overwriteEmpty*/ + false, exportStarDeclaration, name.escapedText); return resolved; } } @@ -48309,13 +45665,8 @@ ${lanes.join("\n")} return void 0; } const suppressInteropError = name.escapedText === "default" /* Default */ && allowSyntheticDefaultImports; - const targetSymbol = resolveESModuleSymbol( - moduleSymbol, - moduleSpecifier, - /*dontResolveAlias*/ - false, - suppressInteropError - ); + const targetSymbol = resolveESModuleSymbol(moduleSymbol, moduleSpecifier, /*dontResolveAlias*/ + false, suppressInteropError); if (targetSymbol) { if (name.escapedText) { if (isShorthandAmbientModuleSymbol(moduleSymbol)) { @@ -48323,12 +45674,8 @@ ${lanes.join("\n")} } let symbolFromVariable; if (moduleSymbol && moduleSymbol.exports && moduleSymbol.exports.get("export=" /* ExportEquals */)) { - symbolFromVariable = getPropertyOfType( - getTypeOfSymbol(targetSymbol), - name.escapedText, - /*skipObjectFunctionPropertyAugment*/ - true - ); + symbolFromVariable = getPropertyOfType(getTypeOfSymbol(targetSymbol), name.escapedText, /*skipObjectFunctionPropertyAugment*/ + true); } else { symbolFromVariable = getPropertyOfVariable(targetSymbol, name.escapedText); } @@ -48361,12 +45708,7 @@ ${lanes.join("\n")} } } else { if ((_a = moduleSymbol.exports) == null ? void 0 : _a.has("default" /* Default */)) { - error2( - name, - Diagnostics.Module_0_has_no_exported_member_1_Did_you_mean_to_use_import_1_from_0_instead, - moduleName, - declarationName - ); + error2(name, Diagnostics.Module_0_has_no_exported_member_1_Did_you_mean_to_use_import_1_from_0_instead, moduleName, declarationName); } else { reportNonExportedMember(node, name, declarationName, moduleSymbol, moduleName); } @@ -48381,7 +45723,7 @@ ${lanes.join("\n")} if (exportedEqualsSymbol) { getSymbolIfSameReference(exportedEqualsSymbol, localSymbol) ? reportInvalidImportEqualsExportMember(node, name, declarationName, moduleName) : error2(name, Diagnostics.Module_0_has_no_exported_member_1, moduleName, declarationName); } else { - const exportedSymbol = exports ? find(symbolsToArray(exports), (symbol) => !!getSymbolIfSameReference(symbol, localSymbol)) : void 0; + const exportedSymbol = exports ? find(symbolsToArray(exports), symbol => !!getSymbolIfSameReference(symbol, localSymbol)) : void 0; const diagnostic = exportedSymbol ? error2(name, Diagnostics.Module_0_declares_1_locally_but_it_is_exported_as_2, moduleName, declarationName, symbolToString(exportedSymbol)) : error2(name, Diagnostics.Module_0_declares_1_locally_but_it_is_not_exported, moduleName, declarationName); if (localSymbol.declarations) { addRelatedInfo(diagnostic, ...map(localSymbol.declarations, (decl, index) => createDiagnosticForNode(decl, index === 0 ? Diagnostics._0_is_declared_here : Diagnostics.and_here, declarationName))); @@ -48420,14 +45762,9 @@ ${lanes.join("\n")} if (commonJSPropertyAccess && resolved && isIdentifier(name)) { return resolveSymbol(getPropertyOfType(getTypeOfSymbol(resolved), name.escapedText), dontResolveAlias); } - markSymbolOfAliasDeclarationIfTypeOnly( - node, - /*immediateTarget*/ - void 0, - resolved, - /*overwriteEmpty*/ - false - ); + markSymbolOfAliasDeclarationIfTypeOnly(node, /*immediateTarget*/ + void 0, resolved, /*overwriteEmpty*/ + false); return resolved; } function getCommonJSPropertyAccess(node) { @@ -48438,14 +45775,9 @@ ${lanes.join("\n")} function getTargetOfNamespaceExportDeclaration(node, dontResolveAlias) { if (canHaveSymbol(node.parent)) { const resolved = resolveExternalModuleSymbol(node.parent.symbol, dontResolveAlias); - markSymbolOfAliasDeclarationIfTypeOnly( - node, - /*immediateTarget*/ - void 0, - resolved, - /*overwriteEmpty*/ - false - ); + markSymbolOfAliasDeclarationIfTypeOnly(node, /*immediateTarget*/ + void 0, resolved, /*overwriteEmpty*/ + false); return resolved; } } @@ -48457,34 +45789,19 @@ ${lanes.join("\n")} return getTargetofModuleDefault(moduleSymbol, node, !!dontResolveAlias); } } - const resolved = node.parent.parent.moduleSpecifier ? getExternalModuleMember(node.parent.parent, node, dontResolveAlias) : resolveEntityName( - node.propertyName || node.name, - meaning, - /*ignoreErrors*/ - false, - dontResolveAlias - ); - markSymbolOfAliasDeclarationIfTypeOnly( - node, - /*immediateTarget*/ - void 0, - resolved, - /*overwriteEmpty*/ - false - ); + const resolved = node.parent.parent.moduleSpecifier ? getExternalModuleMember(node.parent.parent, node, dontResolveAlias) : resolveEntityName(node.propertyName || node.name, meaning, /*ignoreErrors*/ + false, dontResolveAlias); + markSymbolOfAliasDeclarationIfTypeOnly(node, /*immediateTarget*/ + void 0, resolved, /*overwriteEmpty*/ + false); return resolved; } function getTargetOfExportAssignment(node, dontResolveAlias) { const expression = isExportAssignment(node) ? node.expression : node.right; const resolved = getTargetOfAliasLikeExpression(expression, dontResolveAlias); - markSymbolOfAliasDeclarationIfTypeOnly( - node, - /*immediateTarget*/ - void 0, - resolved, - /*overwriteEmpty*/ - false - ); + markSymbolOfAliasDeclarationIfTypeOnly(node, /*immediateTarget*/ + void 0, resolved, /*overwriteEmpty*/ + false); return resolved; } function getTargetOfAliasLikeExpression(expression, dontResolveAlias) { @@ -48494,13 +45811,8 @@ ${lanes.join("\n")} if (!isEntityName(expression) && !isEntityNameExpression(expression)) { return void 0; } - const aliasLike = resolveEntityName( - expression, - 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */, - /*ignoreErrors*/ - true, - dontResolveAlias - ); + const aliasLike = resolveEntityName(expression, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ + true, dontResolveAlias); if (aliasLike) { return aliasLike; } @@ -48535,13 +45847,8 @@ ${lanes.join("\n")} case 270 /* NamespaceExportDeclaration */: return getTargetOfNamespaceExportDeclaration(node, dontRecursivelyResolve); case 304 /* ShorthandPropertyAssignment */: - return resolveEntityName( - node.name, - 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */, - /*ignoreErrors*/ - true, - dontRecursivelyResolve - ); + return resolveEntityName(node.name, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ + true, dontRecursivelyResolve); case 303 /* PropertyAssignment */: return getTargetOfAliasLikeExpression(node.initializer, dontRecursivelyResolve); case 212 /* ElementAccessExpression */: @@ -48552,10 +45859,10 @@ ${lanes.join("\n")} } } 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) { return !dontResolveAlias && isNonLocalAlias(symbol) ? resolveAlias(symbol) : symbol; } @@ -48565,8 +45872,7 @@ ${lanes.join("\n")} 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; @@ -48588,12 +45894,8 @@ ${lanes.join("\n")} function getSymbolFlags(symbol, excludeTypeOnlyMeanings, excludeLocalMeanings) { const typeOnlyDeclaration = excludeTypeOnlyMeanings && getTypeOnlyAliasDeclaration(symbol); const typeOnlyDeclarationIsExportStar = typeOnlyDeclaration && isExportDeclaration(typeOnlyDeclaration); - const typeOnlyResolution = typeOnlyDeclaration && (typeOnlyDeclarationIsExportStar ? resolveExternalModuleName( - typeOnlyDeclaration.moduleSpecifier, - typeOnlyDeclaration.moduleSpecifier, - /*ignoreErrors*/ - true - ) : resolveAlias(typeOnlyDeclaration.symbol)); + const typeOnlyResolution = typeOnlyDeclaration && (typeOnlyDeclarationIsExportStar ? resolveExternalModuleName(typeOnlyDeclaration.moduleSpecifier, typeOnlyDeclaration.moduleSpecifier, /*ignoreErrors*/ + true) : resolveAlias(typeOnlyDeclaration.symbol)); const typeOnlyExportStarTargets = typeOnlyDeclarationIsExportStar && typeOnlyResolution ? getExportsOfModule(typeOnlyResolution) : void 0; let flags = excludeLocalMeanings ? 0 /* None */ : symbol.flags; let seenSymbols; @@ -48605,6 +45907,7 @@ ${lanes.join("\n")} if (target === unknownSymbol) { return 67108863 /* All */; } + if (target === symbol || (seenSymbols == null ? void 0 : seenSymbols.has(target))) { break; } @@ -48612,7 +45915,7 @@ ${lanes.join("\n")} if (seenSymbols) { seenSymbols.add(target); } else { - seenSymbols = /* @__PURE__ */ new Set([symbol, target]); + seenSymbols = /* @__PURE__ */new Set([symbol, target]); } } flags |= target.flags; @@ -48621,8 +45924,7 @@ ${lanes.join("\n")} 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); @@ -48643,9 +45945,10 @@ ${lanes.join("\n")} function markSymbolOfAliasDeclarationIfTypeOnlyWorker(aliasDeclarationLinks, target, overwriteEmpty) { var _a; if (target && (aliasDeclarationLinks.typeOnlyDeclaration === void 0 || overwriteEmpty && aliasDeclarationLinks.typeOnlyDeclaration === false)) { - const exportSymbol = ((_a = target.exports) == null ? void 0 : _a.get("export=" /* ExportEquals */)) ?? target; + var _ref10, _ref11; + const exportSymbol = (_ref10 = (_a = target.exports) == null ? void 0 : _a.get("export=" /* ExportEquals */)) !== null && _ref10 !== void 0 ? _ref10 : target; const typeOnly = exportSymbol.declarations && find(exportSymbol.declarations, isTypeOnlyImportOrExportDeclaration); - aliasDeclarationLinks.typeOnlyDeclaration = typeOnly ?? getSymbolLinks(exportSymbol).typeOnlyDeclaration ?? false; + aliasDeclarationLinks.typeOnlyDeclaration = (_ref11 = typeOnly !== null && typeOnly !== void 0 ? typeOnly : getSymbolLinks(exportSymbol).typeOnlyDeclaration) !== null && _ref11 !== void 0 ? _ref11 : false; } return !!aliasDeclarationLinks.typeOnlyDeclaration; } @@ -48670,11 +45973,8 @@ ${lanes.join("\n")} const symbol = getSymbolOfDeclaration(node); const target = resolveAlias(symbol); if (target) { - const markAlias = target === unknownSymbol || getSymbolFlags( - symbol, - /*excludeTypeOnlyMeanings*/ - true - ) & 111551 /* Value */ && !isConstEnumOrConstEnumOnlyModule(target); + const markAlias = target === unknownSymbol || getSymbolFlags(symbol, /*excludeTypeOnlyMeanings*/ + true) & 111551 /* Value */ && !isConstEnumOrConstEnumOnlyModule(target); if (markAlias) { markAliasSymbolAsReferenced(symbol); } @@ -48686,8 +45986,7 @@ ${lanes.join("\n")} if (!links.referenced) { links.referenced = true; const node = getDeclarationOfAliasSymbol(symbol); - if (!node) - return Debug.fail(); + if (!node) return Debug.fail(); if (isInternalModuleImportEqualsDeclaration(node)) { if (getSymbolFlags(resolveSymbol(symbol)) & 111551 /* Value */) { checkExpressionCached(node.moduleReference); @@ -48706,33 +46005,19 @@ ${lanes.join("\n")} entityName = entityName.parent; } if (entityName.kind === 80 /* Identifier */ || entityName.parent.kind === 166 /* QualifiedName */) { - return resolveEntityName( - entityName, - 1920 /* Namespace */, - /*ignoreErrors*/ - false, - dontResolveAlias - ); + return resolveEntityName(entityName, 1920 /* Namespace */, /*ignoreErrors*/ + false, dontResolveAlias); } else { Debug.assert(entityName.parent.kind === 271 /* ImportEqualsDeclaration */); - return resolveEntityName( - entityName, - 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */, - /*ignoreErrors*/ - false, - dontResolveAlias - ); + return resolveEntityName(entityName, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ + false, dontResolveAlias); } } function getFullyQualifiedName(symbol, containingLocation) { - return symbol.parent ? getFullyQualifiedName(symbol.parent, containingLocation) + "." + symbolToString(symbol) : symbolToString( - symbol, - containingLocation, - /*meaning*/ - void 0, - 32 /* DoNotIncludeSymbolChain */ | 4 /* AllowAnyNodeKind */ - ); + return symbol.parent ? getFullyQualifiedName(symbol.parent, containingLocation) + "." + symbolToString(symbol) : symbolToString(symbol, containingLocation, /*meaning*/ + void 0, 32 /* DoNotIncludeSymbolChain */ | 4 /* AllowAnyNodeKind */); } + function getContainingQualifiedNameNode(node) { while (isQualifiedName(node.parent)) { node = node.parent; @@ -48741,16 +46026,9 @@ ${lanes.join("\n")} } function tryGetQualifiedNameAsValue(node) { let left = getFirstIdentifier(node); - let symbol = resolveName( - left, - left.escapedText, - 111551 /* Value */, - /*nameNotFoundMessage*/ - void 0, - left, - /*isUse*/ - true - ); + let symbol = resolveName(left, left.escapedText, 111551 /* Value */, /*nameNotFoundMessage*/ + void 0, left, /*isUse*/ + true); if (!symbol) { return void 0; } @@ -48773,31 +46051,17 @@ ${lanes.join("\n")} if (name.kind === 80 /* Identifier */) { const message = meaning === namespaceMeaning || nodeIsSynthesized(name) ? Diagnostics.Cannot_find_namespace_0 : getCannotFindNameDiagnosticForName(getFirstIdentifier(name)); const symbolFromJSPrototype = isInJSFile(name) && !nodeIsSynthesized(name) ? resolveEntityNameFromAssignmentDeclaration(name, meaning) : void 0; - symbol = getMergedSymbol(resolveName( - location || name, - name.escapedText, - meaning, - ignoreErrors || symbolFromJSPrototype ? void 0 : message, - name, - /*isUse*/ - true, - /*excludeGlobals*/ - false - )); + symbol = getMergedSymbol(resolveName(location || name, name.escapedText, meaning, ignoreErrors || symbolFromJSPrototype ? void 0 : message, name, /*isUse*/ + true, /*excludeGlobals*/ + false)); if (!symbol) { return getMergedSymbol(symbolFromJSPrototype); } } else if (name.kind === 166 /* QualifiedName */ || name.kind === 211 /* PropertyAccessExpression */) { const left = name.kind === 166 /* QualifiedName */ ? name.left : name.expression; const right = name.kind === 166 /* QualifiedName */ ? name.right : name.name; - let namespace = resolveEntityName( - left, - namespaceMeaning, - ignoreErrors, - /*dontResolveAlias*/ - false, - location - ); + let namespace = resolveEntityName(left, namespaceMeaning, ignoreErrors, /*dontResolveAlias*/ + false, location); if (!namespace || nodeIsMissing(right)) { return void 0; } else if (namespace === unknownSymbol) { @@ -48829,22 +46093,13 @@ ${lanes.join("\n")} const containingQualifiedName = isQualifiedName(name) && getContainingQualifiedNameNode(name); const canSuggestTypeof = globalObjectType && meaning & 788968 /* Type */ && containingQualifiedName && !isTypeOfExpression(containingQualifiedName.parent) && tryGetQualifiedNameAsValue(containingQualifiedName); if (canSuggestTypeof) { - error2( - containingQualifiedName, - Diagnostics._0_refers_to_a_value_but_is_being_used_as_a_type_here_Did_you_mean_typeof_0, - entityNameToString(containingQualifiedName) - ); + error2(containingQualifiedName, Diagnostics._0_refers_to_a_value_but_is_being_used_as_a_type_here_Did_you_mean_typeof_0, entityNameToString(containingQualifiedName)); return void 0; } if (meaning & 1920 /* Namespace */ && isQualifiedName(name.parent)) { const exportedTypeSymbol = getMergedSymbol(getSymbol2(getExportsOfSymbol(namespace), right.escapedText, 788968 /* Type */)); if (exportedTypeSymbol) { - error2( - name.parent.right, - Diagnostics.Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_property_1_in_0_with_0_1, - symbolToString(exportedTypeSymbol), - unescapeLeadingUnderscores(name.parent.right.escapedText) - ); + error2(name.parent.right, Diagnostics.Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_property_1_in_0_with_0_1, symbolToString(exportedTypeSymbol), unescapeLeadingUnderscores(name.parent.right.escapedText)); return void 0; } } @@ -48857,14 +46112,9 @@ ${lanes.join("\n")} } 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), - symbol, - /*finalTarget*/ - void 0, - /*overwriteEmpty*/ - true - ); + markSymbolOfAliasDeclarationIfTypeOnly(getAliasDeclarationFromName(name), symbol, /*finalTarget*/ + void 0, /*overwriteEmpty*/ + true); } return symbol.flags & meaning || dontResolveAlias ? symbol : resolveAlias(symbol); } @@ -48872,21 +46122,14 @@ ${lanes.join("\n")} if (isJSDocTypeReference(name.parent)) { const secondaryLocation = getAssignmentDeclarationLocation(name.parent); if (secondaryLocation) { - return resolveName( - secondaryLocation, - name.escapedText, - meaning, - /*nameNotFoundMessage*/ - void 0, - name, - /*isUse*/ - true - ); + return resolveName(secondaryLocation, name.escapedText, meaning, /*nameNotFoundMessage*/ + void 0, name, /*isUse*/ + true); } } } function getAssignmentDeclarationLocation(node) { - const typeAlias = findAncestor(node, (node2) => !(isJSDocNode(node2) || node2.flags & 16777216 /* JSDoc */) ? "quit" : isJSDocTypeAlias(node2)); + const typeAlias = findAncestor(node, node2 => !(isJSDocNode(node2) || node2.flags & 16777216 /* JSDoc */) ? "quit" : isJSDocTypeAlias(node2)); if (typeAlias) { return; } @@ -48925,11 +46168,8 @@ ${lanes.join("\n")} } function getExpandoSymbol(symbol) { const decl = symbol.valueDeclaration; - if (!decl || !isInJSFile(decl) || symbol.flags & 524288 /* TypeAlias */ || getExpandoInitializer( - decl, - /*isPrototypeAssignment*/ - false - )) { + if (!decl || !isInJSFile(decl) || symbol.flags & 524288 /* TypeAlias */ || getExpandoInitializer(decl, /*isPrototypeAssignment*/ + false)) { return void 0; } const init = isVariableDeclaration(decl) ? getDeclaredExpandoInitializer(decl) : getAssignedExpandoInitializer(decl); @@ -48955,11 +46195,8 @@ ${lanes.join("\n")} const withoutAtTypePrefix = removePrefix(moduleReference, "@types/"); error2(errorNode, diag2, withoutAtTypePrefix, moduleReference); } - const ambientModule = tryFindAmbientModule( - moduleReference, - /*withAugmentations*/ - true - ); + const ambientModule = tryFindAmbientModule(moduleReference, /*withAugmentations*/ + true); if (ambientModule) { return ambientModule; } @@ -48977,11 +46214,7 @@ ${lanes.join("\n")} if (resolvedModule.resolvedUsingTsExtension && isDeclarationFileName(moduleReference)) { const importOrExport = ((_h = findAncestor(location, isImportDeclaration)) == null ? void 0 : _h.importClause) || findAncestor(location, or(isImportEqualsDeclaration, isExportDeclaration)); if (importOrExport && !importOrExport.isTypeOnly || findAncestor(location, isImportCall)) { - error2( - errorNode, - Diagnostics.A_declaration_file_cannot_be_imported_without_import_type_Did_you_mean_to_import_an_implementation_file_0_instead, - getSuggestedImportSource(Debug.checkDefined(tryExtractTSExtension(moduleReference))) - ); + error2(errorNode, Diagnostics.A_declaration_file_cannot_be_imported_without_import_type_Did_you_mean_to_import_an_implementation_file_0_instead, getSuggestedImportSource(Debug.checkDefined(tryExtractTSExtension(moduleReference)))); } } else if (resolvedModule.resolvedUsingTsExtension && !shouldAllowImportingTsExtension(compilerOptions, currentSourceFile.fileName)) { const importOrExport = ((_i = findAncestor(location, isImportDeclaration)) == null ? void 0 : _i.importClause) || findAncestor(location, or(isImportEqualsDeclaration, isExportDeclaration)); @@ -48992,19 +46225,12 @@ ${lanes.join("\n")} } if (sourceFile.symbol) { if (resolvedModule.isExternalLibraryImport && !resolutionExtensionIsTSOrJson(resolvedModule.extension)) { - errorOnImplicitAnyModule( - /*isError*/ - false, - errorNode, - currentSourceFile, - mode, - resolvedModule, - moduleReference - ); + errorOnImplicitAnyModule( /*isError*/ + false, errorNode, currentSourceFile, mode, resolvedModule, moduleReference); } if (moduleResolutionKind === 3 /* Node16 */ || moduleResolutionKind === 99 /* NodeNext */) { const isSyncImport = currentSourceFile.impliedNodeFormat === 1 /* CommonJS */ && !findAncestor(location, isImportCall) || !!findAncestor(location, isImportEqualsDeclaration); - const overrideHost = findAncestor(location, (l) => isImportTypeNode(l) || isExportDeclaration(l) || isImportDeclaration(l)); + const overrideHost = findAncestor(location, l => isImportTypeNode(l) || isExportDeclaration(l) || isImportDeclaration(l)); if (isSyncImport && sourceFile.impliedNodeFormat === 99 /* ESNext */ && !hasResolutionModeOverride(overrideHost)) { if (findAncestor(location, isImportEqualsDeclaration)) { error2(errorNode, Diagnostics.Module_0_cannot_be_imported_using_this_construct_The_specifier_only_resolves_to_an_ES_module_which_cannot_be_imported_with_require_Use_an_ECMAScript_import_instead, moduleReference); @@ -49016,47 +46242,23 @@ ${lanes.join("\n")} const targetExt = ext === ".ts" /* Ts */ ? ".mts" /* Mts */ : ext === ".js" /* Js */ ? ".mjs" /* Mjs */ : void 0; if (scope && !scope.contents.packageJsonContent.type) { if (targetExt) { - diagnosticDetails = chainDiagnosticMessages( - /*details*/ - void 0, - Diagnostics.To_convert_this_file_to_an_ECMAScript_module_change_its_file_extension_to_0_or_add_the_field_type_Colon_module_to_1, - targetExt, - combinePaths(scope.packageDirectory, "package.json") - ); + diagnosticDetails = chainDiagnosticMessages( /*details*/ + void 0, Diagnostics.To_convert_this_file_to_an_ECMAScript_module_change_its_file_extension_to_0_or_add_the_field_type_Colon_module_to_1, targetExt, combinePaths(scope.packageDirectory, "package.json")); } else { - diagnosticDetails = chainDiagnosticMessages( - /*details*/ - void 0, - Diagnostics.To_convert_this_file_to_an_ECMAScript_module_add_the_field_type_Colon_module_to_0, - combinePaths(scope.packageDirectory, "package.json") - ); + diagnosticDetails = chainDiagnosticMessages( /*details*/ + void 0, Diagnostics.To_convert_this_file_to_an_ECMAScript_module_add_the_field_type_Colon_module_to_0, combinePaths(scope.packageDirectory, "package.json")); } } else { if (targetExt) { - diagnosticDetails = chainDiagnosticMessages( - /*details*/ - void 0, - Diagnostics.To_convert_this_file_to_an_ECMAScript_module_change_its_file_extension_to_0_or_create_a_local_package_json_file_with_type_Colon_module, - targetExt - ); + diagnosticDetails = chainDiagnosticMessages( /*details*/ + void 0, Diagnostics.To_convert_this_file_to_an_ECMAScript_module_change_its_file_extension_to_0_or_create_a_local_package_json_file_with_type_Colon_module, targetExt); } else { - diagnosticDetails = chainDiagnosticMessages( - /*details*/ - void 0, - Diagnostics.To_convert_this_file_to_an_ECMAScript_module_create_a_local_package_json_file_with_type_Colon_module - ); + diagnosticDetails = chainDiagnosticMessages( /*details*/ + void 0, Diagnostics.To_convert_this_file_to_an_ECMAScript_module_create_a_local_package_json_file_with_type_Colon_module); } } } - diagnostics.add(createDiagnosticForNodeFromMessageChain( - getSourceFileOfNode(errorNode), - errorNode, - chainDiagnosticMessages( - diagnosticDetails, - Diagnostics.The_current_file_is_a_CommonJS_module_whose_imports_will_produce_require_calls_however_the_referenced_file_is_an_ECMAScript_module_and_cannot_be_imported_with_require_Consider_writing_a_dynamic_import_0_call_instead, - moduleReference - ) - )); + diagnostics.add(createDiagnosticForNodeFromMessageChain(getSourceFileOfNode(errorNode), errorNode, chainDiagnosticMessages(diagnosticDetails, Diagnostics.The_current_file_is_a_CommonJS_module_whose_imports_will_produce_require_calls_however_the_referenced_file_is_an_ECMAScript_module_and_cannot_be_imported_with_require_Consider_writing_a_dynamic_import_0_call_instead, moduleReference))); } } } @@ -49068,7 +46270,7 @@ ${lanes.join("\n")} return void 0; } if (patternAmbientModules) { - const pattern = findBestPatternMatch(patternAmbientModules, (_) => _.pattern, moduleReference); + const pattern = findBestPatternMatch(patternAmbientModules, _ => _.pattern, moduleReference); if (pattern) { const augmentation = patternAmbientModuleAugmentations && patternAmbientModuleAugmentations.get(moduleReference); if (augmentation) { @@ -49082,15 +46284,8 @@ ${lanes.join("\n")} const diag2 = Diagnostics.Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented; error2(errorNode, diag2, moduleReference, resolvedModule.resolvedFileName); } else { - errorOnImplicitAnyModule( - /*isError*/ - noImplicitAny && !!moduleNotFoundError, - errorNode, - currentSourceFile, - mode, - resolvedModule, - moduleReference - ); + errorOnImplicitAnyModule( /*isError*/ + noImplicitAny && !!moduleNotFoundError, errorNode, currentSourceFile, mode, resolvedModule, moduleReference); } return void 0; } @@ -49133,21 +46328,15 @@ ${lanes.join("\n")} return importSourceWithoutExtension; } } - function errorOnImplicitAnyModule(isError, errorNode, sourceFile, mode, { packageId, resolvedFileName }, moduleReference) { + function errorOnImplicitAnyModule(isError, errorNode, sourceFile, mode, { + packageId, + resolvedFileName + }, moduleReference) { let errorInfo; if (!isExternalModuleNameRelative(moduleReference) && packageId) { errorInfo = createModuleNotFoundChain(sourceFile, host, moduleReference, mode, packageId.name); } - errorOrSuggestion( - isError, - errorNode, - chainDiagnosticMessages( - errorInfo, - Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type, - moduleReference, - resolvedFileName - ) - ); + errorOrSuggestion(isError, errorNode, chainDiagnosticMessages(errorInfo, Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type, moduleReference, resolvedFileName)); } function resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) { if (moduleSymbol == null ? void 0 : moduleSymbol.exports) { @@ -49171,8 +46360,7 @@ ${lanes.join("\n")} 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) { @@ -49206,12 +46394,9 @@ ${lanes.join("\n")} if (!sigs || !sigs.length) { sigs = getSignaturesOfStructuredType(type, 1 /* Construct */); } - if (sigs && sigs.length || getPropertyOfType( - type, - "default" /* Default */, - /*skipObjectFunctionPropertyAugment*/ - true - ) || isEsmCjsRef) { + + if (sigs && sigs.length || getPropertyOfType(type, "default" /* Default */, /*skipObjectFunctionPropertyAugment*/ + true) || isEsmCjsRef) { const moduleType = type.flags & 3670016 /* StructuredType */ ? getTypeWithSyntheticDefaultImportType(type, symbol, moduleSymbol, reference) : createDefaultPropertyWrapperForModule(symbol, symbol.parent); return cloneTypeAsModuleType(symbol, moduleType, referenceParent); } @@ -49226,14 +46411,10 @@ ${lanes.join("\n")} 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; @@ -49291,7 +46472,8 @@ ${lanes.join("\n")} return shouldTreatPropertiesOfExternalModuleAsExports(type) ? getPropertyOfType(type, memberName) : void 0; } function shouldTreatPropertiesOfExternalModuleAsExports(resolvedExternalModuleType) { - return !(resolvedExternalModuleType.flags & 402784252 /* Primitive */ || getObjectFlags(resolvedExternalModuleType) & 1 /* Class */ || // `isArrayOrTupleLikeType` is too expensive to use in this auto-imports hot path + return !(resolvedExternalModuleType.flags & 402784252 /* Primitive */ || getObjectFlags(resolvedExternalModuleType) & 1 /* Class */ || + // `isArrayOrTupleLikeType` is too expensive to use in this auto-imports hot path isArrayType(resolvedExternalModuleType) || isTupleType(resolvedExternalModuleType)); } function getExportsOfSymbol(symbol) { @@ -49300,18 +46482,19 @@ ${lanes.join("\n")} function getExportsOfModule(moduleSymbol) { const links = getSymbolLinks(moduleSymbol); if (!links.resolvedExports) { - const { exports, typeOnlyExportStarMap } = getExportsOfModuleWorker(moduleSymbol); + const { + exports, + typeOnlyExportStarMap + } = getExportsOfModuleWorker(moduleSymbol); links.resolvedExports = exports; links.typeOnlyExportStarMap = typeOnlyExportStarMap; } 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); @@ -49333,11 +46516,11 @@ ${lanes.join("\n")} function getExportsOfModuleWorker(moduleSymbol) { const visitedSymbols = []; let typeOnlyExportStarMap; - const nonTypeOnlyNames = /* @__PURE__ */ new Set(); + const nonTypeOnlyNames = /* @__PURE__ */new Set(); moduleSymbol = resolveExternalModuleSymbol(moduleSymbol); const exports = visit(moduleSymbol) || emptySymbols; if (typeOnlyExportStarMap) { - nonTypeOnlyNames.forEach((name) => typeOnlyExportStarMap.delete(name)); + nonTypeOnlyNames.forEach(name => typeOnlyExportStarMap.delete(name)); } return { exports, @@ -49354,42 +46537,30 @@ ${lanes.join("\n")} const exportStars = symbol.exports.get("__export" /* ExportStar */); if (exportStars) { const nestedSymbols = createSymbolTable(); - const lookupTable = /* @__PURE__ */ new Map(); + const lookupTable = /* @__PURE__ */new Map(); if (exportStars.declarations) { for (const node of exportStars.declarations) { const resolvedModule = resolveExternalModuleName(node, node.moduleSpecifier); const exportedSymbols = visit(resolvedModule, node, isTypeOnly || node.isTypeOnly); - extendExportSymbols( - nestedSymbols, - exportedSymbols, - lookupTable, - node - ); + extendExportSymbols(nestedSymbols, exportedSymbols, lookupTable, node); } } - lookupTable.forEach(({ exportsWithDuplicate }, id) => { + lookupTable.forEach(({ + exportsWithDuplicate + }, id) => { if (id === "export=" || !(exportsWithDuplicate && exportsWithDuplicate.length) || symbols.has(id)) { return; } for (const node of exportsWithDuplicate) { - diagnostics.add(createDiagnosticForNode( - node, - Diagnostics.Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambiguity, - lookupTable.get(id).specifierText, - unescapeLeadingUnderscores(id) - )); + diagnostics.add(createDiagnosticForNode(node, Diagnostics.Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambiguity, lookupTable.get(id).specifierText, unescapeLeadingUnderscores(id))); } }); extendExportSymbols(symbols, nestedSymbols); } if (exportStar == null ? void 0 : exportStar.isTypeOnly) { - typeOnlyExportStarMap ?? (typeOnlyExportStarMap = /* @__PURE__ */ new Map()); - symbols.forEach( - (_, escapedName) => typeOnlyExportStarMap.set( - escapedName, - exportStar - ) - ); + var _typeOnlyExportStarMa; + (_typeOnlyExportStarMa = typeOnlyExportStarMap) !== null && _typeOnlyExportStarMa !== void 0 ? _typeOnlyExportStarMa : typeOnlyExportStarMap = /* @__PURE__ */new Map(); + symbols.forEach((_, escapedName) => typeOnlyExportStarMap.set(escapedName, exportStar)); } return symbols; } @@ -49417,23 +46588,16 @@ ${lanes.join("\n")} } if (containingFile && containingFile.imports) { for (const importRef of containingFile.imports) { - if (nodeIsSynthesized(importRef)) - continue; - const resolvedModule = resolveExternalModuleName( - enclosingDeclaration, - importRef, - /*ignoreErrors*/ - true - ); - if (!resolvedModule) - continue; + if (nodeIsSynthesized(importRef)) continue; + const resolvedModule = resolveExternalModuleName(enclosingDeclaration, importRef, /*ignoreErrors*/ + true); + if (!resolvedModule) continue; const ref = getAliasForSymbolInContainer(resolvedModule, symbol); - if (!ref) - continue; + if (!ref) continue; results = append(results, resolvedModule); } if (length(results)) { - (links.extendedContainersByFile || (links.extendedContainersByFile = /* @__PURE__ */ new Map())).set(id, results); + (links.extendedContainersByFile || (links.extendedContainersByFile = /* @__PURE__ */new Map())).set(id, results); return results; } } @@ -49442,12 +46606,10 @@ ${lanes.join("\n")} } 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; @@ -49458,17 +46620,12 @@ ${lanes.join("\n")} const additionalContainers = mapDefined(container.declarations, fileSymbolIfFileSymbolExportEqualsContainer); const reexportContainers = enclosingDeclaration && getAlternativeContainingModules(symbol, enclosingDeclaration); const objectLiteralContainer = getVariableDeclarationOfObjectLiteral(container, meaning); - if (enclosingDeclaration && container.flags & getQualifiedLeftMeaning(meaning) && getAccessibleSymbolChain( - container, - enclosingDeclaration, - 1920 /* Namespace */, - /*useOnlyExternalAliasing*/ - false - )) { + if (enclosingDeclaration && container.flags & getQualifiedLeftMeaning(meaning) && getAccessibleSymbolChain(container, enclosingDeclaration, 1920 /* Namespace */, /*useOnlyExternalAliasing*/ + false)) { return append(concatenate(concatenate([container], additionalContainers), reexportContainers), objectLiteralContainer); } - const firstVariableMatch = !(container.flags & getQualifiedLeftMeaning(meaning)) && container.flags & 788968 /* Type */ && getDeclaredTypeOfSymbol(container).flags & 524288 /* Object */ && meaning === 111551 /* Value */ ? forEachSymbolTableInScope(enclosingDeclaration, (t) => { - return forEachEntry(t, (s) => { + const firstVariableMatch = !(container.flags & getQualifiedLeftMeaning(meaning)) && container.flags & 788968 /* Type */ && getDeclaredTypeOfSymbol(container).flags & 524288 /* Object */ && meaning === 111551 /* Value */ ? forEachSymbolTableInScope(enclosingDeclaration, t => { + return forEachEntry(t, s => { if (s.flags & getQualifiedLeftMeaning(meaning) && getTypeOfSymbol(s) === getDeclaredTypeOfSymbol(container)) { return s; } @@ -49479,7 +46636,7 @@ ${lanes.join("\n")} res = addRange(res, reexportContainers); return res; } - const candidates = mapDefined(symbol.declarations, (d) => { + const candidates = mapDefined(symbol.declarations, d => { if (!isAmbientModule(d) && d.parent) { if (hasNonGlobalAugmentationExternalModuleSymbol(d.parent)) { return getSymbolOfDeclaration(d.parent); @@ -49499,7 +46656,7 @@ ${lanes.join("\n")} if (!length(candidates)) { return void 0; } - return mapDefined(candidates, (candidate) => getAliasForSymbolInContainer(candidate, symbol) ? candidate : void 0); + return mapDefined(candidates, candidate => getAliasForSymbolInContainer(candidate, symbol) ? candidate : void 0); function fileSymbolIfFileSymbolExportEqualsContainer(d) { return container && getFileSymbolIfFileSymbolExportEqualsContainer(d, container); } @@ -49530,7 +46687,7 @@ ${lanes.join("\n")} if (quick && getSymbolIfSameReference(quick, symbol)) { return quick; } - return forEachEntry(exports, (exported) => { + return forEachEntry(exports, exported => { if (getSymbolIfSameReference(exported, symbol)) { return exported; } @@ -49547,6 +46704,7 @@ ${lanes.join("\n")} function symbolIsValue(symbol, includeTypeOnlyMembers) { return !!(symbol.flags & 111551 /* Value */ || symbol.flags & 2097152 /* Alias */ && getSymbolFlags(symbol, !includeTypeOnlyMembers) & 111551 /* Value */); } + function findConstructorDeclaration(node) { const members = node.members; for (const member of members) { @@ -49580,7 +46738,7 @@ ${lanes.join("\n")} return type; } function checkIntrinsicName(name, debug) { - const key = `${name},${debug ?? ""}`; + const key = `${name},${debug !== null && debug !== void 0 ? debug : ""}`; if (seenIntrinsicNames.has(key)) { Debug.fail(`Duplicate intrinsic type name ${name}${debug ? ` (${debug})` : ""}; you may need to pass a name to createIntrinsicType.`); } @@ -49605,6 +46763,7 @@ ${lanes.join("\n")} function isReservedMemberName(name) { return name.charCodeAt(0) === 95 /* _ */ && name.charCodeAt(1) === 95 /* _ */ && name.charCodeAt(2) !== 95 /* _ */ && name.charCodeAt(2) !== 64 /* at */ && name.charCodeAt(2) !== 35 /* hash */; } + function getNamedMembers(members) { let result; members.forEach((symbol, id) => { @@ -49629,28 +46788,18 @@ ${lanes.join("\n")} 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; - const constructSignatures = filter(type.constructSignatures, (signature) => !(signature.flags & 4 /* Abstract */)); - if (type.constructSignatures === constructSignatures) - return type; - const typeCopy = createAnonymousType( - type.symbol, - type.members, - type.callSignatures, - some(constructSignatures) ? constructSignatures : emptyArray, - type.indexInfos - ); + 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; + const typeCopy = createAnonymousType(type.symbol, type.members, type.callSignatures, some(constructSignatures) ? constructSignatures : emptyArray, type.indexInfos); type.objectTypeWithoutAbstractConstructSignatures = typeCopy; typeCopy.objectTypeWithoutAbstractConstructSignatures = typeCopy; return typeCopy; @@ -49659,14 +46808,9 @@ ${lanes.join("\n")} let result; for (let location = enclosingDeclaration; location; location = location.parent) { if (canHaveLocals(location) && location.locals && !isGlobalSourceFile(location)) { - if (result = callback( - location.locals, - /*ignoreQualification*/ - void 0, - /*isLocalNameLookup*/ - true, - location - )) { + if (result = callback(location.locals, /*ignoreQualification*/ + void 0, /*isLocalNameLookup*/ + true, location)) { return result; } } @@ -49677,14 +46821,9 @@ ${lanes.join("\n")} } case 267 /* ModuleDeclaration */: const sym = getSymbolOfDeclaration(location); - if (result = callback( - (sym == null ? void 0 : sym.exports) || emptySymbols, - /*ignoreQualification*/ - void 0, - /*isLocalNameLookup*/ - true, - location - )) { + if (result = callback((sym == null ? void 0 : sym.exports) || emptySymbols, /*ignoreQualification*/ + void 0, /*isLocalNameLookup*/ + true, location)) { return result; } break; @@ -49697,36 +46836,28 @@ ${lanes.join("\n")} (table || (table = createSymbolTable())).set(key, memberSymbol); } }); - if (table && (result = callback( - table, - /*ignoreQualification*/ - void 0, - /*isLocalNameLookup*/ - false, - location - ))) { + if (table && (result = callback(table, /*ignoreQualification*/ + void 0, /*isLocalNameLookup*/ + false, location))) { return result; } break; } } - return callback( - globals, - /*ignoreQualification*/ - void 0, - /*isLocalNameLookup*/ - true - ); + return callback(globals, /*ignoreQualification*/ + void 0, /*isLocalNameLookup*/ + true); } function getQualifiedLeftMeaning(rightMeaning) { return rightMeaning === 111551 /* Value */ ? 111551 /* Value */ : 1920 /* Namespace */; } - function getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, useOnlyExternalAliasing, visitedSymbolTablesMap = /* @__PURE__ */ new Map()) { + + function getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, useOnlyExternalAliasing, visitedSymbolTablesMap = /* @__PURE__ */new Map()) { if (!(symbol && !isPropertyOrMethodDeclarationSymbol(symbol))) { return void 0; } const links = getSymbolLinks(symbol); - const cache = links.accessibleChainCache || (links.accessibleChainCache = /* @__PURE__ */ new Map()); + const cache = links.accessibleChainCache || (links.accessibleChainCache = /* @__PURE__ */new Map()); const firstRelevantLocation = forEachSymbolTableInScope(enclosingDeclaration, (_, __, ___, node) => node); const key = `${useOnlyExternalAliasing ? 0 : 1}|${firstRelevantLocation && getNodeId(firstRelevantLocation)}|${meaning}`; if (cache.has(key)) { @@ -49749,25 +46880,23 @@ ${lanes.join("\n")} return result2; } function canQualifySymbol(symbolFromSymbolTable, meaning2) { - return !needsQualification(symbolFromSymbolTable, enclosingDeclaration, meaning2) || // If symbol needs qualification, make sure that parent is accessible, if it is then this symbol is accessible too + return !needsQualification(symbolFromSymbolTable, enclosingDeclaration, meaning2) || + // If symbol needs qualification, make sure that parent is accessible, if it is then this symbol is accessible too !!getAccessibleSymbolChain(symbolFromSymbolTable.parent, enclosingDeclaration, getQualifiedLeftMeaning(meaning2), useOnlyExternalAliasing, visitedSymbolTablesMap); } function isAccessible(symbolFromSymbolTable, resolvedAliasSymbol, ignoreQualification) { - return (symbol === (resolvedAliasSymbol || symbolFromSymbolTable) || getMergedSymbol(symbol) === getMergedSymbol(resolvedAliasSymbol || symbolFromSymbolTable)) && // if the symbolFromSymbolTable is not external module (it could be if it was determined as ambient external module and would be in globals table) + return (symbol === (resolvedAliasSymbol || symbolFromSymbolTable) || getMergedSymbol(symbol) === getMergedSymbol(resolvedAliasSymbol || symbolFromSymbolTable)) && + // if the symbolFromSymbolTable is not external module (it could be if it was determined as ambient external module and would be in globals table) // and if symbolFromSymbolTable or alias resolution matches the symbol, // check the symbol can be qualified, it is only then this symbol is accessible !some(symbolFromSymbolTable.declarations, hasNonGlobalAugmentationExternalModuleSymbol) && (ignoreQualification || canQualifySymbol(getMergedSymbol(symbolFromSymbolTable), meaning)); } function trySymbolTable(symbols, ignoreQualification, isLocalNameLookup) { - if (isAccessible( - symbols.get(symbol.escapedName), - /*resolvedAliasSymbol*/ - void 0, - ignoreQualification - )) { + if (isAccessible(symbols.get(symbol.escapedName), /*resolvedAliasSymbol*/ + void 0, ignoreQualification)) { return [symbol]; } - const result2 = forEachEntry(symbols, (symbolFromSymbolTable) => { + const result2 = forEachEntry(symbols, symbolFromSymbolTable => { if (symbolFromSymbolTable.flags & 2097152 /* Alias */ && symbolFromSymbolTable.escapedName !== "export=" /* ExportEquals */ && symbolFromSymbolTable.escapedName !== "default" /* Default */ && !(isUMDExportSymbol(symbolFromSymbolTable) && enclosingDeclaration && isExternalModule(getSourceFileOfNode(enclosingDeclaration))) && (!useOnlyExternalAliasing || some(symbolFromSymbolTable.declarations, isExternalModuleImportEqualsDeclaration)) && (isLocalNameLookup ? !some(symbolFromSymbolTable.declarations, isNamespaceReexportDeclaration) : true) && (ignoreQualification || !getDeclarationOfKind(symbolFromSymbolTable, 281 /* ExportSpecifier */))) { const resolvedImportedSymbol = resolveAlias(symbolFromSymbolTable); const candidate = getCandidateListForSymbol(symbolFromSymbolTable, resolvedImportedSymbol, ignoreQualification); @@ -49776,12 +46905,8 @@ ${lanes.join("\n")} } } if (symbolFromSymbolTable.escapedName === symbol.escapedName && symbolFromSymbolTable.exportSymbol) { - if (isAccessible( - getMergedSymbol(symbolFromSymbolTable.exportSymbol), - /*resolvedAliasSymbol*/ - void 0, - ignoreQualification - )) { + if (isAccessible(getMergedSymbol(symbolFromSymbolTable.exportSymbol), /*resolvedAliasSymbol*/ + void 0, ignoreQualification)) { return [symbol]; } } @@ -49793,11 +46918,8 @@ ${lanes.join("\n")} return [symbolFromSymbolTable]; } const candidateTable = getExportsOfSymbol(resolvedImportedSymbol); - const accessibleSymbolsFromExports = candidateTable && getAccessibleSymbolChainFromSymbolTable( - candidateTable, - /*ignoreQualification*/ - true - ); + const accessibleSymbolsFromExports = candidateTable && getAccessibleSymbolChainFromSymbolTable(candidateTable, /*ignoreQualification*/ + true); if (accessibleSymbolsFromExports && canQualifySymbol(symbolFromSymbolTable, getQualifiedLeftMeaning(meaning))) { return [symbolFromSymbolTable].concat(accessibleSymbolsFromExports); } @@ -49805,7 +46927,7 @@ ${lanes.join("\n")} } function needsQualification(symbol, enclosingDeclaration, meaning) { let qualify = false; - forEachSymbolTableInScope(enclosingDeclaration, (symbolTable) => { + forEachSymbolTableInScope(enclosingDeclaration, symbolTable => { let symbolFromSymbolTable = getMergedSymbol(symbolTable.get(symbol.escapedName)); if (!symbolFromSymbolTable) { return false; @@ -49842,54 +46964,33 @@ ${lanes.join("\n")} return false; } function isTypeSymbolAccessible(typeSymbol, enclosingDeclaration) { - const access = isSymbolAccessibleWorker( - typeSymbol, - enclosingDeclaration, - 788968 /* Type */, - /*shouldComputeAliasesToMakeVisible*/ - false, - /*allowModules*/ - true - ); + const access = isSymbolAccessibleWorker(typeSymbol, enclosingDeclaration, 788968 /* Type */, /*shouldComputeAliasesToMakeVisible*/ + false, /*allowModules*/ + true); return access.accessibility === 0 /* Accessible */; } + function isValueSymbolAccessible(typeSymbol, enclosingDeclaration) { - const access = isSymbolAccessibleWorker( - typeSymbol, - enclosingDeclaration, - 111551 /* Value */, - /*shouldComputeAliasesToMakeVisible*/ - false, - /*allowModules*/ - true - ); + const access = isSymbolAccessibleWorker(typeSymbol, enclosingDeclaration, 111551 /* Value */, /*shouldComputeAliasesToMakeVisible*/ + false, /*allowModules*/ + true); return access.accessibility === 0 /* Accessible */; } + function isSymbolAccessibleByFlags(typeSymbol, enclosingDeclaration, flags) { - const access = isSymbolAccessibleWorker( - typeSymbol, - enclosingDeclaration, - flags, - /*shouldComputeAliasesToMakeVisible*/ - false, - /*allowModules*/ - false - ); + const access = isSymbolAccessibleWorker(typeSymbol, enclosingDeclaration, flags, /*shouldComputeAliasesToMakeVisible*/ + false, /*allowModules*/ + false); 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) { - const accessibleSymbolChain = getAccessibleSymbolChain( - symbol, - enclosingDeclaration, - meaning, - /*useOnlyExternalAliasing*/ - false - ); + const accessibleSymbolChain = getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, /*useOnlyExternalAliasing*/ + false); if (accessibleSymbolChain) { hadAccessibleChain = symbol; const hasAccessibleDeclarations = hasVisibleDeclarations(accessibleSymbolChain[0], shouldComputeAliasesToMakeVisible); @@ -49908,6 +47009,7 @@ ${lanes.join("\n")} }; } } + const containers = getContainersOfSymbol(symbol, enclosingDeclaration, meaning); const parentResult = isAnySymbolAccessible(containers, enclosingDeclaration, initialSymbol, initialSymbol === symbol ? getQualifiedLeftMeaning(meaning) : meaning, shouldComputeAliasesToMakeVisible, allowModules); if (parentResult) { @@ -49919,6 +47021,7 @@ ${lanes.join("\n")} accessibility: 0 /* Accessible */ }; } + if (hadAccessibleChain) { return { accessibility: 1 /* NotAccessible */, @@ -49928,14 +47031,8 @@ ${lanes.join("\n")} } } function isSymbolAccessible(symbol, enclosingDeclaration, meaning, shouldComputeAliasesToMakeVisible) { - return isSymbolAccessibleWorker( - symbol, - enclosingDeclaration, - meaning, - shouldComputeAliasesToMakeVisible, - /*allowModules*/ - true - ); + return isSymbolAccessibleWorker(symbol, enclosingDeclaration, meaning, shouldComputeAliasesToMakeVisible, /*allowModules*/ + true); } function isSymbolAccessibleWorker(symbol, enclosingDeclaration, meaning, shouldComputeAliasesToMakeVisible, allowModules) { if (symbol && enclosingDeclaration) { @@ -49960,8 +47057,11 @@ ${lanes.join("\n")} errorSymbolName: symbolToString(symbol, enclosingDeclaration, meaning) }; } - return { accessibility: 0 /* Accessible */ }; + return { + accessibility: 0 /* Accessible */ + }; } + function getExternalModuleContainer(declaration) { const node = findAncestor(declaration, hasExternalModuleSymbol); return node && getSymbolOfDeclaration(node); @@ -49974,18 +47074,23 @@ ${lanes.join("\n")} } function hasVisibleDeclarations(symbol, shouldComputeAliasToMakeVisible) { let aliasesToMakeVisible; - if (!every(filter(symbol.declarations, (d) => d.kind !== 80 /* Identifier */), getIsDeclarationVisible)) { + if (!every(filter(symbol.declarations, d => d.kind !== 80 /* Identifier */), getIsDeclarationVisible)) { return void 0; } - return { accessibility: 0 /* Accessible */, aliasesToMakeVisible }; + return { + accessibility: 0 /* Accessible */, + aliasesToMakeVisible + }; function getIsDeclarationVisible(declaration) { var _a, _b; if (!isDeclarationVisible(declaration)) { const anyImportSyntax = getAnyImportSyntax(declaration); - if (anyImportSyntax && !hasSyntacticModifier(anyImportSyntax, 32 /* Export */) && // import clause without export + if (anyImportSyntax && !hasSyntacticModifier(anyImportSyntax, 32 /* Export */) && + // import clause without export isDeclarationVisible(anyImportSyntax.parent)) { return addVisibleAlias(declaration, anyImportSyntax); - } else if (isVariableDeclaration(declaration) && isVariableStatement(declaration.parent.parent) && !hasSyntacticModifier(declaration.parent.parent, 32 /* Export */) && // unexported variable statement + } else if (isVariableDeclaration(declaration) && isVariableStatement(declaration.parent.parent) && !hasSyntacticModifier(declaration.parent.parent, 32 /* Export */) && + // unexported variable statement isDeclarationVisible(declaration.parent.parent.parent)) { return addVisibleAlias(declaration, declaration.parent.parent); } else if (isLateVisibilityPaintedStatement(declaration) && !hasSyntacticModifier(declaration, 32 /* Export */) && isDeclarationVisible(declaration.parent)) { @@ -50025,41 +47130,29 @@ ${lanes.join("\n")} } else { meaning = 788968 /* Type */; } + const firstIdentifier = getFirstIdentifier(entityName); - const symbol = resolveName( - enclosingDeclaration, - firstIdentifier.escapedText, - meaning, - /*nameNotFoundMessage*/ - void 0, - /*nameArg*/ - void 0, - /*isUse*/ - false - ); + const symbol = resolveName(enclosingDeclaration, firstIdentifier.escapedText, meaning, /*nameNotFoundMessage*/ + void 0, /*nameArg*/ + void 0, /*isUse*/ + false); if (symbol && symbol.flags & 262144 /* TypeParameter */ && meaning & 788968 /* Type */) { - return { accessibility: 0 /* Accessible */ }; + return { + accessibility: 0 /* Accessible */ + }; } - if (!symbol && isThisIdentifier(firstIdentifier) && isSymbolAccessible( - getSymbolOfDeclaration(getThisContainer( - firstIdentifier, - /*includeArrowFunctions*/ - false, - /*includeClassComputedPropertyName*/ - false - )), - firstIdentifier, - meaning, - /*shouldComputeAliasesToMakeVisible*/ - false - ).accessibility === 0 /* Accessible */) { - return { accessibility: 0 /* Accessible */ }; + + if (!symbol && isThisIdentifier(firstIdentifier) && isSymbolAccessible(getSymbolOfDeclaration(getThisContainer(firstIdentifier, /*includeArrowFunctions*/ + false, /*includeClassComputedPropertyName*/ + false)), firstIdentifier, meaning, /*shouldComputeAliasesToMakeVisible*/ + false).accessibility === 0 /* Accessible */) { + return { + accessibility: 0 /* Accessible */ + }; } - return symbol && hasVisibleDeclarations( - symbol, - /*shouldComputeAliasToMakeVisible*/ - true - ) || { + + return symbol && hasVisibleDeclarations(symbol, /*shouldComputeAliasToMakeVisible*/ + true) || { accessibility: 1 /* NotAccessible */, errorSymbolName: getTextOfNode(firstIdentifier), errorNode: firstIdentifier @@ -50070,31 +47163,31 @@ ${lanes.join("\n")} if (flags & 2 /* UseOnlyExternalAliasing */) { nodeFlags |= 128 /* UseOnlyExternalAliasing */; } + if (flags & 1 /* WriteTypeParametersOrArguments */) { nodeFlags |= 512 /* WriteTypeParametersInQualifiedName */; } + if (flags & 8 /* UseAliasDefinedOutsideCurrentScope */) { nodeFlags |= 16384 /* UseAliasDefinedOutsideCurrentScope */; } + if (flags & 32 /* DoNotIncludeSymbolChain */) { nodeFlags |= 134217728 /* DoNotIncludeSymbolChain */; } + if (flags & 16 /* WriteComputedProps */) { nodeFlags |= 1073741824 /* WriteComputedProps */; } + const builder = flags & 4 /* AllowAnyNodeKind */ ? nodeBuilder.symbolToNode : nodeBuilder.symbolToEntityName; return writer ? symbolToStringWorker(writer).getText() : usingSingleLineStringWriter(symbolToStringWorker); function symbolToStringWorker(writer2) { const entity = builder(symbol, meaning, enclosingDeclaration, nodeFlags); const printer = (enclosingDeclaration == null ? void 0 : enclosingDeclaration.kind) === 312 /* SourceFile */ ? createPrinterWithRemoveCommentsNeverAsciiEscape() : createPrinterWithRemoveComments(); const sourceFile = enclosingDeclaration && getSourceFileOfNode(enclosingDeclaration); - printer.writeNode( - 4 /* Unspecified */, - entity, - /*sourceFile*/ - sourceFile, - writer2 - ); + printer.writeNode(4 /* Unspecified */, entity, /*sourceFile*/ + sourceFile, writer2); return writer2; } } @@ -50107,33 +47200,23 @@ ${lanes.join("\n")} } else { sigOutput = kind === 1 /* Construct */ ? 180 /* ConstructSignature */ : 179 /* CallSignature */; } + const sig = nodeBuilder.signatureToSignatureDeclaration(signature, sigOutput, enclosingDeclaration, toNodeBuilderFlags(flags) | 70221824 /* IgnoreErrors */ | 512 /* WriteTypeParametersInQualifiedName */); const printer = createPrinterWithRemoveCommentsOmitTrailingSemicolon(); const sourceFile = enclosingDeclaration && getSourceFileOfNode(enclosingDeclaration); - printer.writeNode( - 4 /* Unspecified */, - sig, - /*sourceFile*/ - sourceFile, - getTrailingSemicolonDeferringWriter(writer2) - ); + printer.writeNode(4 /* Unspecified */, sig, /*sourceFile*/ + sourceFile, getTrailingSemicolonDeferringWriter(writer2)); return writer2; } } 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( - 4 /* Unspecified */, - typeNode, - /*sourceFile*/ - sourceFile, - writer - ); + printer.writeNode(4 /* Unspecified */, typeNode, /*sourceFile*/ + sourceFile, writer); const result = writer.getText(); const maxLength2 = noTruncation ? noTruncationMaximumTruncationLength * 2 : defaultMaximumTruncationLength * 2; if (maxLength2 && result && result.length >= maxLength2) { @@ -50151,52 +47234,41 @@ ${lanes.join("\n")} return [leftStr, rightStr]; } function getTypeNameForErrorDisplay(type) { - return typeToString( - type, - /*enclosingDeclaration*/ - void 0, - 64 /* UseFullyQualifiedType */ - ); + return typeToString(type, /*enclosingDeclaration*/ + void 0, 64 /* UseFullyQualifiedType */); } + function symbolValueDeclarationIsContextSensitive(symbol) { return symbol && !!symbol.valueDeclaration && isExpression(symbol.valueDeclaration) && !isContextSensitive(symbol.valueDeclaration); } function toNodeBuilderFlags(flags = 0 /* None */) { return flags & 848330091 /* NodeBuilderFlagsMask */; } + function isClassInstanceSide(type) { return !!type.symbol && !!(type.symbol.flags & 32 /* Class */) && (type === getDeclaredTypeOfClassOrInterface(type.symbol) || !!(type.flags & 524288 /* Object */) && !!(getObjectFlags(type) & 16777216 /* IsClassInstanceClone */)); } + function createNodeBuilder() { return { - typeToTypeNode: (type, enclosingDeclaration, flags, tracker) => withContext(enclosingDeclaration, flags, tracker, (context) => typeToTypeNodeHelper(type, context)), - indexInfoToIndexSignatureDeclaration: (indexInfo, enclosingDeclaration, flags, tracker) => withContext(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( - 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, bundled) => withContext(enclosingDeclaration, flags, tracker, (context) => symbolTableToDeclarationStatements(symbolTable, context, bundled)), - symbolToNode: (symbol, meaning, enclosingDeclaration, flags, tracker) => withContext(enclosingDeclaration, flags, tracker, (context) => symbolToNode(symbol, context, meaning)) + typeToTypeNode: (type, enclosingDeclaration, flags, tracker) => withContext(enclosingDeclaration, flags, tracker, context => typeToTypeNodeHelper(type, context)), + indexInfoToIndexSignatureDeclaration: (indexInfo, enclosingDeclaration, flags, tracker) => withContext(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(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, bundled) => withContext(enclosingDeclaration, flags, tracker, context => symbolTableToDeclarationStatements(symbolTable, context, bundled)), + symbolToNode: (symbol, meaning, enclosingDeclaration, flags, tracker) => withContext(enclosingDeclaration, flags, tracker, context => symbolToNode(symbol, context, meaning)) }; function symbolToNode(symbol, context, meaning) { 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 */)) { @@ -50229,8 +47301,7 @@ ${lanes.join("\n")} 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) { @@ -50254,6 +47325,7 @@ ${lanes.join("\n")} context.approximateLength += 3; return factory.createKeywordTypeNode(133 /* AnyKeyword */); } + if (!(context.flags & 536870912 /* NoTypeReduction */)) { type = getReducedType(type); } @@ -50267,25 +47339,31 @@ ${lanes.join("\n")} context.approximateLength += 3; return factory.createKeywordTypeNode(type === intrinsicMarkerType ? 141 /* IntrinsicKeyword */ : 133 /* AnyKeyword */); } + if (type.flags & 2 /* Unknown */) { return factory.createKeywordTypeNode(159 /* UnknownKeyword */); } + if (type.flags & 4 /* String */) { context.approximateLength += 6; return factory.createKeywordTypeNode(154 /* StringKeyword */); } + if (type.flags & 8 /* Number */) { context.approximateLength += 6; return factory.createKeywordTypeNode(150 /* NumberKeyword */); } + if (type.flags & 64 /* BigInt */) { context.approximateLength += 6; return factory.createKeywordTypeNode(163 /* BigIntKeyword */); } + if (type.flags & 16 /* Boolean */ && !type.aliasSymbol) { context.approximateLength += 7; return factory.createKeywordTypeNode(136 /* BooleanKeyword */); } + if (type.flags & 1056 /* EnumLike */) { if (type.symbol.flags & 8 /* EnumMember */) { const parentSymbol = getParentOfSymbol(type.symbol); @@ -50295,14 +47373,8 @@ ${lanes.join("\n")} } const memberName = symbolName(type.symbol); if (isIdentifierText(memberName, 0 /* ES3 */)) { - return appendReferenceToType( - parentName, - factory.createTypeReferenceNode( - memberName, - /*typeArguments*/ - void 0 - ) - ); + return appendReferenceToType(parentName, factory.createTypeReferenceNode(memberName, /*typeArguments*/ + void 0)); } if (isImportTypeNode(parentName)) { parentName.isTypeOf = true; @@ -50315,10 +47387,12 @@ ${lanes.join("\n")} } return symbolToTypeNode(type.symbol, context, 788968 /* Type */); } + if (type.flags & 128 /* StringLiteral */) { context.approximateLength += type.value.length + 2; return factory.createLiteralTypeNode(setEmitFlags(factory.createStringLiteral(type.value, !!(context.flags & 268435456 /* UseSingleQuotesForStringLiteralType */)), 16777216 /* NoAsciiEscaping */)); } + if (type.flags & 256 /* NumberLiteral */) { const value = type.value; context.approximateLength += ("" + value).length; @@ -50338,6 +47412,7 @@ ${lanes.join("\n")} context.approximateLength += 6; return symbolToTypeNode(type.symbol, context, 111551 /* Value */); } + if (context.tracker.reportInaccessibleUniqueSymbolError) { context.tracker.reportInaccessibleUniqueSymbolError(); } @@ -50345,14 +47420,17 @@ ${lanes.join("\n")} context.approximateLength += 13; return factory.createTypeOperatorNode(158 /* UniqueKeyword */, factory.createKeywordTypeNode(155 /* SymbolKeyword */)); } + if (type.flags & 16384 /* Void */) { context.approximateLength += 4; return factory.createKeywordTypeNode(116 /* VoidKeyword */); } + if (type.flags & 32768 /* Undefined */) { context.approximateLength += 9; return factory.createKeywordTypeNode(157 /* UndefinedKeyword */); } + if (type.flags & 65536 /* Null */) { context.approximateLength += 4; return factory.createLiteralTypeNode(factory.createNull()); @@ -50361,14 +47439,17 @@ ${lanes.join("\n")} context.approximateLength += 5; return factory.createKeywordTypeNode(146 /* NeverKeyword */); } + if (type.flags & 4096 /* ESSymbol */) { context.approximateLength += 6; return factory.createKeywordTypeNode(155 /* SymbolKeyword */); } + if (type.flags & 67108864 /* NonPrimitive */) { context.approximateLength += 6; return factory.createKeywordTypeNode(151 /* ObjectKeyword */); } + if (isThisTypeParameter(type)) { if (context.flags & 4194304 /* InObjectTypeLiteral */) { if (!context.encounteredError && !(context.flags & 32768 /* AllowThisInObjectLiteral */)) { @@ -50381,8 +47462,7 @@ ${lanes.join("\n")} } 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]); } @@ -50399,11 +47479,8 @@ ${lanes.join("\n")} let constraintNode; const constraint = getConstraintOfTypeParameter(type); if (constraint) { - const inferredConstraint = getInferredTypeParameterConstraint( - type, - /*omitTypeReferences*/ - true - ); + const inferredConstraint = getInferredTypeParameterConstraint(type, /*omitTypeReferences*/ + true); if (!(inferredConstraint && isTypeIdenticalTo(constraint, inferredConstraint))) { context.approximateLength += 9; constraintNode = constraint && typeToTypeNodeHelper(constraint, context); @@ -50414,21 +47491,16 @@ ${lanes.join("\n")} if (context.flags & 4 /* GenerateNamesForShadowedTypeParams */ && type.flags & 262144 /* TypeParameter */ && !isTypeSymbolAccessible(type.symbol, context.enclosingDeclaration)) { const name2 = typeParameterToName(type, context); context.approximateLength += idText(name2).length; - return factory.createTypeReferenceNode( - factory.createIdentifier(idText(name2)), - /*typeArguments*/ - void 0 - ); + return factory.createTypeReferenceNode(factory.createIdentifier(idText(name2)), /*typeArguments*/ + void 0); } if (type.symbol) { return symbolToTypeNode(type.symbol, context, 788968 /* Type */); } + const name = (type === markerSuperTypeForCheck || type === markerSubTypeForCheck) && varianceTypeParameter && varianceTypeParameter.symbol ? (type === markerSubTypeForCheck ? "sub-" : "super-") + symbolName(varianceTypeParameter.symbol) : "?"; - return factory.createTypeReferenceNode( - factory.createIdentifier(name), - /*typeArguments*/ - void 0 - ); + return factory.createTypeReferenceNode(factory.createIdentifier(name), /*typeArguments*/ + void 0); } if (type.flags & 1048576 /* Union */ && type.origin) { type = type.origin; @@ -50438,12 +47510,8 @@ ${lanes.join("\n")} if (length(types) === 1) { return typeToTypeNodeHelper(types[0], context); } - const typeNodes = mapToTypeNodes( - types, - context, - /*isBareList*/ - true - ); + const typeNodes = mapToTypeNodes(types, context, /*isBareList*/ + true); if (typeNodes && typeNodes.length > 0) { return type.flags & 1048576 /* Union */ ? factory.createUnionTypeNode(typeNodes) : factory.createIntersectionTypeNode(typeNodes); } else { @@ -50467,12 +47535,7 @@ ${lanes.join("\n")} const texts = type.texts; const types = type.types; const templateHead = factory.createTemplateHead(texts[0]); - const templateSpans = factory.createNodeArray( - map(types, (t, i) => factory.createTemplateLiteralTypeSpan( - typeToTypeNodeHelper(t, context), - (i < types.length - 1 ? factory.createTemplateMiddle : factory.createTemplateTail)(texts[i + 1]) - )) - ); + const templateSpans = factory.createNodeArray(map(types, (t, i) => factory.createTemplateLiteralTypeSpan(typeToTypeNodeHelper(t, context), (i < types.length - 1 ? factory.createTemplateMiddle : factory.createTemplateTail)(texts[i + 1])))); context.approximateLength += 2; return factory.createTemplateLiteralType(templateHead, templateSpans); } @@ -50487,7 +47550,7 @@ ${lanes.join("\n")} return factory.createIndexedAccessTypeNode(objectTypeNode, indexTypeNode); } if (type.flags & 16777216 /* Conditional */) { - return visitAndTransformType(type, (type2) => conditionalTypeToTypeNode(type2)); + return visitAndTransformType(type, type2 => conditionalTypeToTypeNode(type2)); } if (type.flags & 33554432 /* Substitution */) { return typeToTypeNodeHelper(type.baseType, context); @@ -50508,22 +47571,10 @@ ${lanes.join("\n")} context.inferTypeParameters = saveInferTypeParameters2; const trueTypeNode2 = typeToTypeNodeOrCircularityElision(instantiateType(getTypeFromTypeNode(type2.root.node.trueType), newMapper)); const falseTypeNode2 = typeToTypeNodeOrCircularityElision(instantiateType(getTypeFromTypeNode(type2.root.node.falseType), newMapper)); - return factory.createConditionalTypeNode( - checkTypeNode, - factory.createInferTypeNode(factory.createTypeParameterDeclaration( - /*modifiers*/ - void 0, - factory.cloneNode(newTypeVariable.typeName) - )), - factory.createConditionalTypeNode( - factory.createTypeReferenceNode(factory.cloneNode(name)), - typeToTypeNodeHelper(type2.checkType, context), - factory.createConditionalTypeNode(newTypeVariable, extendsTypeNode2, trueTypeNode2, falseTypeNode2), - factory.createKeywordTypeNode(146 /* NeverKeyword */) - ), - factory.createKeywordTypeNode(146 /* NeverKeyword */) - ); + return factory.createConditionalTypeNode(checkTypeNode, factory.createInferTypeNode(factory.createTypeParameterDeclaration( /*modifiers*/ + void 0, factory.cloneNode(newTypeVariable.typeName))), factory.createConditionalTypeNode(factory.createTypeReferenceNode(factory.cloneNode(name)), typeToTypeNodeHelper(type2.checkType, context), factory.createConditionalTypeNode(newTypeVariable, extendsTypeNode2, trueTypeNode2, falseTypeNode2), factory.createKeywordTypeNode(146 /* NeverKeyword */)), factory.createKeywordTypeNode(146 /* NeverKeyword */)); } + const saveInferTypeParameters = context.inferTypeParameters; context.inferTypeParameters = type2.root.inferTypeParameters; const extendsTypeNode = typeToTypeNodeHelper(type2.extendsType, context); @@ -50542,7 +47593,7 @@ ${lanes.join("\n")} } return createElidedInformationPlaceholder(context); } - return visitAndTransformType(type2, (type3) => typeToTypeNodeHelper(type3, context)); + return visitAndTransformType(type2, type3 => typeToTypeNodeHelper(type3, context)); } return typeToTypeNodeHelper(type2, context); } @@ -50578,43 +47629,19 @@ ${lanes.join("\n")} const typeParameterNode = typeParameterToDeclarationWithConstraint(getTypeParameterFromMappedType(type2), context, appropriateConstraintTypeNode); const nameTypeNode = type2.declaration.nameType ? typeToTypeNodeHelper(getNameTypeFromMappedType(type2), context) : void 0; const templateTypeNode = typeToTypeNodeHelper(removeMissingType(getTemplateTypeFromMappedType(type2), !!(getMappedTypeModifiers(type2) & 4 /* IncludeOptional */)), context); - const mappedTypeNode = factory.createMappedTypeNode( - readonlyToken, - typeParameterNode, - nameTypeNode, - questionToken, - templateTypeNode, - /*members*/ - void 0 - ); + const mappedTypeNode = factory.createMappedTypeNode(readonlyToken, typeParameterNode, nameTypeNode, questionToken, templateTypeNode, /*members*/ + void 0); 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); - return factory.createConditionalTypeNode( - typeToTypeNodeHelper(getModifiersTypeFromMappedType(type2), context), - factory.createInferTypeNode(factory.createTypeParameterDeclaration( - /*modifiers*/ - void 0, - factory.cloneNode(newTypeVariable.typeName), - originalConstraint.flags & 2 /* Unknown */ ? void 0 : typeToTypeNodeHelper(originalConstraint, context) - )), - result, - factory.createKeywordTypeNode(146 /* NeverKeyword */) - ); + return factory.createConditionalTypeNode(typeToTypeNodeHelper(getModifiersTypeFromMappedType(type2), context), factory.createInferTypeNode(factory.createTypeParameterDeclaration( /*modifiers*/ + void 0, factory.cloneNode(newTypeVariable.typeName), originalConstraint.flags & 2 /* Unknown */ ? void 0 : typeToTypeNodeHelper(originalConstraint, context))), result, factory.createKeywordTypeNode(146 /* NeverKeyword */)); } else if (needsModifierPreservingWrapper) { - return factory.createConditionalTypeNode( - typeToTypeNodeHelper(getConstraintTypeFromMappedType(type2), context), - factory.createInferTypeNode(factory.createTypeParameterDeclaration( - /*modifiers*/ - void 0, - factory.cloneNode(newTypeVariable.typeName), - factory.createTypeOperatorNode(143 /* KeyOfKeyword */, typeToTypeNodeHelper(getModifiersTypeFromMappedType(type2), context)) - )), - result, - factory.createKeywordTypeNode(146 /* NeverKeyword */) - ); + return factory.createConditionalTypeNode(typeToTypeNodeHelper(getConstraintTypeFromMappedType(type2), context), factory.createInferTypeNode(factory.createTypeParameterDeclaration( /*modifiers*/ + void 0, factory.cloneNode(newTypeVariable.typeName), factory.createTypeOperatorNode(143 /* KeyOfKeyword */, typeToTypeNodeHelper(getModifiersTypeFromMappedType(type2), context)))), result, factory.createKeywordTypeNode(146 /* NeverKeyword */)); } + return result; } function createAnonymousTypeNode(type2) { @@ -50625,13 +47652,8 @@ ${lanes.join("\n")} const isInstanceType = isClassInstanceSide(type2) ? 788968 /* Type */ : 111551 /* Value */; if (isJSConstructor(symbol.valueDeclaration)) { return symbolToTypeNode(symbol, context, isInstanceType); - } else if (symbol.flags & 32 /* Class */ && !getBaseTypeVariableOfClass(symbol) && !(symbol.valueDeclaration && isClassLike(symbol.valueDeclaration) && context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */ && (!isClassDeclaration(symbol.valueDeclaration) || isSymbolAccessible( - symbol, - context.enclosingDeclaration, - isInstanceType, - /*shouldComputeAliasesToMakeVisible*/ - false - ).accessibility !== 0 /* Accessible */)) || symbol.flags & (384 /* Enum */ | 512 /* ValueModule */) || shouldWriteTypeOfFunctionSymbol()) { + } else if (symbol.flags & 32 /* Class */ && !getBaseTypeVariableOfClass(symbol) && !(symbol.valueDeclaration && isClassLike(symbol.valueDeclaration) && context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */ && (!isClassDeclaration(symbol.valueDeclaration) || isSymbolAccessible(symbol, context.enclosingDeclaration, isInstanceType, /*shouldComputeAliasesToMakeVisible*/ + false).accessibility !== 0 /* Accessible */)) || symbol.flags & (384 /* Enum */ | 512 /* ValueModule */) || shouldWriteTypeOfFunctionSymbol()) { return symbolToTypeNode(symbol, context, isInstanceType); } else if ((_a2 = context.visitedTypes) == null ? void 0 : _a2.has(typeId)) { const typeAlias = getTypeAliasForTypeLiteral(type2); @@ -50662,13 +47684,16 @@ ${lanes.join("\n")} } function shouldWriteTypeOfFunctionSymbol() { var _a3; - const isStaticMethodSymbol = !!(symbol.flags & 8192 /* Method */) && // typeof static method - some(symbol.declarations, (declaration) => isStatic(declaration)); - const isNonLocalFunctionSymbol = !!(symbol.flags & 16 /* Function */) && (symbol.parent || // is exported function symbol - forEach(symbol.declarations, (declaration) => declaration.parent.kind === 312 /* SourceFile */ || declaration.parent.kind === 268 /* ModuleBlock */)); + const isStaticMethodSymbol = !!(symbol.flags & 8192 /* Method */) && + // typeof static method + some(symbol.declarations, declaration => isStatic(declaration)); + const isNonLocalFunctionSymbol = !!(symbol.flags & 16 /* Function */) && (symbol.parent || + // is exported function symbol + forEach(symbol.declarations, declaration => declaration.parent.kind === 312 /* SourceFile */ || declaration.parent.kind === 268 /* ModuleBlock */)); if (isStaticMethodSymbol || isNonLocalFunctionSymbol) { - return (!!(context.flags & 4096 /* UseTypeOfFunction */) || ((_a3 = context.visitedTypes) == null ? void 0 : _a3.has(typeId))) && // it is type of the symbol uses itself recursively - (!(context.flags & 8 /* UseStructuralFallback */) || isValueSymbolAccessible(symbol, context.enclosingDeclaration)); + return (!!(context.flags & 4096 /* UseTypeOfFunction */) || ((_a3 = context.visitedTypes) == null ? void 0 : _a3.has(typeId))) && ( + // it is type of the symbol uses itself recursively + !(context.flags & 8 /* UseStructuralFallback */) || isValueSymbolAccessible(symbol, context.enclosingDeclaration)); } } } @@ -50678,25 +47703,19 @@ ${lanes.join("\n")} const isConstructorObject = getObjectFlags(type2) & 16 /* Anonymous */ && type2.symbol && type2.symbol.flags & 32 /* Class */; const id = getObjectFlags(type2) & 4 /* Reference */ && type2.node ? "N" + getNodeId(type2.node) : type2.flags & 16777216 /* Conditional */ ? "N" + getNodeId(type2.root.node) : type2.symbol ? (isConstructorObject ? "+" : "") + getSymbolId(type2.symbol) : void 0; if (!context.visitedTypes) { - context.visitedTypes = /* @__PURE__ */ new Set(); + context.visitedTypes = /* @__PURE__ */new Set(); } if (id && !context.symbolDepth) { - context.symbolDepth = /* @__PURE__ */ new Map(); + context.symbolDepth = /* @__PURE__ */new Map(); } const links = context.enclosingDeclaration && getNodeLinks(context.enclosingDeclaration); const key = `${getTypeId(type2)}|${context.flags}`; if (links) { - links.serializedTypes || (links.serializedTypes = /* @__PURE__ */ new Map()); + links.serializedTypes || (links.serializedTypes = /* @__PURE__ */new Map()); } const cachedResult = (_a2 = links == null ? void 0 : links.serializedTypes) == null ? void 0 : _a2.get(key); if (cachedResult) { - (_b2 = cachedResult.trackedSymbols) == null ? void 0 : _b2.forEach( - ([symbol, enclosingDeclaration, meaning]) => context.tracker.trackSymbol( - symbol, - enclosingDeclaration, - meaning - ) - ); + (_b2 = cachedResult.trackedSymbols) == null ? void 0 : _b2.forEach(([symbol, enclosingDeclaration, meaning]) => context.tracker.trackSymbol(symbol, enclosingDeclaration, meaning)); if (cachedResult.truncating) { context.truncating = true; } @@ -50739,11 +47758,8 @@ ${lanes.join("\n")} } function deepCloneOrReuseNodes(nodes, visitor, test, start, count) { if (nodes && nodes.length === 0) { - return setTextRange(factory.createNodeArray( - /*elements*/ - void 0, - nodes.hasTrailingComma - ), nodes); + return setTextRange(factory.createNodeArray( /*elements*/ + void 0, nodes.hasTrailingComma), nodes); } return visitNodes2(nodes, visitor, test, start, count); } @@ -50756,11 +47772,10 @@ ${lanes.join("\n")} if (!resolved.properties.length && !resolved.indexInfos.length) { if (!resolved.callSignatures.length && !resolved.constructSignatures.length) { context.approximateLength += 2; - return setEmitFlags(factory.createTypeLiteralNode( - /*members*/ - void 0 - ), 1 /* SingleLine */); + return setEmitFlags(factory.createTypeLiteralNode( /*members*/ + void 0), 1 /* SingleLine */); } + if (resolved.callSignatures.length === 1 && !resolved.constructSignatures.length) { const signature = resolved.callSignatures[0]; const signatureNode = signatureToSignatureDeclarationHelper(signature, 184 /* FunctionType */, context); @@ -50772,12 +47787,13 @@ ${lanes.join("\n")} return signatureNode; } } - const abstractSignatures = filter(resolved.constructSignatures, (signature) => !!(signature.flags & 4 /* Abstract */)); + const abstractSignatures = filter(resolved.constructSignatures, signature => !!(signature.flags & 4 /* Abstract */)); if (some(abstractSignatures)) { const types = map(abstractSignatures, getOrCreateTypeFromSignature); - const typeElementCount = resolved.callSignatures.length + (resolved.constructSignatures.length - abstractSignatures.length) + resolved.indexInfos.length + // exclude `prototype` when writing a class expression as a type literal, as per + const typeElementCount = resolved.callSignatures.length + (resolved.constructSignatures.length - abstractSignatures.length) + resolved.indexInfos.length + ( + // exclude `prototype` when writing a class expression as a type literal, as per // the logic in `createTypeNodesFromResolvedType`. - (context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */ ? countWhere(resolved.properties, (p) => !(p.flags & 4194304 /* Prototype */)) : length(resolved.properties)); + context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */ ? countWhere(resolved.properties, p => !(p.flags & 4194304 /* Prototype */)) : length(resolved.properties)); if (typeElementCount) { types.push(getResolvedTypeWithoutAbstractConstructSignatures(resolved)); } @@ -50808,17 +47824,14 @@ ${lanes.join("\n")} const arity = getTypeReferenceArity(type2); const tupleConstituentNodes = mapToTypeNodes(typeArguments.slice(0, arity), context); if (tupleConstituentNodes) { - const { labeledElementDeclarations } = type2.target; + const { + labeledElementDeclarations + } = type2.target; for (let i = 0; i < tupleConstituentNodes.length; i++) { const flags = type2.target.elementFlags[i]; const labeledElementDeclaration = labeledElementDeclarations == null ? void 0 : labeledElementDeclarations[i]; if (labeledElementDeclaration) { - tupleConstituentNodes[i] = factory.createNamedTupleMember( - flags & 12 /* Variable */ ? factory.createToken(26 /* DotDotDotToken */) : void 0, - factory.createIdentifier(unescapeLeadingUnderscores(getTupleElementLabel(labeledElementDeclaration))), - flags & 2 /* Optional */ ? factory.createToken(58 /* QuestionToken */) : void 0, - flags & 4 /* Rest */ ? factory.createArrayTypeNode(tupleConstituentNodes[i]) : tupleConstituentNodes[i] - ); + tupleConstituentNodes[i] = factory.createNamedTupleMember(flags & 12 /* Variable */ ? factory.createToken(26 /* DotDotDotToken */) : void 0, factory.createIdentifier(unescapeLeadingUnderscores(getTupleElementLabel(labeledElementDeclaration))), flags & 2 /* Optional */ ? factory.createToken(58 /* QuestionToken */) : void 0, flags & 4 /* Rest */ ? factory.createArrayTypeNode(tupleConstituentNodes[i]) : tupleConstituentNodes[i]); } else { tupleConstituentNodes[i] = flags & 12 /* Variable */ ? factory.createRestTypeNode(flags & 4 /* Rest */ ? factory.createArrayTypeNode(tupleConstituentNodes[i]) : tupleConstituentNodes[i]) : flags & 2 /* Optional */ ? factory.createOptionalTypeNode(tupleConstituentNodes[i]) : tupleConstituentNodes[i]; } @@ -50889,14 +47902,7 @@ ${lanes.join("\n")} for (const id of ids) { qualifier = qualifier ? factory.createQualifiedName(qualifier, id) : id; } - return factory.updateImportTypeNode( - root, - root.argument, - root.attributes, - qualifier, - typeArguments, - root.isTypeOf - ); + return factory.updateImportTypeNode(root, root.argument, root.attributes, qualifier, typeArguments, root.isTypeOf); } else { let typeArguments = root.typeArguments; let typeName = root.typeName; @@ -50914,11 +47920,7 @@ ${lanes.join("\n")} for (const id of ids) { typeName = factory.createQualifiedName(typeName, id); } - return factory.updateTypeReferenceNode( - root, - typeName, - typeArguments - ); + return factory.updateTypeReferenceNode(root, typeName, typeArguments); } } function getAccessStack(ref) { @@ -50933,23 +47935,17 @@ ${lanes.join("\n")} } function createTypeNodesFromResolvedType(resolvedType) { if (checkTruncationLength(context)) { - return [factory.createPropertySignature( - /*modifiers*/ - void 0, - "...", - /*questionToken*/ - void 0, - /*type*/ - void 0 - )]; + return [factory.createPropertySignature( /*modifiers*/ + void 0, "...", /*questionToken*/ + void 0, /*type*/ + void 0)]; } const typeElements = []; for (const signature of resolvedType.callSignatures) { typeElements.push(signatureToSignatureDeclarationHelper(signature, 179 /* CallSignature */, context)); } for (const signature of resolvedType.constructSignatures) { - if (signature.flags & 4 /* Abstract */) - continue; + if (signature.flags & 4 /* Abstract */) continue; typeElements.push(signatureToSignatureDeclarationHelper(signature, 180 /* ConstructSignature */, context)); } for (const info of resolvedType.indexInfos) { @@ -50971,15 +47967,10 @@ ${lanes.join("\n")} } } if (checkTruncationLength(context) && i + 2 < properties.length - 1) { - typeElements.push(factory.createPropertySignature( - /*modifiers*/ - void 0, - `... ${properties.length - i} more ...`, - /*questionToken*/ - void 0, - /*type*/ - void 0 - )); + typeElements.push(factory.createPropertySignature( /*modifiers*/ + void 0, `... ${properties.length - i} more ...`, /*questionToken*/ + void 0, /*type*/ + void 0)); addPropertyToElementList(properties[properties.length - 1], context, typeElements); break; } @@ -50991,18 +47982,17 @@ ${lanes.join("\n")} function createElidedInformationPlaceholder(context) { context.approximateLength += 3; if (!(context.flags & 1 /* NoTruncation */)) { - return factory.createTypeReferenceNode( - factory.createIdentifier("..."), - /*typeArguments*/ - void 0 - ); + return factory.createTypeReferenceNode(factory.createIdentifier("..."), /*typeArguments*/ + void 0); } return factory.createKeywordTypeNode(133 /* AnyKeyword */); } + function shouldUsePlaceholderForProperty(propertySymbol, context) { var _a; return !!(getCheckFlags(propertySymbol) & 8192 /* ReverseMapped */) && (contains(context.reverseMappedStack, propertySymbol) || ((_a = context.reverseMappedStack) == null ? void 0 : _a[0]) && !(getObjectFlags(last(context.reverseMappedStack).links.propertyType) & 16 /* Anonymous */)); } + function addPropertyToElementList(propertySymbol, context, typeElements) { var _a; const propertyIsReverseMapped = !!(getCheckFlags(propertySymbol) & 8192 /* ReverseMapped */); @@ -51035,28 +48025,25 @@ ${lanes.join("\n")} if (propertyType !== writeType && !isErrorType(propertyType) && !isErrorType(writeType)) { const getterDeclaration = getDeclarationOfKind(propertySymbol, 177 /* GetAccessor */); const getterSignature = getSignatureFromDeclaration(getterDeclaration); - typeElements.push( - setCommentRange( - signatureToSignatureDeclarationHelper(getterSignature, 177 /* GetAccessor */, context, { name: propertyName }), - getterDeclaration - ) - ); + typeElements.push(setCommentRange(signatureToSignatureDeclarationHelper(getterSignature, 177 /* GetAccessor */, context, { + name: propertyName + }), getterDeclaration)); const setterDeclaration = getDeclarationOfKind(propertySymbol, 178 /* SetAccessor */); const setterSignature = getSignatureFromDeclaration(setterDeclaration); - typeElements.push( - setCommentRange( - signatureToSignatureDeclarationHelper(setterSignature, 178 /* SetAccessor */, context, { name: propertyName }), - setterDeclaration - ) - ); + typeElements.push(setCommentRange(signatureToSignatureDeclarationHelper(setterSignature, 178 /* SetAccessor */, context, { + name: propertyName + }), setterDeclaration)); return; } } const optionalToken = propertySymbol.flags & 16777216 /* Optional */ ? factory.createToken(58 /* QuestionToken */) : void 0; if (propertySymbol.flags & (16 /* Function */ | 8192 /* Method */) && !getPropertiesOfObjectType(propertyType).length && !isReadonlySymbol(propertySymbol)) { - const signatures = getSignaturesOfType(filterType(propertyType, (t) => !(t.flags & 32768 /* Undefined */)), 0 /* Call */); + const signatures = getSignaturesOfType(filterType(propertyType, t => !(t.flags & 32768 /* Undefined */)), 0 /* Call */); for (const signature of signatures) { - const methodDeclaration = signatureToSignatureDeclarationHelper(signature, 173 /* MethodSignature */, context, { name: propertyName, questionToken: optionalToken }); + const methodDeclaration = signatureToSignatureDeclarationHelper(signature, 173 /* MethodSignature */, context, { + name: propertyName, + questionToken: optionalToken + }); typeElements.push(preserveCommentsOn(methodDeclaration)); } if (signatures.length || !optionalToken) { @@ -51080,20 +48067,21 @@ ${lanes.join("\n")} if (modifiers) { context.approximateLength += 9; } - const propertySignature = factory.createPropertySignature( - modifiers, - propertyName, - optionalToken, - propertyTypeNode - ); + const propertySignature = factory.createPropertySignature(modifiers, propertyName, optionalToken, propertyTypeNode); typeElements.push(preserveCommentsOn(propertySignature)); function preserveCommentsOn(node) { var _a2; - const jsdocPropertyTag = (_a2 = propertySymbol.declarations) == null ? void 0 : _a2.find((d) => d.kind === 355 /* JSDocPropertyTag */); + const jsdocPropertyTag = (_a2 = propertySymbol.declarations) == null ? void 0 : _a2.find(d => d.kind === 355 /* JSDocPropertyTag */); if (jsdocPropertyTag) { const commentText = getTextOfJSDocComment(jsdocPropertyTag.comment); if (commentText) { - setSyntheticLeadingComments(node, [{ kind: 3 /* MultiLineCommentTrivia */, text: "*\n * " + commentText.replace(/\n/g, "\n * ") + "\n ", pos: -1, end: -1, hasTrailingNewLine: true }]); + 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); @@ -51105,21 +48093,11 @@ ${lanes.join("\n")} if (some(types)) { if (checkTruncationLength(context)) { if (!isBareList) { - return [factory.createTypeReferenceNode( - "...", - /*typeArguments*/ - void 0 - )]; + return [factory.createTypeReferenceNode("...", /*typeArguments*/ + void 0)]; } else if (types.length > 2) { - return [ - typeToTypeNodeHelper(types[0], context), - factory.createTypeReferenceNode( - `... ${types.length - 2} more ...`, - /*typeArguments*/ - void 0 - ), - typeToTypeNodeHelper(types[types.length - 1], context) - ]; + return [typeToTypeNodeHelper(types[0], context), factory.createTypeReferenceNode(`... ${types.length - 2} more ...`, /*typeArguments*/ + void 0), typeToTypeNodeHelper(types[types.length - 1], context)]; } } const mayHaveNameCollisions = !(context.flags & 64 /* UseFullyQualifiedType */); @@ -51129,11 +48107,8 @@ ${lanes.join("\n")} for (const type of types) { i++; if (checkTruncationLength(context) && i + 2 < types.length - 1) { - result.push(factory.createTypeReferenceNode( - `... ${types.length - i} more ...`, - /*typeArguments*/ - void 0 - )); + result.push(factory.createTypeReferenceNode(`... ${types.length - i} more ...`, /*typeArguments*/ + void 0)); const typeNode2 = typeToTypeNodeHelper(types[types.length - 1], context); if (typeNode2) { result.push(typeNode2); @@ -51152,7 +48127,7 @@ ${lanes.join("\n")} if (seenNames) { const saveContextFlags = context.flags; context.flags |= 64 /* UseFullyQualifiedType */; - seenNames.forEach((types2) => { + seenNames.forEach(types2 => { if (!arrayIsHomogeneous(types2, ([a], [b]) => typesAreSameReference(a, b))) { for (const [type, resultIndex] of types2) { result[resultIndex] = typeToTypeNodeHelper(type, context); @@ -51170,18 +48145,11 @@ ${lanes.join("\n")} function indexInfoToIndexSignatureDeclarationHelper(indexInfo, context, typeNode) { const name = getNameFromIndexInfo(indexInfo) || "x"; const indexerTypeNode = typeToTypeNodeHelper(indexInfo.keyType, context); - const indexingParameter = factory.createParameterDeclaration( - /*modifiers*/ - void 0, - /*dotDotDotToken*/ - void 0, - name, - /*questionToken*/ - void 0, - indexerTypeNode, - /*initializer*/ - void 0 - ); + const indexingParameter = factory.createParameterDeclaration( /*modifiers*/ + void 0, /*dotDotDotToken*/ + void 0, name, /*questionToken*/ + void 0, indexerTypeNode, /*initializer*/ + void 0); if (!typeNode) { typeNode = typeToTypeNodeHelper(indexInfo.type || anyType, context); } @@ -51189,35 +48157,29 @@ ${lanes.join("\n")} context.encounteredError = true; } context.approximateLength += name.length + 4; - return factory.createIndexSignature( - indexInfo.isReadonly ? [factory.createToken(148 /* ReadonlyKeyword */)] : void 0, - [indexingParameter], - typeNode - ); + return factory.createIndexSignature(indexInfo.isReadonly ? [factory.createToken(148 /* ReadonlyKeyword */)] : void 0, [indexingParameter], typeNode); } function signatureToSignatureDeclarationHelper(signature, kind, context, options) { + var _ref13, _ref14, _ref15, _ref16, _returnTypeNode, _returnTypeNode2; var _a; const suppressAny = context.flags & 256 /* SuppressAnyReturnType */; - if (suppressAny) - context.flags &= ~256 /* SuppressAnyReturnType */; + if (suppressAny) 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)); + typeArguments = signature.target.typeParameters.map(parameter => typeToTypeNodeHelper(instantiateType(parameter, signature.mapper), context)); } else { - typeParameters = signature.typeParameters && signature.typeParameters.map((parameter) => typeParameterToDeclaration(parameter, context)); + typeParameters = signature.typeParameters && signature.typeParameters.map(parameter => typeParameterToDeclaration(parameter, context)); } - const expandedParams = getExpandedParameters( - signature, - /*skipUnionExpanding*/ - true - )[0]; + const expandedParams = getExpandedParameters(signature, /*skipUnionExpanding*/ + true)[0]; let cleanup; if (context.enclosingDeclaration && signature.declaration && signature.declaration !== context.enclosingDeclaration && !isInJSFile(signature.declaration) && some(expandedParams)) { + var _ref12; const existingFakeScope = getNodeLinks(context.enclosingDeclaration).fakeScopeForSignatureDeclaration ? context.enclosingDeclaration : void 0; Debug.assertOptionalNode(existingFakeScope, isBlock); - const locals = (existingFakeScope == null ? void 0 : existingFakeScope.locals) ?? createSymbolTable(); + const locals = (_ref12 = existingFakeScope == null ? void 0 : existingFakeScope.locals) !== null && _ref12 !== void 0 ? _ref12 : createSymbolTable(); let newLocals; for (const param of expandedParams) { if (!locals.has(param.escapedName)) { @@ -51226,8 +48188,8 @@ ${lanes.join("\n")} } } if (newLocals) { - let removeNewLocals2 = function() { - forEach(newLocals, (s) => locals.delete(s)); + let removeNewLocals2 = function () { + forEach(newLocals, s => locals.delete(s)); }; var removeNewLocals = removeNewLocals2; if (existingFakeScope) { @@ -51246,7 +48208,7 @@ ${lanes.join("\n")} } } } - const parameters = (some(expandedParams, (p) => p !== expandedParams[expandedParams.length - 1] && !!(getCheckFlags(p) & 32768 /* RestParameter */)) ? signature.parameters : expandedParams).map((parameter) => symbolToParameterDeclaration(parameter, context, kind === 176 /* Constructor */, options == null ? void 0 : options.privateSymbolVisitor, options == null ? void 0 : options.bundledImports)); + const parameters = (some(expandedParams, p => p !== expandedParams[expandedParams.length - 1] && !!(getCheckFlags(p) & 32768 /* RestParameter */)) ? signature.parameters : expandedParams).map(parameter => symbolToParameterDeclaration(parameter, context, kind === 176 /* Constructor */, options == null ? void 0 : options.privateSymbolVisitor, options == null ? void 0 : options.bundledImports)); const thisParameter = context.flags & 33554432 /* OmitThisParameter */ ? void 0 : tryGetThisParameterDeclaration(signature, context); if (thisParameter) { parameters.unshift(thisParameter); @@ -51266,85 +48228,32 @@ ${lanes.join("\n")} returnTypeNode = factory.createKeywordTypeNode(133 /* AnyKeyword */); } } + let modifiers = options == null ? void 0 : options.modifiers; if (kind === 185 /* ConstructorType */ && signature.flags & 4 /* Abstract */) { const flags = modifiersToFlags(modifiers); modifiers = factory.createModifiersFromModifierFlags(flags | 64 /* Abstract */); } - const node = kind === 179 /* CallSignature */ ? factory.createCallSignature(typeParameters, parameters, returnTypeNode) : kind === 180 /* ConstructSignature */ ? factory.createConstructSignature(typeParameters, parameters, returnTypeNode) : kind === 173 /* MethodSignature */ ? factory.createMethodSignature(modifiers, (options == null ? void 0 : options.name) ?? factory.createIdentifier(""), options == null ? void 0 : options.questionToken, typeParameters, parameters, returnTypeNode) : kind === 174 /* MethodDeclaration */ ? factory.createMethodDeclaration( - modifiers, - /*asteriskToken*/ - void 0, - (options == null ? void 0 : options.name) ?? factory.createIdentifier(""), - /*questionToken*/ - void 0, - typeParameters, - parameters, - returnTypeNode, - /*body*/ - void 0 - ) : kind === 176 /* Constructor */ ? factory.createConstructorDeclaration( - modifiers, - parameters, - /*body*/ - void 0 - ) : kind === 177 /* GetAccessor */ ? factory.createGetAccessorDeclaration( - modifiers, - (options == null ? void 0 : options.name) ?? factory.createIdentifier(""), - parameters, - returnTypeNode, - /*body*/ - void 0 - ) : kind === 178 /* SetAccessor */ ? factory.createSetAccessorDeclaration( - modifiers, - (options == null ? void 0 : options.name) ?? factory.createIdentifier(""), - parameters, - /*body*/ - void 0 - ) : kind === 181 /* IndexSignature */ ? factory.createIndexSignature(modifiers, parameters, returnTypeNode) : kind === 324 /* JSDocFunctionType */ ? factory.createJSDocFunctionType(parameters, returnTypeNode) : kind === 184 /* FunctionType */ ? factory.createFunctionTypeNode(typeParameters, parameters, returnTypeNode ?? factory.createTypeReferenceNode(factory.createIdentifier(""))) : kind === 185 /* ConstructorType */ ? factory.createConstructorTypeNode(modifiers, typeParameters, parameters, returnTypeNode ?? factory.createTypeReferenceNode(factory.createIdentifier(""))) : kind === 262 /* FunctionDeclaration */ ? factory.createFunctionDeclaration( - modifiers, - /*asteriskToken*/ - void 0, - (options == null ? void 0 : options.name) ? cast(options.name, isIdentifier) : factory.createIdentifier(""), - typeParameters, - parameters, - returnTypeNode, - /*body*/ - void 0 - ) : kind === 218 /* FunctionExpression */ ? factory.createFunctionExpression( - modifiers, - /*asteriskToken*/ - void 0, - (options == null ? void 0 : options.name) ? cast(options.name, isIdentifier) : factory.createIdentifier(""), - typeParameters, - parameters, - returnTypeNode, - factory.createBlock([]) - ) : kind === 219 /* ArrowFunction */ ? factory.createArrowFunction( - modifiers, - typeParameters, - parameters, - returnTypeNode, - /*equalsGreaterThanToken*/ - void 0, - factory.createBlock([]) - ) : Debug.assertNever(kind); + + const node = kind === 179 /* CallSignature */ ? factory.createCallSignature(typeParameters, parameters, returnTypeNode) : kind === 180 /* ConstructSignature */ ? factory.createConstructSignature(typeParameters, parameters, returnTypeNode) : kind === 173 /* MethodSignature */ ? factory.createMethodSignature(modifiers, (_ref13 = options == null ? void 0 : options.name) !== null && _ref13 !== void 0 ? _ref13 : factory.createIdentifier(""), options == null ? void 0 : options.questionToken, typeParameters, parameters, returnTypeNode) : kind === 174 /* MethodDeclaration */ ? factory.createMethodDeclaration(modifiers, /*asteriskToken*/ + void 0, (_ref14 = options == null ? void 0 : options.name) !== null && _ref14 !== void 0 ? _ref14 : factory.createIdentifier(""), /*questionToken*/ + void 0, typeParameters, parameters, returnTypeNode, /*body*/ + void 0) : kind === 176 /* Constructor */ ? factory.createConstructorDeclaration(modifiers, parameters, /*body*/ + void 0) : kind === 177 /* GetAccessor */ ? factory.createGetAccessorDeclaration(modifiers, (_ref15 = options == null ? void 0 : options.name) !== null && _ref15 !== void 0 ? _ref15 : factory.createIdentifier(""), parameters, returnTypeNode, /*body*/ + void 0) : kind === 178 /* SetAccessor */ ? factory.createSetAccessorDeclaration(modifiers, (_ref16 = options == null ? void 0 : options.name) !== null && _ref16 !== void 0 ? _ref16 : factory.createIdentifier(""), parameters, /*body*/ + void 0) : kind === 181 /* IndexSignature */ ? factory.createIndexSignature(modifiers, parameters, returnTypeNode) : kind === 324 /* JSDocFunctionType */ ? factory.createJSDocFunctionType(parameters, returnTypeNode) : kind === 184 /* FunctionType */ ? factory.createFunctionTypeNode(typeParameters, parameters, (_returnTypeNode = returnTypeNode) !== null && _returnTypeNode !== void 0 ? _returnTypeNode : factory.createTypeReferenceNode(factory.createIdentifier(""))) : kind === 185 /* ConstructorType */ ? factory.createConstructorTypeNode(modifiers, typeParameters, parameters, (_returnTypeNode2 = returnTypeNode) !== null && _returnTypeNode2 !== void 0 ? _returnTypeNode2 : factory.createTypeReferenceNode(factory.createIdentifier(""))) : kind === 262 /* FunctionDeclaration */ ? factory.createFunctionDeclaration(modifiers, /*asteriskToken*/ + void 0, (options == null ? void 0 : options.name) ? cast(options.name, isIdentifier) : factory.createIdentifier(""), typeParameters, parameters, returnTypeNode, /*body*/ + void 0) : kind === 218 /* FunctionExpression */ ? factory.createFunctionExpression(modifiers, /*asteriskToken*/ + void 0, (options == null ? void 0 : options.name) ? cast(options.name, isIdentifier) : factory.createIdentifier(""), typeParameters, parameters, returnTypeNode, factory.createBlock([])) : kind === 219 /* ArrowFunction */ ? factory.createArrowFunction(modifiers, typeParameters, parameters, returnTypeNode, /*equalsGreaterThanToken*/ + void 0, factory.createBlock([])) : Debug.assertNever(kind); if (typeArguments) { node.typeArguments = factory.createNodeArray(typeArguments); } if (((_a = signature.declaration) == null ? void 0 : _a.kind) === 330 /* JSDocSignature */ && signature.declaration.parent.kind === 346 /* JSDocOverloadTag */) { - const comment = getTextOfNode( - signature.declaration.parent.parent, - /*includeTrivia*/ - true - ).slice(2, -2).split(/\r\n|\n|\r/).map((line) => line.replace(/^\s+/, " ")).join("\n"); - addSyntheticLeadingComment( - node, - 3 /* MultiLineCommentTrivia */, - comment, - /*hasTrailingNewLine*/ - true - ); + const comment = getTextOfNode(signature.declaration.parent.parent, /*includeTrivia*/ + true).slice(2, -2).split(/\r\n|\n|\r/).map(line => line.replace(/^\s+/, " ")).join("\n"); + addSyntheticLeadingComment(node, 3 /* MultiLineCommentTrivia */, comment, /*hasTrailingNewLine*/ + true); } cleanup == null ? void 0 : cleanup(); return node; @@ -51356,16 +48265,10 @@ ${lanes.join("\n")} if (signature.declaration && isInJSFile(signature.declaration)) { const thisTag = getJSDocThisTag(signature.declaration); if (thisTag && thisTag.typeExpression) { - return factory.createParameterDeclaration( - /*modifiers*/ - void 0, - /*dotDotDotToken*/ - void 0, - "this", - /*questionToken*/ - void 0, - typeToTypeNodeHelper(getTypeFromTypeNode(thisTag.typeExpression), context) - ); + return factory.createParameterDeclaration( /*modifiers*/ + void 0, /*dotDotDotToken*/ + void 0, "this", /*questionToken*/ + void 0, typeToTypeNodeHelper(getTypeFromTypeNode(thisTag.typeExpression), context)); } } } @@ -51392,6 +48295,7 @@ ${lanes.join("\n")} return getDeclarationOfKind(parameterSymbol, 348 /* JSDocParameterTag */); } } + function symbolToParameterDeclaration(parameterSymbol, context, preserveModifierFlags, privateSymbolVisitor, bundledImports) { const parameterDeclaration = getEffectiveParameterDeclaration(parameterSymbol); let parameterType = getTypeOfSymbol(parameterSymbol); @@ -51405,15 +48309,8 @@ ${lanes.join("\n")} const name = parameterToParameterDeclarationName(parameterSymbol, parameterDeclaration, context); const isOptional = parameterDeclaration && isOptionalParameter(parameterDeclaration) || getCheckFlags(parameterSymbol) & 16384 /* OptionalParameter */; const questionToken = isOptional ? factory.createToken(58 /* QuestionToken */) : void 0; - const parameterNode = factory.createParameterDeclaration( - modifiers, - dotDotDotToken, - name, - questionToken, - parameterTypeNode, - /*initializer*/ - void 0 - ); + const parameterNode = factory.createParameterDeclaration(modifiers, dotDotDotToken, name, questionToken, parameterTypeNode, /*initializer*/ + void 0); context.approximateLength += symbolName(parameterSymbol).length + 3; return parameterNode; } @@ -51425,23 +48322,11 @@ ${lanes.join("\n")} if (context.tracker.canTrackSymbol && isComputedPropertyName(node2) && isLateBindableName(node2)) { trackComputedName(node2.expression, context.enclosingDeclaration, context); } - let visited = visitEachChild( - node2, - elideInitializerAndSetEmitFlags, - nullTransformationContext, - /*nodesVisitor*/ - void 0, - elideInitializerAndSetEmitFlags - ); + let visited = visitEachChild(node2, elideInitializerAndSetEmitFlags, nullTransformationContext, /*nodesVisitor*/ + void 0, elideInitializerAndSetEmitFlags); if (isBindingElement(visited)) { - visited = factory.updateBindingElement( - visited, - visited.dotDotDotToken, - visited.propertyName, - visited.name, - /*initializer*/ - void 0 - ); + visited = factory.updateBindingElement(visited, visited.dotDotDotToken, visited.propertyName, visited.name, /*initializer*/ + void 0); } if (!nodeIsSynthesized(visited)) { visited = factory.cloneNode(visited); @@ -51450,25 +48335,19 @@ ${lanes.join("\n")} } } } + function trackComputedName(accessExpression, enclosingDeclaration, context) { - if (!context.tracker.canTrackSymbol) - return; + if (!context.tracker.canTrackSymbol) return; const firstIdentifier = getFirstIdentifier(accessExpression); - const name = resolveName( - firstIdentifier, - firstIdentifier.escapedText, - 111551 /* Value */ | 1048576 /* ExportValue */, - /*nameNotFoundMessage*/ - void 0, - /*nameArg*/ - void 0, - /*isUse*/ - true - ); + const name = resolveName(firstIdentifier, firstIdentifier.escapedText, 111551 /* Value */ | 1048576 /* ExportValue */, /*nameNotFoundMessage*/ + void 0, /*nameArg*/ + void 0, /*isUse*/ + true); if (name) { context.tracker.trackSymbol(name, enclosingDeclaration, 111551 /* Value */); } } + function lookupSymbolChain(symbol, context, meaning, yieldModuleSymbol) { context.tracker.trackSymbol(symbol, context.enclosingDeclaration, meaning); return lookupSymbolChainWorker(symbol, context, meaning, yieldModuleSymbol); @@ -51477,12 +48356,8 @@ ${lanes.join("\n")} let chain; const isTypeParameter = symbol.flags & 262144 /* TypeParameter */; if (!isTypeParameter && (context.enclosingDeclaration || context.flags & 64 /* UseFullyQualifiedType */) && !(context.flags & 134217728 /* DoNotIncludeSymbolChain */)) { - chain = Debug.checkDefined(getSymbolChain( - symbol, - meaning, - /*endOfChain*/ - true - )); + chain = Debug.checkDefined(getSymbolChain(symbol, meaning, /*endOfChain*/ + true)); Debug.assert(chain && chain.length > 0); } else { chain = [symbol]; @@ -51494,19 +48369,13 @@ ${lanes.join("\n")} if (!accessibleSymbolChain || needsQualification(accessibleSymbolChain[0], context.enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning2 : getQualifiedLeftMeaning(meaning2))) { const parents = getContainersOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol2, context.enclosingDeclaration, meaning2); if (length(parents)) { - parentSpecifiers = parents.map( - (symbol3) => some(symbol3.declarations, hasNonGlobalAugmentationExternalModuleSymbol) ? getSpecifierForModuleSymbol(symbol3, context) : void 0 - ); + parentSpecifiers = parents.map(symbol3 => some(symbol3.declarations, hasNonGlobalAugmentationExternalModuleSymbol) ? getSpecifierForModuleSymbol(symbol3, context) : void 0); const indices = parents.map((_, i) => i); indices.sort(sortByBestName); - const sortedParents = indices.map((i) => parents[i]); + const sortedParents = indices.map(i => parents[i]); for (const parent2 of sortedParents) { - const parentChain = getSymbolChain( - parent2, - getQualifiedLeftMeaning(meaning2), - /*endOfChain*/ - false - ); + const parentChain = getSymbolChain(parent2, getQualifiedLeftMeaning(meaning2), /*endOfChain*/ + false); if (parentChain) { if (parent2.exports && parent2.exports.get("export=" /* ExportEquals */) && getSymbolIfSameReference(parent2.exports.get("export=" /* ExportEquals */), symbol2)) { accessibleSymbolChain = parentChain; @@ -51522,10 +48391,10 @@ ${lanes.join("\n")} return accessibleSymbolChain; } if ( - // If this is the last part of outputting the symbol, always output. The cases apply only to parent symbols. - endOfChain || // If a parent symbol is an anonymous type, don't write it. - !(symbol2.flags & (2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */)) - ) { + // If this is the last part of outputting the symbol, always output. The cases apply only to parent symbols. + endOfChain || + // If a parent symbol is an anonymous type, don't write it. + !(symbol2.flags & (2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */))) { if (!endOfChain && !yieldModuleSymbol && !!forEach(symbol2.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) { return; } @@ -51552,7 +48421,7 @@ ${lanes.join("\n")} let typeParameterNodes; const targetSymbol = getTargetSymbol(symbol); if (targetSymbol.flags & (32 /* Class */ | 64 /* Interface */ | 524288 /* TypeAlias */)) { - typeParameterNodes = factory.createNodeArray(map(getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol), (tp) => typeParameterToDeclaration(tp, context))); + typeParameterNodes = factory.createNodeArray(map(getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol), tp => typeParameterToDeclaration(tp, context))); } return typeParameterNodes; } @@ -51564,16 +48433,14 @@ ${lanes.join("\n")} if ((_a = context.typeParameterSymbolList) == null ? void 0 : _a.has(symbolId)) { return void 0; } - (context.typeParameterSymbolList || (context.typeParameterSymbolList = /* @__PURE__ */ new Set())).add(symbolId); + (context.typeParameterSymbolList || (context.typeParameterSymbolList = /* @__PURE__ */new Set())).add(symbolId); let typeParameterNodes; if (context.flags & 512 /* WriteTypeParametersInQualifiedName */ && index < chain.length - 1) { const parentSymbol = symbol; const nextSymbol = chain[index + 1]; if (getCheckFlags(nextSymbol) & 1 /* Instantiated */) { - const params = getTypeParametersOfClassOrInterface( - parentSymbol.flags & 2097152 /* Alias */ ? resolveAlias(parentSymbol) : parentSymbol - ); - typeParameterNodes = mapToTypeNodes(map(params, (t) => getMappedType(t, nextSymbol.links.mapper)), context); + const params = getTypeParametersOfClassOrInterface(parentSymbol.flags & 2097152 /* Alias */ ? resolveAlias(parentSymbol) : parentSymbol); + typeParameterNodes = mapToTypeNodes(map(params, t => getMappedType(t, nextSymbol.links.mapper)), context); } else { typeParameterNodes = typeParametersToTypeParameterDeclarations(symbol, context); } @@ -51589,11 +48456,12 @@ ${lanes.join("\n")} function getSpecifierForModuleSymbol(symbol, context, overrideImportMode) { let file = getDeclarationOfKind(symbol, 312 /* SourceFile */); if (!file) { - const equivalentFileSymbol = firstDefined(symbol.declarations, (d) => getFileSymbolIfFileSymbolExportEqualsContainer(d, symbol)); + const equivalentFileSymbol = firstDefined(symbol.declarations, d => getFileSymbolIfFileSymbolExportEqualsContainer(d, symbol)); if (equivalentFileSymbol) { file = getDeclarationOfKind(equivalentFileSymbol, 312 /* SourceFile */); } } + if (file && file.moduleName !== void 0) { return file.moduleName; } @@ -51622,22 +48490,22 @@ ${lanes.join("\n")} const links = getSymbolLinks(symbol); let specifier = links.specifierCache && links.specifierCache.get(cacheKey); if (!specifier) { + var _links$specifierCache; const isBundle2 = !!outFile(compilerOptions); - const { moduleResolverHost } = context.tracker; - const specifierCompilerOptions = isBundle2 ? { ...compilerOptions, baseUrl: moduleResolverHost.getCommonSourceDirectory() } : compilerOptions; - specifier = first(getModuleSpecifiers( - symbol, - checker, - specifierCompilerOptions, - contextFile, - moduleResolverHost, - { - importModuleSpecifierPreference: isBundle2 ? "non-relative" : "project-relative", - importModuleSpecifierEnding: isBundle2 ? "minimal" : resolutionMode === 99 /* ESNext */ ? "js" : void 0 - }, - { overrideImportMode } - )); - links.specifierCache ?? (links.specifierCache = /* @__PURE__ */ new Map()); + const { + moduleResolverHost + } = context.tracker; + const specifierCompilerOptions = isBundle2 ? { + ...compilerOptions, + baseUrl: moduleResolverHost.getCommonSourceDirectory() + } : compilerOptions; + specifier = first(getModuleSpecifiers(symbol, checker, specifierCompilerOptions, contextFile, moduleResolverHost, { + importModuleSpecifierPreference: isBundle2 ? "non-relative" : "project-relative", + importModuleSpecifierEnding: isBundle2 ? "minimal" : resolutionMode === 99 /* ESNext */ ? "js" : void 0 + }, { + overrideImportMode + })); + (_links$specifierCache = links.specifierCache) !== null && _links$specifierCache !== void 0 ? _links$specifierCache : links.specifierCache = /* @__PURE__ */new Map(); links.specifierCache.set(cacheKey, specifier); } return specifier; @@ -51659,14 +48527,7 @@ ${lanes.join("\n")} if (getEmitModuleResolutionKind(compilerOptions) === 3 /* Node16 */ || getEmitModuleResolutionKind(compilerOptions) === 99 /* NodeNext */) { if ((targetFile == null ? void 0 : targetFile.impliedNodeFormat) === 99 /* ESNext */ && targetFile.impliedNodeFormat !== (contextFile == null ? void 0 : contextFile.impliedNodeFormat)) { specifier = getSpecifierForModuleSymbol(chain[0], context, 99 /* ESNext */); - attributes = factory.createImportAttributes( - factory.createNodeArray([ - factory.createImportAttribute( - factory.createStringLiteral("resolution-mode"), - factory.createStringLiteral("import") - ) - ]) - ); + attributes = factory.createImportAttributes(factory.createNodeArray([factory.createImportAttribute(factory.createStringLiteral("resolution-mode"), factory.createStringLiteral("import"))])); } } if (!specifier) { @@ -51680,14 +48541,7 @@ ${lanes.join("\n")} if (specifier.includes("/node_modules/")) { specifier = oldSpecifier; } else { - attributes = factory.createImportAttributes( - factory.createNodeArray([ - factory.createImportAttribute( - factory.createStringLiteral("resolution-mode"), - factory.createStringLiteral(swappedMode === 99 /* ESNext */ ? "import" : "require") - ) - ]) - ); + attributes = factory.createImportAttributes(factory.createNodeArray([factory.createImportAttribute(factory.createStringLiteral("resolution-mode"), factory.createStringLiteral(swappedMode === 99 /* ESNext */ ? "import" : "require"))])); } } if (!attributes) { @@ -51698,17 +48552,13 @@ ${lanes.join("\n")} } } const lit = factory.createLiteralTypeNode(factory.createStringLiteral(specifier)); - if (context.tracker.trackExternalModuleSymbolOfImportTypeNode) - context.tracker.trackExternalModuleSymbolOfImportTypeNode(chain[0]); + if (context.tracker.trackExternalModuleSymbolOfImportTypeNode) context.tracker.trackExternalModuleSymbolOfImportTypeNode(chain[0]); context.approximateLength += specifier.length + 10; if (!nonRootParts || isEntityName(nonRootParts)) { if (nonRootParts) { const lastId = isIdentifier(nonRootParts) ? nonRootParts : nonRootParts.right; - setIdentifierTypeArguments( - lastId, - /*typeArguments*/ - void 0 - ); + setIdentifierTypeArguments(lastId, /*typeArguments*/ + void 0); } return factory.createImportTypeNode(lit, attributes, nonRootParts, typeParameterNodes, isTypeOf); } else { @@ -51726,11 +48576,8 @@ ${lanes.join("\n")} } else { const lastId = isIdentifier(entityName) ? entityName : entityName.right; const lastTypeArgs = getIdentifierTypeArguments(lastId); - setIdentifierTypeArguments( - lastId, - /*typeArguments*/ - void 0 - ); + setIdentifierTypeArguments(lastId, /*typeArguments*/ + void 0); return factory.createTypeReferenceNode(entityName, lastTypeArgs); } function createAccessFromSymbolChain(chain2, index, stopper) { @@ -51775,8 +48622,7 @@ ${lanes.join("\n")} } } 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); @@ -51789,16 +48635,9 @@ ${lanes.join("\n")} } } function typeParameterShadowsNameInScope(escapedName, context, type) { - const result = resolveName( - context.enclosingDeclaration, - escapedName, - 788968 /* Type */, - /*nameNotFoundMessage*/ - void 0, - escapedName, - /*isUse*/ - false - ); + const result = resolveName(context.enclosingDeclaration, escapedName, 788968 /* Type */, /*nameNotFoundMessage*/ + void 0, escapedName, /*isUse*/ + false); if (result) { if (result.flags & 262144 /* TypeParameter */ && result === type.symbol) { return false; @@ -51815,13 +48654,8 @@ ${lanes.join("\n")} return cached; } } - let result = symbolToName( - type.symbol, - context, - 788968 /* Type */, - /*expectsIdentifier*/ - true - ); + let result = symbolToName(type.symbol, context, 788968 /* Type */, /*expectsIdentifier*/ + true); if (!(result.kind & 80 /* Identifier */)) { return factory.createIdentifier("(Missing type parameter)"); } @@ -51838,9 +48672,9 @@ ${lanes.join("\n")} 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(rawtext); + (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(rawtext); } return result; } @@ -51856,13 +48690,14 @@ ${lanes.join("\n")} if (index === 0) { context.flags |= 16777216 /* InInitialEntityName */; } + const symbolName2 = getNameOfSymbolAsWritten(symbol2, context); if (index === 0) { context.flags ^= 16777216 /* InInitialEntityName */; } + const identifier = setEmitFlags(factory.createIdentifier(symbolName2), 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; } @@ -51876,18 +48711,19 @@ ${lanes.join("\n")} if (index === 0) { context.flags |= 16777216 /* InInitialEntityName */; } + let symbolName2 = getNameOfSymbolAsWritten(symbol2, context); if (index === 0) { context.flags ^= 16777216 /* InInitialEntityName */; } + let firstChar = symbolName2.charCodeAt(0); if (isSingleOrDoubleQuote(firstChar) && some(symbol2.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) { return factory.createStringLiteral(getSpecifierForModuleSymbol(symbol2, context)); } if (index === 0 || canUsePropertyAccess(symbolName2, languageVersion)) { const identifier = setEmitFlags(factory.createIdentifier(symbolName2), 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 { @@ -51897,14 +48733,13 @@ ${lanes.join("\n")} } let expression; if (isSingleOrDoubleQuote(firstChar) && !(symbol2.flags & 8 /* EnumMember */)) { - expression = factory.createStringLiteral(stripQuotes(symbolName2).replace(/\\./g, (s) => s.substring(1)), firstChar === 39 /* singleQuote */); + expression = factory.createStringLiteral(stripQuotes(symbolName2).replace(/\\./g, s => s.substring(1)), firstChar === 39 /* singleQuote */); } else if ("" + +symbolName2 === symbolName2) { expression = factory.createNumericLiteral(+symbolName2); } if (!expression) { const identifier = setEmitFlags(factory.createIdentifier(symbolName2), 16777216 /* NoAsciiEscaping */); - if (typeParameterNodes) - setIdentifierTypeArguments(identifier, factory.createNodeArray(typeParameterNodes)); + if (typeParameterNodes) setIdentifierTypeArguments(identifier, factory.createNodeArray(typeParameterNodes)); identifier.symbol = symbol2; expression = identifier; } @@ -51921,19 +48756,18 @@ ${lanes.join("\n")} const type = checkExpression(name.expression); return !!(type.flags & 402653316 /* StringLike */); } + if (isElementAccessExpression(name)) { const type = checkExpression(name.argumentExpression); return !!(type.flags & 402653316 /* StringLike */); } + return isStringLiteral(name); } function isSingleQuotedStringNamed(d) { const name = getNameOfDeclaration(d); - return !!(name && isStringLiteral(name) && (name.singleQuote || !nodeIsSynthesized(name) && startsWith(getTextOfNode( - name, - /*includeTrivia*/ - false - ), "'"))); + return !!(name && isStringLiteral(name) && (name.singleQuote || !nodeIsSynthesized(name) && startsWith(getTextOfNode(name, /*includeTrivia*/ + false), "'"))); } function getPropertyNameNodeForSymbol(symbol, context) { const stringNamed = !!length(symbol.declarations) && every(symbol.declarations, isStringNamed); @@ -51964,8 +48798,11 @@ ${lanes.join("\n")} } } } + function cloneNodeBuilderContext(context) { - const initial = { ...context }; + const initial = { + ...context + }; if (initial.typeParameterNames) { initial.typeParameterNames = new Map(initial.typeParameterNames); } @@ -51979,7 +48816,7 @@ ${lanes.join("\n")} return initial; } function getDeclarationWithTypeAnnotation(symbol, enclosingDeclaration) { - return symbol.declarations && find(symbol.declarations, (s) => !!getEffectiveTypeAnnotationNode(s) && (!enclosingDeclaration || !!findAncestor(s, (n) => n === enclosingDeclaration))); + return symbol.declarations && find(symbol.declarations, s => !!getEffectiveTypeAnnotationNode(s) && (!enclosingDeclaration || !!findAncestor(s, n => n === enclosingDeclaration))); } function existingTypeNodeIsNotReferenceOrIsReferenceWithCompatibleTypeArgumentCount(existing, type) { return !(getObjectFlags(type) & 4 /* Reference */) || !isTypeReferenceNode(existing) || length(existing.typeArguments) >= getMinTypeArgumentCount(type.target.typeParameters); @@ -52001,9 +48838,10 @@ ${lanes.join("\n")} } } const oldFlags = context.flags; - if (type.flags & 8192 /* UniqueESSymbol */ && type.symbol === symbol && (!context.enclosingDeclaration || some(symbol.declarations, (d) => getSourceFileOfNode(d) === getSourceFileOfNode(context.enclosingDeclaration)))) { + if (type.flags & 8192 /* UniqueESSymbol */ && type.symbol === symbol && (!context.enclosingDeclaration || some(symbol.declarations, d => getSourceFileOfNode(d) === getSourceFileOfNode(context.enclosingDeclaration)))) { context.flags |= 1048576 /* AllowUniqueESSymbolType */; } + const result = typeToTypeNodeHelper(type, context); context.flags = oldFlags; return result; @@ -52022,7 +48860,7 @@ ${lanes.join("\n")} if (!isErrorType(type) && context.enclosingDeclaration) { const annotation = signature.declaration && getEffectiveReturnTypeNode(signature.declaration); const enclosingDeclarationIgnoringFakeScope = getEnclosingDeclarationIgnoringFakeScope(context.enclosingDeclaration); - if (!!findAncestor(annotation, (n) => n === enclosingDeclarationIgnoringFakeScope) && annotation) { + if (!!findAncestor(annotation, n => n === enclosingDeclarationIgnoringFakeScope) && annotation) { const annotated = getTypeFromTypeNode(annotation); const thisInstantiated = annotated.flags & 262144 /* TypeParameter */ && annotated.isThisType ? instantiateType(annotated, signature.mapper) : annotated; if (thisInstantiated === type && existingTypeNodeIsNotReferenceOrIsReferenceWithCompatibleTypeArgumentCount(annotation, type)) { @@ -52040,24 +48878,17 @@ ${lanes.join("\n")} const leftmost = getFirstIdentifier(node); if (isInJSFile(node) && (isExportsIdentifier(leftmost) || isModuleExportsAccessExpression(leftmost.parent) || isQualifiedName(leftmost.parent) && isModuleIdentifier(leftmost.parent.left) && isExportsIdentifier(leftmost.parent.right))) { introducesError = true; - return { introducesError, node }; + return { + introducesError, + node + }; } - const sym = resolveEntityName( - leftmost, - 67108863 /* All */, - /*ignoreErrors*/ - true, - /*dontResolveAlias*/ - true - ); + const sym = resolveEntityName(leftmost, 67108863 /* All */, /*ignoreErrors*/ + true, /*dontResolveAlias*/ + true); if (sym) { - if (isSymbolAccessible( - sym, - context.enclosingDeclaration, - 67108863 /* All */, - /*shouldComputeAliasesToMakeVisible*/ - false - ).accessibility !== 0 /* Accessible */) { + if (isSymbolAccessible(sym, context.enclosingDeclaration, 67108863 /* All */, /*shouldComputeAliasesToMakeVisible*/ + false).accessibility !== 0 /* Accessible */) { introducesError = true; } else { context.tracker.trackSymbol(sym, context.enclosingDeclaration, 67108863 /* All */); @@ -52067,10 +48898,17 @@ ${lanes.join("\n")} const type = getDeclaredTypeOfSymbol(sym); const name = sym.flags & 262144 /* TypeParameter */ && !isTypeSymbolAccessible(type.symbol, context.enclosingDeclaration) ? typeParameterToName(type, context) : factory.cloneNode(node); name.symbol = sym; - return { introducesError, node: setEmitFlags(setOriginalNode(name, node), 16777216 /* NoAsciiEscaping */) }; + return { + introducesError, + node: setEmitFlags(setOriginalNode(name, node), 16777216 /* NoAsciiEscaping */) + }; } } - return { introducesError, node }; + + return { + introducesError, + node + }; } function serializeExistingTypeNode(context, existing, includePrivateSymbol, bundled) { if (cancellationToken && cancellationToken.throwIfCancellationRequested) { @@ -52087,15 +48925,18 @@ ${lanes.join("\n")} if (isJSDocAllType(node) || node.kind === 326 /* JSDocNamepathType */) { return factory.createKeywordTypeNode(133 /* AnyKeyword */); } + if (isJSDocUnknownType(node)) { return factory.createKeywordTypeNode(159 /* UnknownKeyword */); } + if (isJSDocNullableType(node)) { return factory.createUnionTypeNode([visitNode(node.type, visitExistingNodeTreeSymbols, isTypeNode), factory.createLiteralTypeNode(factory.createNull())]); } if (isJSDocOptionalType(node)) { return factory.createUnionTypeNode([visitNode(node.type, visitExistingNodeTreeSymbols, isTypeNode), factory.createKeywordTypeNode(157 /* UndefinedKeyword */)]); } + if (isJSDocNonNullableType(node)) { return visitNode(node.type, visitExistingNodeTreeSymbols); } @@ -52103,101 +48944,59 @@ ${lanes.join("\n")} return factory.createArrayTypeNode(visitNode(node.type, visitExistingNodeTreeSymbols, isTypeNode)); } if (isJSDocTypeLiteral(node)) { - return factory.createTypeLiteralNode(map(node.jsDocPropertyTags, (t) => { + 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; - return factory.createPropertySignature( - /*modifiers*/ - void 0, - name, - t.isBracketed || t.typeExpression && isJSDocOptionalType(t.typeExpression.type) ? factory.createToken(58 /* QuestionToken */) : void 0, - overrideTypeNode || t.typeExpression && visitNode(t.typeExpression.type, visitExistingNodeTreeSymbols, isTypeNode) || factory.createKeywordTypeNode(133 /* AnyKeyword */) - ); + return factory.createPropertySignature( /*modifiers*/ + void 0, name, t.isBracketed || t.typeExpression && isJSDocOptionalType(t.typeExpression.type) ? factory.createToken(58 /* QuestionToken */) : void 0, overrideTypeNode || t.typeExpression && visitNode(t.typeExpression.type, visitExistingNodeTreeSymbols, isTypeNode) || factory.createKeywordTypeNode(133 /* AnyKeyword */)); })); } + if (isTypeReferenceNode(node) && isIdentifier(node.typeName) && node.typeName.escapedText === "") { return setOriginalNode(factory.createKeywordTypeNode(133 /* AnyKeyword */), node); } if ((isExpressionWithTypeArguments(node) || isTypeReferenceNode(node)) && isJSDocIndexSignature(node)) { - return factory.createTypeLiteralNode([factory.createIndexSignature( - /*modifiers*/ - void 0, - [factory.createParameterDeclaration( - /*modifiers*/ - void 0, - /*dotDotDotToken*/ - void 0, - "x", - /*questionToken*/ - void 0, - visitNode(node.typeArguments[0], visitExistingNodeTreeSymbols, isTypeNode) - )], - visitNode(node.typeArguments[1], visitExistingNodeTreeSymbols, isTypeNode) - )]); + return factory.createTypeLiteralNode([factory.createIndexSignature( /*modifiers*/ + void 0, [factory.createParameterDeclaration( /*modifiers*/ + void 0, /*dotDotDotToken*/ + void 0, "x", /*questionToken*/ + void 0, visitNode(node.typeArguments[0], visitExistingNodeTreeSymbols, isTypeNode))], visitNode(node.typeArguments[1], visitExistingNodeTreeSymbols, isTypeNode))]); } if (isJSDocFunctionType(node)) { if (isJSDocConstructSignature(node)) { let newTypeNode; - return factory.createConstructorTypeNode( - /*modifiers*/ - void 0, - visitNodes2(node.typeParameters, visitExistingNodeTreeSymbols, isTypeParameterDeclaration), - mapDefined(node.parameters, (p, i) => p.name && isIdentifier(p.name) && p.name.escapedText === "new" ? (newTypeNode = p.type, void 0) : factory.createParameterDeclaration( - /*modifiers*/ - void 0, - getEffectiveDotDotDotForParameter(p), - getNameForJSDocFunctionParameter(p, i), - p.questionToken, - visitNode(p.type, visitExistingNodeTreeSymbols, isTypeNode), - /*initializer*/ - void 0 - )), - visitNode(newTypeNode || node.type, visitExistingNodeTreeSymbols, isTypeNode) || factory.createKeywordTypeNode(133 /* AnyKeyword */) - ); + return factory.createConstructorTypeNode( /*modifiers*/ + void 0, visitNodes2(node.typeParameters, visitExistingNodeTreeSymbols, isTypeParameterDeclaration), mapDefined(node.parameters, (p, i) => p.name && isIdentifier(p.name) && p.name.escapedText === "new" ? (newTypeNode = p.type, void 0) : factory.createParameterDeclaration( /*modifiers*/ + void 0, getEffectiveDotDotDotForParameter(p), getNameForJSDocFunctionParameter(p, i), p.questionToken, visitNode(p.type, visitExistingNodeTreeSymbols, isTypeNode), /*initializer*/ + void 0)), visitNode(newTypeNode || node.type, visitExistingNodeTreeSymbols, isTypeNode) || factory.createKeywordTypeNode(133 /* AnyKeyword */)); } else { - return factory.createFunctionTypeNode( - visitNodes2(node.typeParameters, visitExistingNodeTreeSymbols, isTypeParameterDeclaration), - map(node.parameters, (p, i) => factory.createParameterDeclaration( - /*modifiers*/ - void 0, - getEffectiveDotDotDotForParameter(p), - getNameForJSDocFunctionParameter(p, i), - p.questionToken, - visitNode(p.type, visitExistingNodeTreeSymbols, isTypeNode), - /*initializer*/ - void 0 - )), - visitNode(node.type, visitExistingNodeTreeSymbols, isTypeNode) || factory.createKeywordTypeNode(133 /* AnyKeyword */) - ); + return factory.createFunctionTypeNode(visitNodes2(node.typeParameters, visitExistingNodeTreeSymbols, isTypeParameterDeclaration), map(node.parameters, (p, i) => factory.createParameterDeclaration( /*modifiers*/ + void 0, getEffectiveDotDotDotForParameter(p), getNameForJSDocFunctionParameter(p, i), p.questionToken, visitNode(p.type, visitExistingNodeTreeSymbols, isTypeNode), /*initializer*/ + void 0)), visitNode(node.type, visitExistingNodeTreeSymbols, isTypeNode) || factory.createKeywordTypeNode(133 /* AnyKeyword */)); } } - if (isTypeReferenceNode(node) && isInJSDoc(node) && (!existingTypeNodeIsNotReferenceOrIsReferenceWithCompatibleTypeArgumentCount(node, getTypeFromTypeNode(node)) || getIntendedTypeFromJSDocTypeReference(node) || unknownSymbol === resolveTypeReferenceName( - node, - 788968 /* Type */, - /*ignoreErrors*/ - true - ))) { + + if (isTypeReferenceNode(node) && isInJSDoc(node) && (!existingTypeNodeIsNotReferenceOrIsReferenceWithCompatibleTypeArgumentCount(node, getTypeFromTypeNode(node)) || getIntendedTypeFromJSDocTypeReference(node) || unknownSymbol === resolveTypeReferenceName(node, 788968 /* Type */, /*ignoreErrors*/ + true))) { return setOriginalNode(typeToTypeNodeHelper(getTypeFromTypeNode(node), context), node); } if (isLiteralImportTypeNode(node)) { 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 + 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 factory.updateImportTypeNode( - node, - factory.updateLiteralTypeNode(node.argument, rewriteModuleSpecifier(node, node.argument.literal)), - node.attributes, - node.qualifier, - visitNodes2(node.typeArguments, visitExistingNodeTreeSymbols, isTypeNode), - node.isTypeOf - ); + return factory.updateImportTypeNode(node, factory.updateLiteralTypeNode(node.argument, rewriteModuleSpecifier(node, node.argument.literal)), node.attributes, node.qualifier, visitNodes2(node.typeArguments, visitExistingNodeTreeSymbols, isTypeNode), node.isTypeOf); } if (isEntityName(node) || isEntityNameExpression(node)) { - const { introducesError, node: result } = trackExistingEntityName(node, context, includePrivateSymbol); + const { + introducesError, + node: result + } = trackExistingEntityName(node, context, includePrivateSymbol); hadError = hadError || introducesError; if (result !== node) { return result; @@ -52206,6 +49005,7 @@ ${lanes.join("\n")} if (file && isTupleTypeNode(node) && getLineAndCharacterOfPosition(file, node.pos).line === getLineAndCharacterOfPosition(file, node.end).line) { setEmitFlags(node, 1 /* SingleLine */); } + return visitEachChild(node, visitExistingNodeTreeSymbols, nullTransformationContext); function getEffectiveDotDotDotForParameter(p) { return p.dotDotDotToken || (p.type && isJSDocVariadicType(p.type) ? factory.createToken(26 /* DotDotDotToken */) : void 0); @@ -52230,12 +49030,8 @@ ${lanes.join("\n")} } } else { if (context.tracker && context.tracker.trackExternalModuleSymbolOfImportTypeNode) { - const moduleSym = resolveExternalModuleNameWorker( - lit, - lit, - /*moduleNotFoundError*/ - void 0 - ); + const moduleSym = resolveExternalModuleNameWorker(lit, lit, /*moduleNotFoundError*/ + void 0); if (moduleSym) { context.tracker.trackExternalModuleSymbolOfImportTypeNode(moduleSym); } @@ -52247,27 +49043,19 @@ ${lanes.join("\n")} } function symbolTableToDeclarationStatements(symbolTable, context, bundled) { var _a; - const serializePropertySymbolForClass = makeSerializePropertySymbol( - factory.createPropertyDeclaration, - 174 /* MethodDeclaration */, - /*useAccessors*/ - true - ); - const serializePropertySymbolForInterfaceWorker = makeSerializePropertySymbol( - (mods, name, question, type) => factory.createPropertySignature(mods, name, question, type), - 173 /* MethodSignature */, - /*useAccessors*/ - false - ); + const serializePropertySymbolForClass = makeSerializePropertySymbol(factory.createPropertyDeclaration, 174 /* MethodDeclaration */, /*useAccessors*/ + true); + const serializePropertySymbolForInterfaceWorker = makeSerializePropertySymbol((mods, name, question, type) => factory.createPropertySignature(mods, name, question, type), 173 /* MethodSignature */, /*useAccessors*/ + false); const enclosingDeclaration = context.enclosingDeclaration; let results = []; - const visitedSymbols = /* @__PURE__ */ new Set(); + const visitedSymbols = /* @__PURE__ */new Set(); const deferredPrivatesStack = []; const oldcontext = context; context = { ...oldcontext, usedSymbolNames: new Set(oldcontext.usedSymbolNames), - remappedSymbolNames: /* @__PURE__ */ new Map(), + remappedSymbolNames: /* @__PURE__ */new Map(), remappedSymbolReferences: new Map((_a = oldcontext.remappedSymbolReferences) == null ? void 0 : _a.entries()), tracker: void 0 }; @@ -52275,21 +49063,15 @@ ${lanes.join("\n")} ...oldcontext.tracker.inner, trackSymbol: (sym, decl, meaning) => { var _a2, _b; - if ((_a2 = context.remappedSymbolNames) == null ? void 0 : _a2.has(getSymbolId(sym))) - return false; - const accessibleResult = isSymbolAccessible( - sym, - decl, - meaning, - /*shouldComputeAliasesToMakeVisible*/ - false - ); + if ((_a2 = context.remappedSymbolNames) == null ? void 0 : _a2.has(getSymbolId(sym))) return false; + const accessibleResult = isSymbolAccessible(sym, decl, meaning, /*shouldComputeAliasesToMakeVisible*/ + false); if (accessibleResult.accessibility === 0 /* Accessible */) { const chain = lookupSymbolChainWorker(sym, context, meaning); if (!(sym.flags & 4 /* Property */)) { const root = chain[0]; const contextFile = getSourceFileOfNode(oldcontext.enclosingDeclaration); - if (some(root.declarations, (d) => getSourceFileOfNode(d) === contextFile)) { + if (some(root.declarations, d => getSourceFileOfNode(d) === contextFile)) { includePrivateSymbol(root); } } @@ -52315,6 +49097,7 @@ ${lanes.join("\n")} function isIdentifierAndNotUndefined(node) { return !!node && node.kind === 80 /* Identifier */; } + function getNamesOfDeclaration(statement) { if (isVariableStatement(statement)) { return filter(map(statement.declarationList.declarations, getNameOfDeclaration), isIdentifierAndNotUndefined); @@ -52326,83 +49109,48 @@ ${lanes.join("\n")} const nsIndex = findIndex(statements, isModuleDeclaration); let ns = nsIndex !== -1 ? statements[nsIndex] : void 0; if (ns && exportAssignment && exportAssignment.isExportEquals && isIdentifier(exportAssignment.expression) && isIdentifier(ns.name) && idText(ns.name) === idText(exportAssignment.expression) && ns.body && isModuleBlock(ns.body)) { - const excessExports = filter(statements, (s) => !!(getEffectiveModifierFlags(s) & 32 /* Export */)); + const excessExports = filter(statements, s => !!(getEffectiveModifierFlags(s) & 32 /* Export */)); const name = ns.name; let body = ns.body; if (length(excessExports)) { - ns = factory.updateModuleDeclaration( - ns, - ns.modifiers, - ns.name, - body = factory.updateModuleBlock( - body, - factory.createNodeArray([ - ...ns.body.statements, - factory.createExportDeclaration( - /*modifiers*/ - void 0, - /*isTypeOnly*/ - false, - factory.createNamedExports(map(flatMap(excessExports, (e) => getNamesOfDeclaration(e)), (id) => factory.createExportSpecifier( - /*isTypeOnly*/ - false, - /*propertyName*/ - void 0, - id - ))), - /*moduleSpecifier*/ - void 0 - ) - ]) - ) - ); + ns = factory.updateModuleDeclaration(ns, ns.modifiers, ns.name, body = factory.updateModuleBlock(body, factory.createNodeArray([...ns.body.statements, factory.createExportDeclaration( /*modifiers*/ + void 0, /*isTypeOnly*/ + false, factory.createNamedExports(map(flatMap(excessExports, e => getNamesOfDeclaration(e)), id => factory.createExportSpecifier( /*isTypeOnly*/ + false, /*propertyName*/ + void 0, id))), /*moduleSpecifier*/ + void 0)]))); statements = [...statements.slice(0, nsIndex), ns, ...statements.slice(nsIndex + 1)]; } - if (!find(statements, (s) => s !== ns && nodeHasName(s, name))) { + if (!find(statements, s => s !== ns && nodeHasName(s, name))) { results = []; - const mixinExportFlag = !some(body.statements, (s) => hasSyntacticModifier(s, 32 /* Export */) || isExportAssignment(s) || isExportDeclaration(s)); - forEach(body.statements, (s) => { + const mixinExportFlag = !some(body.statements, s => hasSyntacticModifier(s, 32 /* Export */) || isExportAssignment(s) || isExportDeclaration(s)); + forEach(body.statements, s => { addResult(s, mixinExportFlag ? 32 /* Export */ : 0 /* None */); }); - statements = [...filter(statements, (s) => s !== ns && s !== exportAssignment), ...results]; + + statements = [...filter(statements, s => s !== ns && s !== exportAssignment), ...results]; } } return statements; } function mergeExportDeclarations(statements) { - const exports = filter(statements, (d) => isExportDeclaration(d) && !d.moduleSpecifier && !!d.exportClause && isNamedExports(d.exportClause)); + const exports = filter(statements, d => isExportDeclaration(d) && !d.moduleSpecifier && !!d.exportClause && isNamedExports(d.exportClause)); if (length(exports) > 1) { - const nonExports = filter(statements, (d) => !isExportDeclaration(d) || !!d.moduleSpecifier || !d.exportClause); - statements = [ - ...nonExports, - factory.createExportDeclaration( - /*modifiers*/ - void 0, - /*isTypeOnly*/ - false, - factory.createNamedExports(flatMap(exports, (e) => cast(e.exportClause, isNamedExports).elements)), - /*moduleSpecifier*/ - void 0 - ) - ]; + const nonExports = filter(statements, d => !isExportDeclaration(d) || !!d.moduleSpecifier || !d.exportClause); + statements = [...nonExports, factory.createExportDeclaration( /*modifiers*/ + void 0, /*isTypeOnly*/ + false, factory.createNamedExports(flatMap(exports, e => cast(e.exportClause, isNamedExports).elements)), /*moduleSpecifier*/ + void 0)]; } - const reexports = filter(statements, (d) => isExportDeclaration(d) && !!d.moduleSpecifier && !!d.exportClause && isNamedExports(d.exportClause)); + const reexports = filter(statements, d => isExportDeclaration(d) && !!d.moduleSpecifier && !!d.exportClause && isNamedExports(d.exportClause)); if (length(reexports) > 1) { - const groups = group(reexports, (decl) => isStringLiteral(decl.moduleSpecifier) ? ">" + decl.moduleSpecifier.text : ">"); + const groups = group(reexports, decl => isStringLiteral(decl.moduleSpecifier) ? ">" + decl.moduleSpecifier.text : ">"); if (groups.length !== reexports.length) { for (const group2 of groups) { if (group2.length > 1) { - statements = [ - ...filter(statements, (s) => !group2.includes(s)), - factory.createExportDeclaration( - /*modifiers*/ - void 0, - /*isTypeOnly*/ - false, - factory.createNamedExports(flatMap(group2, (e) => cast(e.exportClause, isNamedExports).elements)), - group2[0].moduleSpecifier - ) - ]; + statements = [...filter(statements, s => !group2.includes(s)), factory.createExportDeclaration( /*modifiers*/ + void 0, /*isTypeOnly*/ + false, factory.createNamedExports(flatMap(group2, e => cast(e.exportClause, isNamedExports).elements)), group2[0].moduleSpecifier)]; } } } @@ -52410,14 +49158,14 @@ ${lanes.join("\n")} return statements; } function inlineExportModifiers(statements) { - const index = findIndex(statements, (d) => isExportDeclaration(d) && !d.moduleSpecifier && !d.attributes && !!d.exportClause && isNamedExports(d.exportClause)); + const index = findIndex(statements, d => isExportDeclaration(d) && !d.moduleSpecifier && !d.attributes && !!d.exportClause && isNamedExports(d.exportClause)); if (index >= 0) { const exportDecl = statements[index]; - const replacements = mapDefined(exportDecl.exportClause.elements, (e) => { + const replacements = mapDefined(exportDecl.exportClause.elements, e => { if (!e.propertyName) { const indices = indicesOf(statements); - const associatedIndices = filter(indices, (i) => nodeHasName(statements[i], e.name)); - if (length(associatedIndices) && every(associatedIndices, (i) => canHaveExportModifier(statements[i]))) { + const associatedIndices = filter(indices, i => nodeHasName(statements[i], e.name)); + if (length(associatedIndices) && every(associatedIndices, i => canHaveExportModifier(statements[i]))) { for (const index2 of associatedIndices) { statements[index2] = addExportModifier(statements[index2]); } @@ -52429,17 +49177,7 @@ ${lanes.join("\n")} if (!length(replacements)) { orderedRemoveItemAt(statements, index); } else { - statements[index] = factory.updateExportDeclaration( - exportDecl, - exportDecl.modifiers, - exportDecl.isTypeOnly, - factory.updateNamedExports( - exportDecl.exportClause, - replacements - ), - exportDecl.moduleSpecifier, - exportDecl.attributes - ); + statements[index] = factory.updateExportDeclaration(exportDecl, exportDecl.modifiers, exportDecl.isTypeOnly, factory.updateNamedExports(exportDecl.exportClause, replacements), exportDecl.moduleSpecifier, exportDecl.attributes); } } return statements; @@ -52463,24 +49201,16 @@ ${lanes.join("\n")} } function visitSymbolTable(symbolTable2, suppressNewPrivateContext, propertyAsAlias) { if (!suppressNewPrivateContext) { - deferredPrivatesStack.push(/* @__PURE__ */ new Map()); + deferredPrivatesStack.push( /* @__PURE__ */new Map()); } - symbolTable2.forEach((symbol) => { - serializeSymbol( - symbol, - /*isPrivate*/ - false, - !!propertyAsAlias - ); + symbolTable2.forEach(symbol => { + serializeSymbol(symbol, /*isPrivate*/ + false, !!propertyAsAlias); }); if (!suppressNewPrivateContext) { - deferredPrivatesStack[deferredPrivatesStack.length - 1].forEach((symbol) => { - serializeSymbol( - symbol, - /*isPrivate*/ - true, - !!propertyAsAlias - ); + deferredPrivatesStack[deferredPrivatesStack.length - 1].forEach(symbol => { + serializeSymbol(symbol, /*isPrivate*/ + true, !!propertyAsAlias); }); deferredPrivatesStack.pop(); } @@ -52492,7 +49222,7 @@ ${lanes.join("\n")} } visitedSymbols.add(getSymbolId(visitedSym)); const skipMembershipCheck = !isPrivate; - if (skipMembershipCheck || !!length(symbol.declarations) && some(symbol.declarations, (d) => !!findAncestor(d, (n) => n === enclosingDeclaration))) { + if (skipMembershipCheck || !!length(symbol.declarations) && some(symbol.declarations, d => !!findAncestor(d, n => n === enclosingDeclaration))) { const oldContext = context; context = cloneNodeBuilderContext(context); serializeSymbolWorker(symbol, isPrivate, propertyAsAlias); @@ -52500,10 +49230,7 @@ ${lanes.join("\n")} oldcontext.reportedDiagnostic = context.reportedDiagnostic; } if (context.trackedSymbols) { - if (!oldContext.trackedSymbols) - oldContext.trackedSymbols = context.trackedSymbols; - else - Debug.assert(context.trackedSymbols === oldContext.trackedSymbols); + if (!oldContext.trackedSymbols) oldContext.trackedSymbols = context.trackedSymbols;else Debug.assert(context.trackedSymbols === oldContext.trackedSymbols); } context = oldContext; } @@ -52542,7 +49269,7 @@ ${lanes.join("\n")} const localName = getInternalSymbolName(symbol, symbolName2); if (type.symbol && type.symbol !== symbol && type.symbol.flags & 16 /* Function */ && some(type.symbol.declarations, isFunctionExpressionOrArrowFunction) && (((_a2 = type.symbol.members) == null ? void 0 : _a2.size) || ((_b = type.symbol.exports) == null ? void 0 : _b.size))) { if (!context.remappedSymbolReferences) { - context.remappedSymbolReferences = /* @__PURE__ */ new Map(); + context.remappedSymbolReferences = /* @__PURE__ */new Map(); } context.remappedSymbolReferences.set(getSymbolId(type.symbol), symbol); serializeSymbolWorker(type.symbol, isPrivate, propertyAsAlias, escapedSymbolName); @@ -52552,62 +49279,30 @@ ${lanes.join("\n")} } else { const flags = !(symbol.flags & 2 /* BlockScopedVariable */) ? ((_c = symbol.parent) == null ? void 0 : _c.valueDeclaration) && isSourceFile((_d = symbol.parent) == null ? void 0 : _d.valueDeclaration) ? 2 /* Const */ : void 0 : isConstantVariable(symbol) ? 2 /* Const */ : 1 /* Let */; const name = needsPostExportDefault || !(symbol.flags & 4 /* Property */) ? localName : getUnusedName(localName, symbol); - let textRange = symbol.declarations && find(symbol.declarations, (d) => isVariableDeclaration(d)); + let textRange = symbol.declarations && find(symbol.declarations, d => isVariableDeclaration(d)); if (textRange && isVariableDeclarationList(textRange.parent) && textRange.parent.declarations.length === 1) { textRange = textRange.parent.parent; } const propertyAccessRequire = (_e = symbol.declarations) == null ? void 0 : _e.find(isPropertyAccessExpression); if (propertyAccessRequire && isBinaryExpression(propertyAccessRequire.parent) && isIdentifier(propertyAccessRequire.parent.right) && ((_f = type.symbol) == null ? void 0 : _f.valueDeclaration) && isSourceFile(type.symbol.valueDeclaration)) { const alias = localName === propertyAccessRequire.parent.right.escapedText ? void 0 : propertyAccessRequire.parent.right; - addResult( - factory.createExportDeclaration( - /*modifiers*/ - void 0, - /*isTypeOnly*/ - false, - factory.createNamedExports([factory.createExportSpecifier( - /*isTypeOnly*/ - false, - alias, - localName - )]) - ), - 0 /* None */ - ); + addResult(factory.createExportDeclaration( /*modifiers*/ + void 0, /*isTypeOnly*/ + false, factory.createNamedExports([factory.createExportSpecifier( /*isTypeOnly*/ + false, alias, localName)])), 0 /* None */); + context.tracker.trackSymbol(type.symbol, context.enclosingDeclaration, 111551 /* Value */); } else { - const statement = setTextRange( - factory.createVariableStatement( - /*modifiers*/ - void 0, - factory.createVariableDeclarationList([ - factory.createVariableDeclaration( - name, - /*exclamationToken*/ - void 0, - serializeTypeForDeclaration(context, type, symbol, enclosingDeclaration, includePrivateSymbol, bundled) - ) - ], flags) - ), - textRange - ); + const statement = setTextRange(factory.createVariableStatement( /*modifiers*/ + void 0, factory.createVariableDeclarationList([factory.createVariableDeclaration(name, /*exclamationToken*/ + void 0, serializeTypeForDeclaration(context, type, symbol, enclosingDeclaration, includePrivateSymbol, bundled))], flags)), textRange); addResult(statement, name !== localName ? modifierFlags & ~32 /* Export */ : modifierFlags); if (name !== localName && !isPrivate) { - addResult( - factory.createExportDeclaration( - /*modifiers*/ - void 0, - /*isTypeOnly*/ - false, - factory.createNamedExports([factory.createExportSpecifier( - /*isTypeOnly*/ - false, - name, - localName - )]) - ), - 0 /* None */ - ); + addResult(factory.createExportDeclaration( /*modifiers*/ + void 0, /*isTypeOnly*/ + false, factory.createNamedExports([factory.createExportSpecifier( /*isTypeOnly*/ + false, name, localName)])), 0 /* None */); + needsExportDeclaration = false; needsPostExportDefault = false; } @@ -52641,52 +49336,32 @@ ${lanes.join("\n")} if (symbol.declarations) { for (const node of symbol.declarations) { const resolvedModule = resolveExternalModuleName(node, node.moduleSpecifier); - if (!resolvedModule) - continue; - addResult(factory.createExportDeclaration( - /*modifiers*/ - void 0, - /*isTypeOnly*/ - node.isTypeOnly, - /*exportClause*/ - void 0, - factory.createStringLiteral(getSpecifierForModuleSymbol(resolvedModule, context)) - ), 0 /* None */); + if (!resolvedModule) continue; + addResult(factory.createExportDeclaration( /*modifiers*/ + void 0, /*isTypeOnly*/ + node.isTypeOnly, /*exportClause*/ + void 0, factory.createStringLiteral(getSpecifierForModuleSymbol(resolvedModule, context))), 0 /* None */); } } } + if (needsPostExportDefault) { - addResult(factory.createExportAssignment( - /*modifiers*/ - void 0, - /*isExportEquals*/ - false, - factory.createIdentifier(getInternalSymbolName(symbol, symbolName2)) - ), 0 /* None */); + addResult(factory.createExportAssignment( /*modifiers*/ + void 0, /*isExportEquals*/ + false, factory.createIdentifier(getInternalSymbolName(symbol, symbolName2))), 0 /* None */); } else if (needsExportDeclaration) { - addResult( - factory.createExportDeclaration( - /*modifiers*/ - void 0, - /*isTypeOnly*/ - false, - factory.createNamedExports([factory.createExportSpecifier( - /*isTypeOnly*/ - false, - getInternalSymbolName(symbol, symbolName2), - symbolName2 - )]) - ), - 0 /* None */ - ); + addResult(factory.createExportDeclaration( /*modifiers*/ + void 0, /*isTypeOnly*/ + false, factory.createNamedExports([factory.createExportSpecifier( /*isTypeOnly*/ + false, getInternalSymbolName(symbol, symbolName2), symbolName2)])), 0 /* None */); } } + function includePrivateSymbol(symbol) { - if (some(symbol.declarations, isParameterDeclaration)) - return; + if (some(symbol.declarations, isParameterDeclaration)) 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)); + const isExternalImportAlias = !!(symbol.flags & 2097152 /* Alias */) && !some(symbol.declarations, d => !!findAncestor(d, isExportDeclaration) || isNamespaceExport(d) || isImportEqualsDeclaration(d) && !isExternalModuleReference(d.moduleReference)); deferredPrivatesStack[isExternalImportAlias ? 0 : deferredPrivatesStack.length - 1].set(getSymbolId(symbol), symbol); } function isExportingScope(enclosingDeclaration2) { @@ -52699,12 +49374,15 @@ ${lanes.join("\n")} if (additionalModifierFlags & 32 /* Export */ && enclosingDeclaration2 && (isExportingScope(enclosingDeclaration2) || isModuleDeclaration(enclosingDeclaration2)) && canHaveExportModifier(node)) { newModifierFlags |= 32 /* Export */; } + if (addingDeclare && !(newModifierFlags & 32 /* Export */) && (!enclosingDeclaration2 || !(enclosingDeclaration2.flags & 33554432 /* Ambient */)) && (isEnumDeclaration(node) || isVariableStatement(node) || isFunctionDeclaration(node) || isClassDeclaration(node) || isModuleDeclaration(node))) { newModifierFlags |= 128 /* Ambient */; } + if (additionalModifierFlags & 2048 /* Default */ && (isClassDeclaration(node) || isInterfaceDeclaration(node) || isFunctionDeclaration(node))) { newModifierFlags |= 2048 /* Default */; } + if (newModifierFlags) { node = factory.replaceModifiers(node, newModifierFlags | getEffectiveModifierFlags(node)); } @@ -52715,7 +49393,7 @@ ${lanes.join("\n")} var _a2; const aliasType = getDeclaredTypeOfTypeAlias(symbol); const typeParams = getSymbolLinks(symbol).typeParameters; - const typeParamDecls = map(typeParams, (p) => typeParameterToDeclaration(p, context)); + const typeParamDecls = map(typeParams, p => typeParameterToDeclaration(p, context)); const jsdocAliasDecl = (_a2 = symbol.declarations) == null ? void 0 : _a2.find(isJSDocTypeAlias); const commentText = getTextOfJSDocComment(jsdocAliasDecl ? jsdocAliasDecl.comment || jsdocAliasDecl.parent.comment : void 0); const oldFlags = context.flags; @@ -52723,136 +49401,96 @@ ${lanes.join("\n")} const oldEnclosingDecl = context.enclosingDeclaration; context.enclosingDeclaration = jsdocAliasDecl; const typeNode = jsdocAliasDecl && jsdocAliasDecl.typeExpression && isJSDocTypeExpression(jsdocAliasDecl.typeExpression) && serializeExistingTypeNode(context, jsdocAliasDecl.typeExpression.type, includePrivateSymbol, bundled) || typeToTypeNodeHelper(aliasType, context); - addResult( - setSyntheticLeadingComments( - factory.createTypeAliasDeclaration( - /*modifiers*/ - void 0, - getInternalSymbolName(symbol, symbolName2), - typeParamDecls, - typeNode - ), - !commentText ? [] : [{ kind: 3 /* MultiLineCommentTrivia */, text: "*\n * " + commentText.replace(/\n/g, "\n * ") + "\n ", pos: -1, end: -1, hasTrailingNewLine: true }] - ), - modifierFlags - ); + addResult(setSyntheticLeadingComments(factory.createTypeAliasDeclaration( /*modifiers*/ + void 0, getInternalSymbolName(symbol, symbolName2), typeParamDecls, typeNode), !commentText ? [] : [{ + kind: 3 /* MultiLineCommentTrivia */, + text: "*\n * " + commentText.replace(/\n/g, "\n * ") + "\n ", + pos: -1, + end: -1, + hasTrailingNewLine: true + }]), modifierFlags); context.flags = oldFlags; context.enclosingDeclaration = oldEnclosingDecl; } function serializeInterface(symbol, symbolName2, modifierFlags) { const interfaceType = getDeclaredTypeOfClassOrInterface(symbol); const localParams = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); - const typeParamDecls = map(localParams, (p) => typeParameterToDeclaration(p, context)); + const typeParamDecls = map(localParams, p => typeParameterToDeclaration(p, context)); const baseTypes = getBaseTypes(interfaceType); const baseType = length(baseTypes) ? getIntersectionType(baseTypes) : void 0; - const members = flatMap(getPropertiesOfType(interfaceType), (p) => serializePropertySymbolForInterface(p, baseType)); + const members = flatMap(getPropertiesOfType(interfaceType), p => serializePropertySymbolForInterface(p, baseType)); const callSignatures = serializeSignatures(0 /* Call */, interfaceType, baseType, 179 /* CallSignature */); const constructSignatures = serializeSignatures(1 /* Construct */, interfaceType, baseType, 180 /* ConstructSignature */); const indexSignatures = serializeIndexSignatures(interfaceType, baseType); - const heritageClauses = !length(baseTypes) ? void 0 : [factory.createHeritageClause(96 /* ExtendsKeyword */, mapDefined(baseTypes, (b) => trySerializeAsTypeReference(b, 111551 /* Value */)))]; - addResult( - factory.createInterfaceDeclaration( - /*modifiers*/ - void 0, - getInternalSymbolName(symbol, symbolName2), - typeParamDecls, - heritageClauses, - [...indexSignatures, ...constructSignatures, ...callSignatures, ...members] - ), - modifierFlags - ); + const heritageClauses = !length(baseTypes) ? void 0 : [factory.createHeritageClause(96 /* ExtendsKeyword */, mapDefined(baseTypes, b => trySerializeAsTypeReference(b, 111551 /* Value */)))]; + addResult(factory.createInterfaceDeclaration( /*modifiers*/ + void 0, getInternalSymbolName(symbol, symbolName2), typeParamDecls, heritageClauses, [...indexSignatures, ...constructSignatures, ...callSignatures, ...members]), modifierFlags); } function getNamespaceMembersForSerialization(symbol) { const exports = getExportsOfSymbol(symbol); - return !exports ? [] : filter(arrayFrom(exports.values()), (m) => isNamespaceMember(m) && isIdentifierText(m.escapedName, 99 /* ESNext */)); + return !exports ? [] : filter(arrayFrom(exports.values()), m => isNamespaceMember(m) && isIdentifierText(m.escapedName, 99 /* ESNext */)); } + function isTypeOnlyNamespace(symbol) { - return every(getNamespaceMembersForSerialization(symbol), (m) => !(getSymbolFlags(resolveSymbol(m)) & 111551 /* Value */)); + return every(getNamespaceMembersForSerialization(symbol), m => !(getSymbolFlags(resolveSymbol(m)) & 111551 /* Value */)); } + function serializeModule(symbol, symbolName2, modifierFlags) { const members = getNamespaceMembersForSerialization(symbol); - const locationMap = arrayToMultiMap(members, (m) => m.parent && m.parent === symbol ? "real" : "merged"); + const locationMap = arrayToMultiMap(members, m => m.parent && m.parent === symbol ? "real" : "merged"); const realMembers = locationMap.get("real") || emptyArray; const mergedMembers = locationMap.get("merged") || emptyArray; if (length(realMembers)) { const localName = getInternalSymbolName(symbol, symbolName2); serializeAsNamespaceDeclaration(realMembers, localName, modifierFlags, !!(symbol.flags & (16 /* Function */ | 67108864 /* Assignment */))); } + if (length(mergedMembers)) { const containingFile = getSourceFileOfNode(context.enclosingDeclaration); const localName = getInternalSymbolName(symbol, symbolName2); - const nsBody = factory.createModuleBlock([factory.createExportDeclaration( - /*modifiers*/ - void 0, - /*isTypeOnly*/ - false, - factory.createNamedExports(mapDefined(filter(mergedMembers, (n) => n.escapedName !== "export=" /* ExportEquals */), (s) => { - var _a2, _b; - const name = unescapeLeadingUnderscores(s.escapedName); - const localName2 = getInternalSymbolName(s, name); - const aliasDecl = s.declarations && getDeclarationOfAliasSymbol(s); - if (containingFile && (aliasDecl ? containingFile !== getSourceFileOfNode(aliasDecl) : !some(s.declarations, (d) => getSourceFileOfNode(d) === containingFile))) { - (_b = (_a2 = context.tracker) == null ? void 0 : _a2.reportNonlocalAugmentation) == null ? void 0 : _b.call(_a2, containingFile, symbol, s); - return void 0; - } - const target = aliasDecl && getTargetOfAliasDeclaration( - aliasDecl, - /*dontRecursivelyResolve*/ - true - ); - includePrivateSymbol(target || s); - const targetName = target ? getInternalSymbolName(target, unescapeLeadingUnderscores(target.escapedName)) : localName2; - return factory.createExportSpecifier( - /*isTypeOnly*/ - false, - name === targetName ? void 0 : targetName, - name - ); - })) - )]); - addResult( - factory.createModuleDeclaration( - /*modifiers*/ - void 0, - factory.createIdentifier(localName), - nsBody, - 32 /* Namespace */ - ), - 0 /* None */ - ); + const nsBody = factory.createModuleBlock([factory.createExportDeclaration( /*modifiers*/ + void 0, /*isTypeOnly*/ + false, factory.createNamedExports(mapDefined(filter(mergedMembers, n => n.escapedName !== "export=" /* ExportEquals */), s => { + var _a2, _b; + const name = unescapeLeadingUnderscores(s.escapedName); + const localName2 = getInternalSymbolName(s, name); + const aliasDecl = s.declarations && getDeclarationOfAliasSymbol(s); + if (containingFile && (aliasDecl ? containingFile !== getSourceFileOfNode(aliasDecl) : !some(s.declarations, d => getSourceFileOfNode(d) === containingFile))) { + (_b = (_a2 = context.tracker) == null ? void 0 : _a2.reportNonlocalAugmentation) == null ? void 0 : _b.call(_a2, containingFile, symbol, s); + return void 0; + } + const target = aliasDecl && getTargetOfAliasDeclaration(aliasDecl, /*dontRecursivelyResolve*/ + true); + includePrivateSymbol(target || s); + const targetName = target ? getInternalSymbolName(target, unescapeLeadingUnderscores(target.escapedName)) : localName2; + return factory.createExportSpecifier( /*isTypeOnly*/ + false, name === targetName ? void 0 : targetName, name); + })))]); + addResult(factory.createModuleDeclaration( /*modifiers*/ + void 0, factory.createIdentifier(localName), nsBody, 32 /* Namespace */), 0 /* None */); } } + function serializeEnum(symbol, symbolName2, modifierFlags) { - addResult( - factory.createEnumDeclaration( - factory.createModifiersFromModifierFlags(isConstEnumSymbol(symbol) ? 4096 /* Const */ : 0), - getInternalSymbolName(symbol, symbolName2), - map(filter(getPropertiesOfType(getTypeOfSymbol(symbol)), (p) => !!(p.flags & 8 /* EnumMember */)), (p) => { - const initializedValue = p.declarations && p.declarations[0] && isEnumMember(p.declarations[0]) ? getConstantValue2(p.declarations[0]) : void 0; - return factory.createEnumMember( - unescapeLeadingUnderscores(p.escapedName), - initializedValue === void 0 ? void 0 : typeof initializedValue === "string" ? factory.createStringLiteral(initializedValue) : factory.createNumericLiteral(initializedValue) - ); - }) - ), - modifierFlags - ); + addResult(factory.createEnumDeclaration(factory.createModifiersFromModifierFlags(isConstEnumSymbol(symbol) ? 4096 /* Const */ : 0), getInternalSymbolName(symbol, symbolName2), map(filter(getPropertiesOfType(getTypeOfSymbol(symbol)), p => !!(p.flags & 8 /* EnumMember */)), p => { + const initializedValue = p.declarations && p.declarations[0] && isEnumMember(p.declarations[0]) ? getConstantValue2(p.declarations[0]) : void 0; + return factory.createEnumMember(unescapeLeadingUnderscores(p.escapedName), initializedValue === void 0 ? void 0 : typeof initializedValue === "string" ? factory.createStringLiteral(initializedValue) : factory.createNumericLiteral(initializedValue)); + })), modifierFlags); } function serializeAsFunctionNamespaceMerge(type, symbol, localName, modifierFlags) { const signatures = getSignaturesOfType(type, 0 /* Call */); for (const sig of signatures) { - const decl = signatureToSignatureDeclarationHelper(sig, 262 /* FunctionDeclaration */, context, { name: factory.createIdentifier(localName), privateSymbolVisitor: includePrivateSymbol, bundledImports: bundled }); + const decl = signatureToSignatureDeclarationHelper(sig, 262 /* FunctionDeclaration */, context, { + name: factory.createIdentifier(localName), + privateSymbolVisitor: includePrivateSymbol, + bundledImports: bundled + }); addResult(setTextRange(decl, getSignatureTextRangeLocation(sig)), modifierFlags); } if (!(symbol.flags & (512 /* ValueModule */ | 1024 /* NamespaceModule */) && !!symbol.exports && !!symbol.exports.size)) { const props = filter(getPropertiesOfType(type), isNamespaceMember); - serializeAsNamespaceDeclaration( - props, - localName, - modifierFlags, - /*suppressNewPrivateContext*/ - true - ); + serializeAsNamespaceDeclaration(props, localName, modifierFlags, /*suppressNewPrivateContext*/ + true); } } function getSignatureTextRangeLocation(signature) { @@ -52868,15 +49506,11 @@ ${lanes.join("\n")} } function serializeAsNamespaceDeclaration(props, localName, modifierFlags, suppressNewPrivateContext) { if (length(props)) { - const localVsRemoteMap = arrayToMultiMap(props, (p) => !length(p.declarations) || some(p.declarations, (d) => getSourceFileOfNode(d) === getSourceFileOfNode(context.enclosingDeclaration)) ? "local" : "remote"); + const localVsRemoteMap = arrayToMultiMap(props, p => !length(p.declarations) || some(p.declarations, d => getSourceFileOfNode(d) === getSourceFileOfNode(context.enclosingDeclaration)) ? "local" : "remote"); const localProps = localVsRemoteMap.get("local") || emptyArray; - let fakespace = parseNodeFactory.createModuleDeclaration( - /*modifiers*/ - void 0, - factory.createIdentifier(localName), - factory.createModuleBlock([]), - 32 /* Namespace */ - ); + let fakespace = parseNodeFactory.createModuleDeclaration( /*modifiers*/ + void 0, factory.createIdentifier(localName), factory.createModuleBlock([]), 32 /* Namespace */); + setParent(fakespace, enclosingDeclaration); fakespace.locals = createSymbolTable(props); fakespace.symbol = props[0].parent; @@ -52884,38 +49518,24 @@ ${lanes.join("\n")} results = []; const oldAddingDeclare = addingDeclare; addingDeclare = false; - const subcontext = { ...context, enclosingDeclaration: fakespace }; + const subcontext = { + ...context, + enclosingDeclaration: fakespace + }; const oldContext = context; context = subcontext; - visitSymbolTable( - createSymbolTable(localProps), - suppressNewPrivateContext, - /*propertyAsAlias*/ - true - ); + visitSymbolTable(createSymbolTable(localProps), suppressNewPrivateContext, /*propertyAsAlias*/ + true); context = oldContext; addingDeclare = oldAddingDeclare; const declarations = results; results = oldResults; - const defaultReplaced = map(declarations, (d) => isExportAssignment(d) && !d.isExportEquals && isIdentifier(d.expression) ? factory.createExportDeclaration( - /*modifiers*/ - void 0, - /*isTypeOnly*/ - false, - factory.createNamedExports([factory.createExportSpecifier( - /*isTypeOnly*/ - false, - d.expression, - factory.createIdentifier("default" /* Default */) - )]) - ) : d); - const exportModifierStripped = every(defaultReplaced, (d) => hasSyntacticModifier(d, 32 /* Export */)) ? map(defaultReplaced, removeExportModifier) : defaultReplaced; - fakespace = factory.updateModuleDeclaration( - fakespace, - fakespace.modifiers, - fakespace.name, - factory.createModuleBlock(exportModifierStripped) - ); + const defaultReplaced = map(declarations, d => isExportAssignment(d) && !d.isExportEquals && isIdentifier(d.expression) ? factory.createExportDeclaration( /*modifiers*/ + void 0, /*isTypeOnly*/ + false, factory.createNamedExports([factory.createExportSpecifier( /*isTypeOnly*/ + false, d.expression, factory.createIdentifier("default" /* Default */))])) : d); + const exportModifierStripped = every(defaultReplaced, d => hasSyntacticModifier(d, 32 /* Export */)) ? map(defaultReplaced, removeExportModifier) : defaultReplaced; + fakespace = factory.updateModuleDeclaration(fakespace, fakespace.modifiers, fakespace.name, factory.createModuleBlock(exportModifierStripped)); addResult(fakespace, modifierFlags); } } @@ -52923,30 +49543,26 @@ ${lanes.join("\n")} return !!(p.flags & (788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */)) || !(p.flags & 4194304 /* Prototype */ || p.escapedName === "prototype" || p.valueDeclaration && isStatic(p.valueDeclaration) && isClassLike(p.valueDeclaration.parent)); } function sanitizeJSDocImplements(clauses) { - const result = mapDefined(clauses, (e) => { + const result = mapDefined(clauses, e => { const oldEnclosing = context.enclosingDeclaration; context.enclosingDeclaration = e; let expr = e.expression; if (isEntityNameExpression(expr)) { if (isIdentifier(expr) && idText(expr) === "") { - return cleanup( - /*result*/ - void 0 - ); + return cleanup( /*result*/ + void 0); } let introducesError; - ({ introducesError, node: expr } = trackExistingEntityName(expr, context, includePrivateSymbol)); + ({ + introducesError, + node: expr + } = trackExistingEntityName(expr, context, includePrivateSymbol)); if (introducesError) { - return cleanup( - /*result*/ - void 0 - ); + return cleanup( /*result*/ + void 0); } } - return cleanup(factory.createExpressionWithTypeArguments( - expr, - map(e.typeArguments, (a) => serializeExistingTypeNode(context, a, includePrivateSymbol, bundled) || typeToTypeNodeHelper(getTypeFromTypeNode(a), context)) - )); + return cleanup(factory.createExpressionWithTypeArguments(expr, map(e.typeArguments, a => serializeExistingTypeNode(context, a, includePrivateSymbol, bundled) || typeToTypeNodeHelper(getTypeFromTypeNode(a), context)))); function cleanup(result2) { context.enclosingDeclaration = oldEnclosing; return result2; @@ -52963,7 +49579,7 @@ ${lanes.join("\n")} const oldEnclosing = context.enclosingDeclaration; context.enclosingDeclaration = originalDecl || oldEnclosing; const localParams = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); - const typeParamDecls = map(localParams, (p) => typeParameterToDeclaration(p, context)); + const typeParamDecls = map(localParams, p => typeParameterToDeclaration(p, context)); const classType = getTypeWithThisArgument(getDeclaredTypeOfClassOrInterface(symbol)); const baseTypes = getBaseTypes(classType); const originalImplements = originalDecl && getEffectiveImplementsTypeNodes(originalDecl); @@ -52971,71 +49587,35 @@ ${lanes.join("\n")} const staticType = getTypeOfSymbol(symbol); const isClass = !!((_b = staticType.symbol) == null ? void 0 : _b.valueDeclaration) && isClassLike(staticType.symbol.valueDeclaration); const staticBaseType = isClass ? getBaseConstructorTypeOfClass(staticType) : anyType; - const heritageClauses = [ - ...!length(baseTypes) ? [] : [factory.createHeritageClause(96 /* ExtendsKeyword */, map(baseTypes, (b) => serializeBaseType(b, staticBaseType, localName)))], - ...!length(implementsExpressions) ? [] : [factory.createHeritageClause(119 /* ImplementsKeyword */, implementsExpressions)] - ]; + const heritageClauses = [...(!length(baseTypes) ? [] : [factory.createHeritageClause(96 /* ExtendsKeyword */, map(baseTypes, b => serializeBaseType(b, staticBaseType, localName)))]), ...(!length(implementsExpressions) ? [] : [factory.createHeritageClause(119 /* ImplementsKeyword */, implementsExpressions)])]; const symbolProps = getNonInheritedProperties(classType, baseTypes, getPropertiesOfType(classType)); - const publicSymbolProps = filter(symbolProps, (s) => { + const publicSymbolProps = filter(symbolProps, s => { const valueDecl = s.valueDeclaration; return !!valueDecl && !(isNamedDeclaration(valueDecl) && isPrivateIdentifier(valueDecl.name)); }); - const hasPrivateIdentifier = some(symbolProps, (s) => { + const hasPrivateIdentifier = some(symbolProps, s => { const valueDecl = s.valueDeclaration; return !!valueDecl && isNamedDeclaration(valueDecl) && isPrivateIdentifier(valueDecl.name); }); - const privateProperties = hasPrivateIdentifier ? [factory.createPropertyDeclaration( - /*modifiers*/ - void 0, - factory.createPrivateIdentifier("#private"), - /*questionOrExclamationToken*/ - void 0, - /*type*/ - void 0, - /*initializer*/ - void 0 - )] : emptyArray; - const publicProperties = flatMap(publicSymbolProps, (p) => serializePropertySymbolForClass( - p, - /*isStatic*/ - false, - baseTypes[0] - )); - const staticMembers = flatMap( - filter(getPropertiesOfType(staticType), (p) => !(p.flags & 4194304 /* Prototype */) && p.escapedName !== "prototype" && !isNamespaceMember(p)), - (p) => serializePropertySymbolForClass( - p, - /*isStatic*/ - true, - staticBaseType - ) - ); + const privateProperties = hasPrivateIdentifier ? [factory.createPropertyDeclaration( /*modifiers*/ + void 0, factory.createPrivateIdentifier("#private"), /*questionOrExclamationToken*/ + void 0, /*type*/ + void 0, /*initializer*/ + void 0)] : emptyArray; + const publicProperties = flatMap(publicSymbolProps, p => serializePropertySymbolForClass(p, /*isStatic*/ + false, baseTypes[0])); + const staticMembers = flatMap(filter(getPropertiesOfType(staticType), p => !(p.flags & 4194304 /* Prototype */) && p.escapedName !== "prototype" && !isNamespaceMember(p)), p => serializePropertySymbolForClass(p, /*isStatic*/ + true, staticBaseType)); const isNonConstructableClassLikeInJsFile = !isClass && !!symbol.valueDeclaration && isInJSFile(symbol.valueDeclaration) && !some(getSignaturesOfType(staticType, 1 /* Construct */)); - const constructors = isNonConstructableClassLikeInJsFile ? [factory.createConstructorDeclaration( - factory.createModifiersFromModifierFlags(2 /* Private */), - [], - /*body*/ - void 0 - )] : serializeSignatures(1 /* Construct */, staticType, staticBaseType, 176 /* Constructor */); + const constructors = isNonConstructableClassLikeInJsFile ? [factory.createConstructorDeclaration(factory.createModifiersFromModifierFlags(2 /* Private */), [], /*body*/ + void 0)] : serializeSignatures(1 /* Construct */, staticType, staticBaseType, 176 /* Constructor */); const indexSignatures = serializeIndexSignatures(classType, baseTypes[0]); context.enclosingDeclaration = oldEnclosing; - addResult( - setTextRange( - factory.createClassDeclaration( - /*modifiers*/ - void 0, - localName, - typeParamDecls, - heritageClauses, - [...indexSignatures, ...staticMembers, ...constructors, ...publicProperties, ...privateProperties] - ), - symbol.declarations && filter(symbol.declarations, (d) => isClassDeclaration(d) || isClassExpression(d))[0] - ), - modifierFlags - ); + addResult(setTextRange(factory.createClassDeclaration( /*modifiers*/ + void 0, localName, typeParamDecls, heritageClauses, [...indexSignatures, ...staticMembers, ...constructors, ...publicProperties, ...privateProperties]), symbol.declarations && filter(symbol.declarations, d => isClassDeclaration(d) || isClassExpression(d))[0]), modifierFlags); } function getSomeTargetNameFromDeclarations(declarations) { - return firstDefined(declarations, (d) => { + return firstDefined(declarations, d => { if (isImportSpecifier(d) || isExportSpecifier(d)) { return idText(d.propertyName || d.name); } @@ -53057,13 +49637,9 @@ ${lanes.join("\n")} function serializeAsAlias(symbol, localName, modifierFlags) { var _a2, _b, _c, _d, _e; const node = getDeclarationOfAliasSymbol(symbol); - if (!node) - return Debug.fail(); - const target = getMergedSymbol(getTargetOfAliasDeclaration( - node, - /*dontRecursivelyResolve*/ - true - )); + if (!node) return Debug.fail(); + const target = getMergedSymbol(getTargetOfAliasDeclaration(node, /*dontRecursivelyResolve*/ + true)); if (!target) { return; } @@ -53071,45 +49647,30 @@ ${lanes.join("\n")} if (verbatimTargetName === "export=" /* ExportEquals */ && allowSyntheticDefaultImports) { verbatimTargetName = "default" /* Default */; } + const targetName = getInternalSymbolName(target, verbatimTargetName); includePrivateSymbol(target); switch (node.kind) { case 208 /* BindingElement */: if (((_b = (_a2 = node.parent) == null ? void 0 : _a2.parent) == null ? void 0 : _b.kind) === 260 /* VariableDeclaration */) { const specifier2 = getSpecifierForModuleSymbol(target.parent || target, context); - const { propertyName } = node; - addResult( - factory.createImportDeclaration( - /*modifiers*/ - void 0, - factory.createImportClause( - /*isTypeOnly*/ - false, - /*name*/ - void 0, - factory.createNamedImports([factory.createImportSpecifier( - /*isTypeOnly*/ - false, - propertyName && isIdentifier(propertyName) ? factory.createIdentifier(idText(propertyName)) : void 0, - factory.createIdentifier(localName) - )]) - ), - factory.createStringLiteral(specifier2), - /*attributes*/ - void 0 - ), - 0 /* None */ - ); + const { + propertyName + } = node; + addResult(factory.createImportDeclaration( /*modifiers*/ + void 0, factory.createImportClause( /*isTypeOnly*/ + false, /*name*/ + void 0, factory.createNamedImports([factory.createImportSpecifier( /*isTypeOnly*/ + false, propertyName && isIdentifier(propertyName) ? factory.createIdentifier(idText(propertyName)) : void 0, factory.createIdentifier(localName))])), factory.createStringLiteral(specifier2), /*attributes*/ + void 0), 0 /* None */); + break; } Debug.failBadSyntaxKind(((_c = node.parent) == null ? void 0 : _c.parent) || node, "Unhandled binding element grandparent kind in declaration serialization"); break; case 304 /* ShorthandPropertyAssignment */: if (((_e = (_d = node.parent) == null ? void 0 : _d.parent) == null ? void 0 : _e.kind) === 226 /* BinaryExpression */) { - serializeExportSpecifier( - unescapeLeadingUnderscores(symbol.escapedName), - targetName - ); + serializeExportSpecifier(unescapeLeadingUnderscores(symbol.escapedName), targetName); } break; case 260 /* VariableDeclaration */: @@ -53117,147 +49678,73 @@ ${lanes.join("\n")} const initializer = node.initializer; const uniqueName = factory.createUniqueName(localName); const specifier2 = getSpecifierForModuleSymbol(target.parent || target, context); - addResult( - factory.createImportEqualsDeclaration( - /*modifiers*/ - void 0, - /*isTypeOnly*/ - false, - uniqueName, - factory.createExternalModuleReference(factory.createStringLiteral(specifier2)) - ), - 0 /* None */ - ); - addResult( - factory.createImportEqualsDeclaration( - /*modifiers*/ - void 0, - /*isTypeOnly*/ - false, - factory.createIdentifier(localName), - factory.createQualifiedName(uniqueName, initializer.name) - ), - modifierFlags - ); + addResult(factory.createImportEqualsDeclaration( /*modifiers*/ + void 0, /*isTypeOnly*/ + false, uniqueName, factory.createExternalModuleReference(factory.createStringLiteral(specifier2))), 0 /* None */); + + addResult(factory.createImportEqualsDeclaration( /*modifiers*/ + void 0, /*isTypeOnly*/ + false, factory.createIdentifier(localName), factory.createQualifiedName(uniqueName, initializer.name)), modifierFlags); break; } case 271 /* ImportEqualsDeclaration */: - if (target.escapedName === "export=" /* ExportEquals */ && some(target.declarations, (d) => isSourceFile(d) && isJsonSourceFile(d))) { + if (target.escapedName === "export=" /* ExportEquals */ && some(target.declarations, d => isSourceFile(d) && isJsonSourceFile(d))) { serializeMaybeAliasAssignment(symbol); break; } const isLocalImport = !(target.flags & 512 /* ValueModule */) && !isVariableDeclaration(node); - addResult( - factory.createImportEqualsDeclaration( - /*modifiers*/ - void 0, - /*isTypeOnly*/ - false, - factory.createIdentifier(localName), - isLocalImport ? symbolToName( - target, - context, - 67108863 /* All */, - /*expectsIdentifier*/ - false - ) : factory.createExternalModuleReference(factory.createStringLiteral(getSpecifierForModuleSymbol(target, context))) - ), - isLocalImport ? modifierFlags : 0 /* None */ - ); + addResult(factory.createImportEqualsDeclaration( /*modifiers*/ + void 0, /*isTypeOnly*/ + false, factory.createIdentifier(localName), isLocalImport ? symbolToName(target, context, 67108863 /* All */, /*expectsIdentifier*/ + false) : factory.createExternalModuleReference(factory.createStringLiteral(getSpecifierForModuleSymbol(target, context)))), isLocalImport ? modifierFlags : 0 /* None */); + break; case 270 /* NamespaceExportDeclaration */: addResult(factory.createNamespaceExportDeclaration(idText(node.name)), 0 /* None */); break; - case 273 /* ImportClause */: { - const generatedSpecifier = getSpecifierForModuleSymbol(target.parent || target, context); - const specifier2 = bundled ? factory.createStringLiteral(generatedSpecifier) : node.parent.moduleSpecifier; - addResult( - factory.createImportDeclaration( - /*modifiers*/ - void 0, - factory.createImportClause( - /*isTypeOnly*/ - false, - factory.createIdentifier(localName), - /*namedBindings*/ - void 0 - ), - specifier2, - node.parent.attributes - ), - 0 /* None */ - ); - break; - } - case 274 /* NamespaceImport */: { - const generatedSpecifier = getSpecifierForModuleSymbol(target.parent || target, context); - const specifier2 = bundled ? factory.createStringLiteral(generatedSpecifier) : node.parent.parent.moduleSpecifier; - addResult( - factory.createImportDeclaration( - /*modifiers*/ - void 0, - factory.createImportClause( - /*isTypeOnly*/ - false, - /*name*/ - void 0, - factory.createNamespaceImport(factory.createIdentifier(localName)) - ), - specifier2, - node.parent.attributes - ), - 0 /* None */ - ); - break; - } + case 273 /* ImportClause */: + { + const generatedSpecifier = getSpecifierForModuleSymbol(target.parent || target, context); + const specifier2 = bundled ? factory.createStringLiteral(generatedSpecifier) : node.parent.moduleSpecifier; + addResult(factory.createImportDeclaration( /*modifiers*/ + void 0, factory.createImportClause( /*isTypeOnly*/ + false, factory.createIdentifier(localName), /*namedBindings*/ + void 0), specifier2, node.parent.attributes), 0 /* None */); + + break; + } + case 274 /* NamespaceImport */: + { + const generatedSpecifier = getSpecifierForModuleSymbol(target.parent || target, context); + const specifier2 = bundled ? factory.createStringLiteral(generatedSpecifier) : node.parent.parent.moduleSpecifier; + addResult(factory.createImportDeclaration( /*modifiers*/ + void 0, factory.createImportClause( /*isTypeOnly*/ + false, /*name*/ + void 0, factory.createNamespaceImport(factory.createIdentifier(localName))), specifier2, node.parent.attributes), 0 /* None */); + + break; + } case 280 /* NamespaceExport */: - addResult( - factory.createExportDeclaration( - /*modifiers*/ - void 0, - /*isTypeOnly*/ - false, - factory.createNamespaceExport(factory.createIdentifier(localName)), - factory.createStringLiteral(getSpecifierForModuleSymbol(target, context)) - ), - 0 /* None */ - ); + addResult(factory.createExportDeclaration( /*modifiers*/ + void 0, /*isTypeOnly*/ + false, factory.createNamespaceExport(factory.createIdentifier(localName)), factory.createStringLiteral(getSpecifierForModuleSymbol(target, context))), 0 /* None */); + break; - case 276 /* ImportSpecifier */: { - const generatedSpecifier = getSpecifierForModuleSymbol(target.parent || target, context); - const specifier2 = bundled ? factory.createStringLiteral(generatedSpecifier) : node.parent.parent.parent.moduleSpecifier; - addResult( - factory.createImportDeclaration( - /*modifiers*/ - void 0, - factory.createImportClause( - /*isTypeOnly*/ - false, - /*name*/ - void 0, - factory.createNamedImports([ - factory.createImportSpecifier( - /*isTypeOnly*/ - false, - localName !== verbatimTargetName ? factory.createIdentifier(verbatimTargetName) : void 0, - factory.createIdentifier(localName) - ) - ]) - ), - specifier2, - node.parent.parent.parent.attributes - ), - 0 /* None */ - ); - break; - } + case 276 /* ImportSpecifier */: + { + const generatedSpecifier = getSpecifierForModuleSymbol(target.parent || target, context); + const specifier2 = bundled ? factory.createStringLiteral(generatedSpecifier) : node.parent.parent.parent.moduleSpecifier; + addResult(factory.createImportDeclaration( /*modifiers*/ + void 0, factory.createImportClause( /*isTypeOnly*/ + false, /*name*/ + void 0, factory.createNamedImports([factory.createImportSpecifier( /*isTypeOnly*/ + false, localName !== verbatimTargetName ? factory.createIdentifier(verbatimTargetName) : void 0, factory.createIdentifier(localName))])), specifier2, node.parent.parent.parent.attributes), 0 /* None */); + + break; + } case 281 /* ExportSpecifier */: const specifier = node.parent.parent.moduleSpecifier; - serializeExportSpecifier( - unescapeLeadingUnderscores(symbol.escapedName), - specifier ? verbatimTargetName : targetName, - specifier && isStringLiteralLike(specifier) ? factory.createStringLiteral(specifier.text) : void 0 - ); + serializeExportSpecifier(unescapeLeadingUnderscores(symbol.escapedName), specifier ? verbatimTargetName : targetName, specifier && isStringLiteralLike(specifier) ? factory.createStringLiteral(specifier.text) : void 0); break; case 277 /* ExportAssignment */: serializeMaybeAliasAssignment(symbol); @@ -53276,23 +49763,12 @@ ${lanes.join("\n")} } } function serializeExportSpecifier(localName, targetName, specifier) { - addResult( - factory.createExportDeclaration( - /*modifiers*/ - void 0, - /*isTypeOnly*/ - false, - factory.createNamedExports([factory.createExportSpecifier( - /*isTypeOnly*/ - false, - localName !== targetName ? targetName : void 0, - localName - )]), - specifier - ), - 0 /* None */ - ); + addResult(factory.createExportDeclaration( /*modifiers*/ + void 0, /*isTypeOnly*/ + false, factory.createNamedExports([factory.createExportSpecifier( /*isTypeOnly*/ + false, localName !== targetName ? targetName : void 0, localName)]), specifier), 0 /* None */); } + function serializeMaybeAliasAssignment(symbol) { var _a2; if (symbol.flags & 4194304 /* Prototype */) { @@ -53303,35 +49779,22 @@ ${lanes.join("\n")} const isDefault = name === "default" /* Default */; const isExportAssignmentCompatibleSymbolName = isExportEquals || isDefault; const aliasDecl = symbol.declarations && getDeclarationOfAliasSymbol(symbol); - const target = aliasDecl && getTargetOfAliasDeclaration( - aliasDecl, - /*dontRecursivelyResolve*/ - true - ); - if (target && length(target.declarations) && some(target.declarations, (d) => getSourceFileOfNode(d) === getSourceFileOfNode(enclosingDeclaration))) { + const target = aliasDecl && getTargetOfAliasDeclaration(aliasDecl, /*dontRecursivelyResolve*/ + true); + if (target && length(target.declarations) && some(target.declarations, d => getSourceFileOfNode(d) === getSourceFileOfNode(enclosingDeclaration))) { const expr = aliasDecl && (isExportAssignment(aliasDecl) || isBinaryExpression(aliasDecl) ? getExportAssignmentExpression(aliasDecl) : getPropertyAssignmentAliasLikeExpression(aliasDecl)); const first2 = expr && isEntityNameExpression(expr) ? getFirstNonModuleExportsIdentifier(expr) : void 0; - const referenced = first2 && resolveEntityName( - first2, - 67108863 /* All */, - /*ignoreErrors*/ - true, - /*dontResolveAlias*/ - true, - enclosingDeclaration - ); + const referenced = first2 && resolveEntityName(first2, 67108863 /* All */, /*ignoreErrors*/ + true, /*dontResolveAlias*/ + true, enclosingDeclaration); if (referenced || target) { includePrivateSymbol(referenced || target); } const prevDisableTrackSymbol = context.tracker.disableTrackSymbol; context.tracker.disableTrackSymbol = true; if (isExportAssignmentCompatibleSymbolName) { - results.push(factory.createExportAssignment( - /*modifiers*/ - void 0, - isExportEquals, - symbolToExpression(target, context, 67108863 /* All */) - )); + results.push(factory.createExportAssignment( /*modifiers*/ + void 0, isExportEquals, symbolToExpression(target, context, 67108863 /* All */))); } else { if (first2 === expr && first2) { serializeExportSpecifier(name, idText(first2)); @@ -53339,23 +49802,11 @@ ${lanes.join("\n")} serializeExportSpecifier(name, getInternalSymbolName(target, symbolName(target))); } else { const varName = getUnusedName(name, symbol); - addResult( - factory.createImportEqualsDeclaration( - /*modifiers*/ - void 0, - /*isTypeOnly*/ - false, - factory.createIdentifier(varName), - symbolToName( - target, - context, - 67108863 /* All */, - /*expectsIdentifier*/ - false - ) - ), - 0 /* None */ - ); + addResult(factory.createImportEqualsDeclaration( /*modifiers*/ + void 0, /*isTypeOnly*/ + false, factory.createIdentifier(varName), symbolToName(target, context, 67108863 /* All */, /*expectsIdentifier*/ + false)), 0 /* None */); + serializeExportSpecifier(name, varName); } } @@ -53368,30 +49819,15 @@ ${lanes.join("\n")} serializeAsFunctionNamespaceMerge(typeToSerialize, symbol, varName, isExportAssignmentCompatibleSymbolName ? 0 /* None */ : 32 /* Export */); } else { const flags = ((_a2 = context.enclosingDeclaration) == null ? void 0 : _a2.kind) === 267 /* ModuleDeclaration */ && (!(symbol.flags & 98304 /* Accessor */) || symbol.flags & 65536 /* SetAccessor */) ? 1 /* Let */ : 2 /* Const */; - const statement = factory.createVariableStatement( - /*modifiers*/ - void 0, - factory.createVariableDeclarationList([ - factory.createVariableDeclaration( - varName, - /*exclamationToken*/ - void 0, - serializeTypeForDeclaration(context, typeToSerialize, symbol, enclosingDeclaration, includePrivateSymbol, bundled) - ) - ], flags) - ); - addResult( - statement, - target && target.flags & 4 /* Property */ && target.escapedName === "export=" /* ExportEquals */ ? 128 /* Ambient */ : name === varName ? 32 /* Export */ : 0 /* None */ - ); + const statement = factory.createVariableStatement( /*modifiers*/ + void 0, factory.createVariableDeclarationList([factory.createVariableDeclaration(varName, /*exclamationToken*/ + void 0, serializeTypeForDeclaration(context, typeToSerialize, symbol, enclosingDeclaration, includePrivateSymbol, bundled))], flags)); + addResult(statement, target && target.flags & 4 /* Property */ && target.escapedName === "export=" /* ExportEquals */ ? 128 /* Ambient */ : name === varName ? 32 /* Export */ : 0 /* None */); } + if (isExportAssignmentCompatibleSymbolName) { - results.push(factory.createExportAssignment( - /*modifiers*/ - void 0, - isExportEquals, - factory.createIdentifier(varName) - )); + results.push(factory.createExportAssignment( /*modifiers*/ + void 0, isExportEquals, factory.createIdentifier(varName))); return true; } else if (name !== varName) { serializeExportSpecifier(name, varName); @@ -53402,9 +49838,11 @@ ${lanes.join("\n")} } function isTypeRepresentableAsFunctionNamespaceMerge(typeToSerialize, hostSymbol) { const ctxSrc = getSourceFileOfNode(context.enclosingDeclaration); - return getObjectFlags(typeToSerialize) & (16 /* Anonymous */ | 32 /* Mapped */) && !length(getIndexInfosOfType(typeToSerialize)) && !isClassInstanceSide(typeToSerialize) && // While a class instance is potentially representable as a NS, prefer printing a reference to the instance type and serializing the class - !!(length(filter(getPropertiesOfType(typeToSerialize), isNamespaceMember)) || length(getSignaturesOfType(typeToSerialize, 0 /* Call */))) && !length(getSignaturesOfType(typeToSerialize, 1 /* Construct */)) && // TODO: could probably serialize as function + ns + class, now that that's OK - !getDeclarationWithTypeAnnotation(hostSymbol, enclosingDeclaration) && !(typeToSerialize.symbol && some(typeToSerialize.symbol.declarations, (d) => getSourceFileOfNode(d) !== ctxSrc)) && !some(getPropertiesOfType(typeToSerialize), (p) => isLateBoundName(p.escapedName)) && !some(getPropertiesOfType(typeToSerialize), (p) => some(p.declarations, (d) => getSourceFileOfNode(d) !== ctxSrc)) && every(getPropertiesOfType(typeToSerialize), (p) => { + return getObjectFlags(typeToSerialize) & (16 /* Anonymous */ | 32 /* Mapped */) && !length(getIndexInfosOfType(typeToSerialize)) && !isClassInstanceSide(typeToSerialize) && + // While a class instance is potentially representable as a NS, prefer printing a reference to the instance type and serializing the class + !!(length(filter(getPropertiesOfType(typeToSerialize), isNamespaceMember)) || length(getSignaturesOfType(typeToSerialize, 0 /* Call */))) && !length(getSignaturesOfType(typeToSerialize, 1 /* Construct */)) && + // TODO: could probably serialize as function + ns + class, now that that's OK + !getDeclarationWithTypeAnnotation(hostSymbol, enclosingDeclaration) && !(typeToSerialize.symbol && some(typeToSerialize.symbol.declarations, d => getSourceFileOfNode(d) !== ctxSrc)) && !some(getPropertiesOfType(typeToSerialize), p => isLateBoundName(p.escapedName)) && !some(getPropertiesOfType(typeToSerialize), p => some(p.declarations, d => getSourceFileOfNode(d) !== ctxSrc)) && every(getPropertiesOfType(typeToSerialize), p => { if (!isIdentifierText(symbolName(p), languageVersion)) { return false; } @@ -53431,12 +49869,12 @@ ${lanes.join("\n")} if (p.flags & 98304 /* Accessor */ && useAccessors) { const result = []; if (p.flags & 65536 /* SetAccessor */) { - const setter = p.declarations && forEach(p.declarations, (d) => { + const setter = p.declarations && forEach(p.declarations, d => { if (d.kind === 178 /* SetAccessor */) { return d; } if (isCallExpression(d) && isBindableObjectDefinePropertyCall(d)) { - return forEach(d.arguments[2].properties, (propDecl) => { + return forEach(d.arguments[2].properties, propDecl => { const id = getNameOfDeclaration(propDecl); if (!!id && isIdentifier(id) && idText(id) === "set") { return propDecl; @@ -53446,85 +49884,40 @@ ${lanes.join("\n")} }); Debug.assert(!!setter); const paramSymbol = isFunctionLikeDeclaration(setter) ? getSignatureFromDeclaration(setter).parameters[0] : void 0; - result.push(setTextRange( - factory.createSetAccessorDeclaration( - factory.createModifiersFromModifierFlags(flag), - name, - [factory.createParameterDeclaration( - /*modifiers*/ - void 0, - /*dotDotDotToken*/ - void 0, - paramSymbol ? parameterToParameterDeclarationName(paramSymbol, getEffectiveParameterDeclaration(paramSymbol), context) : "value", - /*questionToken*/ - void 0, - isPrivate ? void 0 : serializeTypeForDeclaration(context, getTypeOfSymbol(p), p, enclosingDeclaration, includePrivateSymbol, bundled) - )], - /*body*/ - void 0 - ), - ((_b = p.declarations) == null ? void 0 : _b.find(isSetAccessor)) || firstPropertyLikeDecl - )); + result.push(setTextRange(factory.createSetAccessorDeclaration(factory.createModifiersFromModifierFlags(flag), name, [factory.createParameterDeclaration( /*modifiers*/ + void 0, /*dotDotDotToken*/ + void 0, paramSymbol ? parameterToParameterDeclarationName(paramSymbol, getEffectiveParameterDeclaration(paramSymbol), context) : "value", /*questionToken*/ + void 0, isPrivate ? void 0 : serializeTypeForDeclaration(context, getTypeOfSymbol(p), p, enclosingDeclaration, includePrivateSymbol, bundled))], /*body*/ + void 0), ((_b = p.declarations) == null ? void 0 : _b.find(isSetAccessor)) || firstPropertyLikeDecl)); } if (p.flags & 32768 /* GetAccessor */) { const isPrivate2 = modifierFlags & 2 /* Private */; - result.push(setTextRange( - factory.createGetAccessorDeclaration( - factory.createModifiersFromModifierFlags(flag), - name, - [], - isPrivate2 ? void 0 : serializeTypeForDeclaration(context, getTypeOfSymbol(p), p, enclosingDeclaration, includePrivateSymbol, bundled), - /*body*/ - void 0 - ), - ((_c = p.declarations) == null ? void 0 : _c.find(isGetAccessor)) || firstPropertyLikeDecl - )); + result.push(setTextRange(factory.createGetAccessorDeclaration(factory.createModifiersFromModifierFlags(flag), name, [], isPrivate2 ? void 0 : serializeTypeForDeclaration(context, getTypeOfSymbol(p), p, enclosingDeclaration, includePrivateSymbol, bundled), /*body*/ + void 0), ((_c = p.declarations) == null ? void 0 : _c.find(isGetAccessor)) || firstPropertyLikeDecl)); } return result; } else if (p.flags & (4 /* Property */ | 3 /* Variable */ | 98304 /* Accessor */)) { - return setTextRange( - createProperty2( - factory.createModifiersFromModifierFlags((isReadonlySymbol(p) ? 8 /* Readonly */ : 0) | flag), - name, - p.flags & 16777216 /* Optional */ ? factory.createToken(58 /* QuestionToken */) : void 0, - isPrivate ? void 0 : serializeTypeForDeclaration(context, getWriteTypeOfSymbol(p), p, enclosingDeclaration, includePrivateSymbol, bundled), - // TODO: https://github.com/microsoft/TypeScript/pull/32372#discussion_r328386357 - // interface members can't have initializers, however class members _can_ - /*initializer*/ - void 0 - ), - ((_d = p.declarations) == null ? void 0 : _d.find(or(isPropertyDeclaration, isVariableDeclaration))) || firstPropertyLikeDecl - ); + return setTextRange(createProperty2(factory.createModifiersFromModifierFlags((isReadonlySymbol(p) ? 8 /* Readonly */ : 0) | flag), name, p.flags & 16777216 /* Optional */ ? factory.createToken(58 /* QuestionToken */) : void 0, isPrivate ? void 0 : serializeTypeForDeclaration(context, getWriteTypeOfSymbol(p), p, enclosingDeclaration, includePrivateSymbol, bundled), + // TODO: https://github.com/microsoft/TypeScript/pull/32372#discussion_r328386357 + // interface members can't have initializers, however class members _can_ + /*initializer*/ + void 0), ((_d = p.declarations) == null ? void 0 : _d.find(or(isPropertyDeclaration, isVariableDeclaration))) || firstPropertyLikeDecl); } if (p.flags & (8192 /* Method */ | 16 /* Function */)) { const type = getTypeOfSymbol(p); const signatures = getSignaturesOfType(type, 0 /* Call */); if (flag & 2 /* Private */) { - return setTextRange( - createProperty2( - factory.createModifiersFromModifierFlags((isReadonlySymbol(p) ? 8 /* Readonly */ : 0) | flag), - name, - p.flags & 16777216 /* Optional */ ? factory.createToken(58 /* QuestionToken */) : void 0, - /*type*/ - void 0, - /*initializer*/ - void 0 - ), - ((_e = p.declarations) == null ? void 0 : _e.find(isFunctionLikeDeclaration)) || signatures[0] && signatures[0].declaration || p.declarations && p.declarations[0] - ); + return setTextRange(createProperty2(factory.createModifiersFromModifierFlags((isReadonlySymbol(p) ? 8 /* Readonly */ : 0) | flag), name, p.flags & 16777216 /* Optional */ ? factory.createToken(58 /* QuestionToken */) : void 0, /*type*/ + void 0, /*initializer*/ + void 0), ((_e = p.declarations) == null ? void 0 : _e.find(isFunctionLikeDeclaration)) || signatures[0] && signatures[0].declaration || p.declarations && p.declarations[0]); } const results2 = []; for (const sig of signatures) { - const decl = signatureToSignatureDeclarationHelper( - sig, - methodKind, - context, - { - name, - questionToken: p.flags & 16777216 /* Optional */ ? factory.createToken(58 /* QuestionToken */) : void 0, - modifiers: flag ? factory.createModifiersFromModifierFlags(flag) : void 0 - } - ); + const decl = signatureToSignatureDeclarationHelper(sig, methodKind, context, { + name, + questionToken: p.flags & 16777216 /* Optional */ ? factory.createToken(58 /* QuestionToken */) : void 0, + modifiers: flag ? factory.createModifiersFromModifierFlags(flag) : void 0 + }); const location = sig.declaration && isPrototypePropertyAssignment(sig.declaration.parent) ? sig.declaration.parent : sig.declaration; results2.push(setTextRange(decl, location)); } @@ -53534,38 +49927,27 @@ ${lanes.join("\n")} }; } function serializePropertySymbolForInterface(p, baseType) { - return serializePropertySymbolForInterfaceWorker( - p, - /*isStatic*/ - false, - baseType - ); + return serializePropertySymbolForInterfaceWorker(p, /*isStatic*/ + false, baseType); } function serializeSignatures(kind, input, baseType, outputKind) { const signatures = getSignaturesOfType(input, kind); if (kind === 1 /* Construct */) { - if (!baseType && every(signatures, (s) => length(s.parameters) === 0)) { + if (!baseType && every(signatures, s => length(s.parameters) === 0)) { return []; } if (baseType) { const baseSigs = getSignaturesOfType(baseType, 1 /* Construct */); - if (!length(baseSigs) && every(signatures, (s) => length(s.parameters) === 0)) { + if (!length(baseSigs) && every(signatures, s => length(s.parameters) === 0)) { return []; } if (baseSigs.length === signatures.length) { let failed = false; for (let i = 0; i < baseSigs.length; i++) { - if (!compareSignaturesIdentical( - signatures[i], - baseSigs[i], - /*partialMatch*/ - false, - /*ignoreThisTypes*/ - false, - /*ignoreReturnTypes*/ - true, - compareTypesIdentical - )) { + if (!compareSignaturesIdentical(signatures[i], baseSigs[i], /*partialMatch*/ + false, /*ignoreThisTypes*/ + false, /*ignoreReturnTypes*/ + true, compareTypesIdentical)) { failed = true; break; } @@ -53581,17 +49963,11 @@ ${lanes.join("\n")} privateProtected |= getSelectedEffectiveModifierFlags(s.declaration, 2 /* Private */ | 4 /* Protected */); } } + if (privateProtected) { - return [setTextRange( - factory.createConstructorDeclaration( - factory.createModifiersFromModifierFlags(privateProtected), - /*parameters*/ - [], - /*body*/ - void 0 - ), - signatures[0].declaration - )]; + return [setTextRange(factory.createConstructorDeclaration(factory.createModifiersFromModifierFlags(privateProtected), /*parameters*/ + [], /*body*/ + void 0), signatures[0].declaration)]; } } const results2 = []; @@ -53612,12 +49988,8 @@ ${lanes.join("\n")} } } } - results2.push(indexInfoToIndexSignatureDeclarationHelper( - info, - context, - /*typeNode*/ - void 0 - )); + results2.push(indexInfoToIndexSignatureDeclarationHelper(info, context, /*typeNode*/ + void 0)); } return results2; } @@ -53627,34 +49999,24 @@ ${lanes.join("\n")} return ref; } const tempName = getUnusedName(`${rootName}_base`); - const statement = factory.createVariableStatement( - /*modifiers*/ - void 0, - factory.createVariableDeclarationList([ - factory.createVariableDeclaration( - tempName, - /*exclamationToken*/ - void 0, - typeToTypeNodeHelper(staticType, context) - ) - ], 2 /* Const */) - ); + const statement = factory.createVariableStatement( /*modifiers*/ + void 0, factory.createVariableDeclarationList([factory.createVariableDeclaration(tempName, /*exclamationToken*/ + void 0, typeToTypeNodeHelper(staticType, context))], 2 /* Const */)); + addResult(statement, 0 /* None */); - return factory.createExpressionWithTypeArguments( - factory.createIdentifier(tempName), - /*typeArguments*/ - void 0 - ); + return factory.createExpressionWithTypeArguments(factory.createIdentifier(tempName), /*typeArguments*/ + void 0); } function trySerializeAsTypeReference(t, flags) { let typeArgs; let reference; if (t.target && isSymbolAccessibleByFlags(t.target.symbol, enclosingDeclaration, flags)) { - typeArgs = map(getTypeArguments(t), (t2) => typeToTypeNodeHelper(t2, context)); + typeArgs = map(getTypeArguments(t), t2 => typeToTypeNodeHelper(t2, context)); reference = symbolToExpression(t.target.symbol, context, 788968 /* Type */); } else if (t.symbol && isSymbolAccessibleByFlags(t.symbol, enclosingDeclaration, flags)) { reference = symbolToExpression(t.symbol, context, 788968 /* Type */); } + if (reference) { return factory.createExpressionWithTypeArguments(reference, typeArgs); } @@ -53665,11 +50027,8 @@ ${lanes.join("\n")} return ref; } if (t.symbol) { - return factory.createExpressionWithTypeArguments( - symbolToExpression(t.symbol, context, 788968 /* Type */), - /*typeArguments*/ - void 0 - ); + return factory.createExpressionWithTypeArguments(symbolToExpression(t.symbol, context, 788968 /* Type */), /*typeArguments*/ + void 0); } } function getUnusedName(input, symbol) { @@ -53725,21 +50084,14 @@ ${lanes.join("\n")} function typePredicateToString(typePredicate, enclosingDeclaration, flags = 16384 /* UseAliasDefinedOutsideCurrentScope */, writer) { return writer ? typePredicateToStringWorker(writer).getText() : usingSingleLineStringWriter(typePredicateToStringWorker); function typePredicateToStringWorker(writer2) { - const predicate = factory.createTypePredicateNode( - typePredicate.kind === 2 /* AssertsThis */ || typePredicate.kind === 3 /* AssertsIdentifier */ ? factory.createToken(131 /* AssertsKeyword */) : void 0, - typePredicate.kind === 1 /* Identifier */ || typePredicate.kind === 3 /* AssertsIdentifier */ ? factory.createIdentifier(typePredicate.parameterName) : factory.createThisTypeNode(), - typePredicate.type && nodeBuilder.typeToTypeNode(typePredicate.type, enclosingDeclaration, toNodeBuilderFlags(flags) | 70221824 /* IgnoreErrors */ | 512 /* WriteTypeParametersInQualifiedName */) - // TODO: GH#18217 + const predicate = factory.createTypePredicateNode(typePredicate.kind === 2 /* AssertsThis */ || typePredicate.kind === 3 /* AssertsIdentifier */ ? factory.createToken(131 /* AssertsKeyword */) : void 0, typePredicate.kind === 1 /* Identifier */ || typePredicate.kind === 3 /* AssertsIdentifier */ ? factory.createIdentifier(typePredicate.parameterName) : factory.createThisTypeNode(), typePredicate.type && nodeBuilder.typeToTypeNode(typePredicate.type, enclosingDeclaration, toNodeBuilderFlags(flags) | 70221824 /* IgnoreErrors */ | 512 /* WriteTypeParametersInQualifiedName */) + // TODO: GH#18217 ); + const printer = createPrinterWithRemoveComments(); const sourceFile = enclosingDeclaration && getSourceFileOfNode(enclosingDeclaration); - printer.writeNode( - 4 /* Unspecified */, - predicate, - /*sourceFile*/ - sourceFile, - writer2 - ); + printer.writeNode(4 /* Unspecified */, predicate, /*sourceFile*/ + sourceFile, writer2); return writer2; } } @@ -53764,10 +50116,8 @@ ${lanes.join("\n")} 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) { @@ -53817,14 +50167,17 @@ ${lanes.join("\n")} if ((_a = context == null ? void 0 : context.remappedSymbolReferences) == null ? void 0 : _a.has(getSymbolId(symbol))) { symbol = context.remappedSymbolReferences.get(getSymbolId(symbol)); } - if (context && symbol.escapedName === "default" /* Default */ && !(context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */) && // If it's not the first part of an entity name, it must print as `default` - (!(context.flags & 16777216 /* InInitialEntityName */) || // if the symbol is synthesized, it will only be referenced externally it must print as `default` - !symbol.declarations || // if not in the same binding context (source file, module declaration), it must print as `default` + if (context && symbol.escapedName === "default" /* Default */ && !(context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */) && ( + // If it's not the first part of an entity name, it must print as `default` + !(context.flags & 16777216 /* InInitialEntityName */) || + // if the symbol is synthesized, it will only be referenced externally it must print as `default` + !symbol.declarations || + // if not in the same binding context (source file, module declaration), it must print as `default` context.enclosingDeclaration && findAncestor(symbol.declarations[0], isDefaultBindingContext) !== findAncestor(context.enclosingDeclaration, isDefaultBindingContext))) { return "default"; } if (symbol.declarations && symbol.declarations.length) { - let declaration = firstDefined(symbol.declarations, (d) => getNameOfDeclaration(d) ? d : void 0); + let declaration = firstDefined(symbol.declarations, d => getNameOfDeclaration(d) ? d : void 0); const name2 = declaration && getNameOfDeclaration(declaration); if (declaration && name2) { if (isCallExpression(declaration) && isBindableObjectDefinePropertyCall(declaration)) { @@ -53940,29 +50293,23 @@ ${lanes.join("\n")} function collectLinkedAliases(node, setVisibility) { let exportSymbol; if (node.parent && node.parent.kind === 277 /* ExportAssignment */) { - exportSymbol = resolveName( - node, - node.escapedText, - 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, - /*nameNotFoundMessage*/ - void 0, - node, - /*isUse*/ - false - ); + exportSymbol = resolveName(node, node.escapedText, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ + void 0, node, /*isUse*/ + false); } else if (node.parent.kind === 281 /* ExportSpecifier */) { exportSymbol = getTargetOfExportSpecifier(node.parent, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); } + let result; let visited; if (exportSymbol) { - visited = /* @__PURE__ */ new Set(); + visited = /* @__PURE__ */new Set(); visited.add(getSymbolId(exportSymbol)); buildVisibleNodeList(exportSymbol.declarations); } return result; function buildVisibleNodeList(declarations) { - forEach(declarations, (declaration) => { + forEach(declarations, declaration => { const resultNode = getAnyImportSyntax(declaration) || declaration; if (setVisibility) { getNodeLinks(declaration).isVisible = true; @@ -53973,17 +50320,10 @@ ${lanes.join("\n")} if (isInternalModuleImportEqualsDeclaration(declaration)) { const internalModuleReference = declaration.moduleReference; const firstIdentifier = getFirstIdentifier(internalModuleReference); - const importSymbol = resolveName( - declaration, - firstIdentifier.escapedText, - 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */, - /*nameNotFoundMessage*/ - void 0, - /*nameArg*/ - void 0, - /*isUse*/ - false - ); + const importSymbol = resolveName(declaration, firstIdentifier.escapedText, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */, /*nameNotFoundMessage*/ + void 0, /*nameArg*/ + void 0, /*isUse*/ + false); if (importSymbol && visited) { if (tryAddToSet(visited, getSymbolId(importSymbol))) { buildVisibleNodeList(importSymbol.declarations); @@ -53996,17 +50336,17 @@ ${lanes.join("\n")} function pushTypeResolution(target, propertyName) { const resolutionCycleStartIndex = findResolutionCycleStartIndex(target, propertyName); if (resolutionCycleStartIndex >= 0) { - const { length: length2 } = resolutionTargets; + const { + length: length2 + } = resolutionTargets; for (let i = resolutionCycleStartIndex; i < length2; i++) { resolutionResults[i] = false; } return false; } resolutionTargets.push(target); - resolutionResults.push( - /*items*/ - true - ); + resolutionResults.push( /*items*/ + true); resolutionPropertyNames.push(propertyName); return true; } @@ -54052,7 +50392,7 @@ ${lanes.join("\n")} return resolutionResults.pop(); } function getDeclarationContainer(node) { - return findAncestor(getRootDeclaration(node), (node2) => { + return findAncestor(getRootDeclaration(node), node2 => { switch (node2.kind) { case 260 /* VariableDeclaration */: case 261 /* VariableDeclarationList */: @@ -54068,7 +50408,7 @@ ${lanes.join("\n")} } function getTypeOfPrototypeProperty(prototype) { const classType = getDeclaredTypeOfSymbol(getParentOfSymbol(prototype)); - return classType.typeParameters ? createTypeReference(classType, map(classType.typeParameters, (_) => anyType)) : classType; + return classType.typeParameters ? createTypeReference(classType, map(classType.typeParameters, _ => anyType)) : classType; } function getTypeOfPropertyOfType(type, name) { const prop = getPropertyOfType(type, name); @@ -54077,13 +50417,9 @@ ${lanes.join("\n")} function getTypeOfPropertyOrIndexSignatureOfType(type, name) { var _a; let propType; - return getTypeOfPropertyOfType(type, name) || (propType = (_a = getApplicableIndexInfoForName(type, name)) == null ? void 0 : _a.type) && addOptionality( - propType, - /*isProperty*/ - true, - /*isOptional*/ - true - ); + return getTypeOfPropertyOfType(type, name) || (propType = (_a = getApplicableIndexInfoForName(type, name)) == null ? void 0 : _a.type) && addOptionality(propType, /*isProperty*/ + true, /*isOptional*/ + true); } function isTypeAny(type) { return type && (type.flags & 1 /* Any */) !== 0; @@ -54093,28 +50429,20 @@ ${lanes.join("\n")} } function getTypeForBindingElementParent(node, checkMode) { if (checkMode !== 0 /* Normal */) { - return getTypeForVariableLikeDeclaration( - node, - /*includeOptionality*/ - false, - checkMode - ); + return getTypeForVariableLikeDeclaration(node, /*includeOptionality*/ + false, checkMode); } const symbol = getSymbolOfDeclaration(node); - return symbol && getSymbolLinks(symbol).type || getTypeForVariableLikeDeclaration( - node, - /*includeOptionality*/ - false, - checkMode - ); + return symbol && getSymbolLinks(symbol).type || getTypeForVariableLikeDeclaration(node, /*includeOptionality*/ + false, checkMode); } function getRestType(source, properties, symbol) { - source = filterType(source, (t) => !(t.flags & 98304 /* Nullable */)); + source = filterType(source, t => !(t.flags & 98304 /* Nullable */)); if (source.flags & 131072 /* Never */) { return emptyObjectType; } if (source.flags & 1048576 /* Union */) { - return mapType(source, (t) => getRestType(t, properties, symbol)); + return mapType(source, t => getRestType(t, properties, symbol)); } let omitKeyType = getUnionType(map(properties, getLiteralTypeFromPropertyName)); const spreadableProperties = []; @@ -54142,11 +50470,8 @@ ${lanes.join("\n")} } const members = createSymbolTable(); for (const prop of spreadableProperties) { - members.set(prop.escapedName, getSpreadSymbol( - prop, - /*readonly*/ - false - )); + members.set(prop.escapedName, getSpreadSymbol(prop, /*readonly*/ + false)); } const result = createAnonymousType(symbol, members, emptyArray, emptyArray, getIndexInfosOfType(source)); result.objectFlags |= 4194304 /* ObjectRestType */; @@ -54155,10 +50480,12 @@ ${lanes.join("\n")} function isGenericTypeWithUndefinedConstraint(type) { return !!(type.flags & 465829888 /* Instantiable */) && maybeTypeOfKind(getBaseConstraintOfType(type) || unknownType, 32768 /* Undefined */); } + function getNonUndefinedType(type) { - const typeOrConstraint = someType(type, isGenericTypeWithUndefinedConstraint) ? mapType(type, (t) => t.flags & 465829888 /* Instantiable */ ? getBaseConstraintOrType(t) : t) : type; + const typeOrConstraint = someType(type, isGenericTypeWithUndefinedConstraint) ? mapType(type, t => t.flags & 465829888 /* Instantiable */ ? getBaseConstraintOrType(t) : t) : type; return getTypeWithFacts(typeOrConstraint, 524288 /* NEUndefined */); } + function getFlowTypeOfDestructuring(node, declaredType) { const reference = getSyntheticElementAccess(node); return reference ? getFlowTypeOfReference(reference, declaredType) : declaredType; @@ -54212,12 +50539,8 @@ ${lanes.join("\n")} function getTypeForBindingElement(declaration) { const checkMode = declaration.dotDotDotToken ? 32 /* RestBindingElement */ : 0 /* Normal */; const parentType = getTypeForBindingElementParent(declaration.parent.parent, checkMode); - return parentType && getBindingElementTypeFromParentType( - declaration, - parentType, - /*noTupleBoundsCheck*/ - false - ); + return parentType && getBindingElementTypeFromParentType(declaration, parentType, /*noTupleBoundsCheck*/ + false); } function getBindingElementTypeFromParentType(declaration, parentType, noTupleBoundsCheck) { if (isTypeAny(parentType)) { @@ -54229,6 +50552,7 @@ ${lanes.join("\n")} } else if (strictNullChecks && pattern.parent.initializer && !hasTypeFacts(getTypeOfInitializer(pattern.parent.initializer), 65536 /* EQUndefined */)) { parentType = getTypeWithFacts(parentType, 524288 /* NEUndefined */); } + let type; if (pattern.kind === 206 /* ObjectBindingPattern */) { if (declaration.dotDotDotToken) { @@ -54254,8 +50578,8 @@ ${lanes.join("\n")} const elementType = checkIteratedTypeOrElementType(65 /* Destructuring */ | (declaration.dotDotDotToken ? 0 : 128 /* PossiblyOutOfBounds */), parentType, undefinedType, pattern); const index = pattern.elements.indexOf(declaration); if (declaration.dotDotDotToken) { - const baseConstraint = mapType(parentType, (t) => t.flags & 58982400 /* InstantiableNonPrimitive */ ? getBaseConstraintOrType(t) : t); - type = everyType(baseConstraint, isTupleType) ? mapType(baseConstraint, (t) => sliceTupleType(t, index)) : createArrayType(elementType); + const baseConstraint = mapType(parentType, t => t.flags & 58982400 /* InstantiableNonPrimitive */ ? getBaseConstraintOrType(t) : t); + type = everyType(baseConstraint, isTupleType) ? mapType(baseConstraint, t => sliceTupleType(t, index)) : createArrayType(elementType); } else if (isArrayLikeType(parentType)) { const indexType = getNumberLiteralType(index); const accessFlags = 32 /* ExpressionPosition */ | (noTupleBoundsCheck || hasDefaultValue(declaration) ? 16 /* NoTupleBoundsCheck */ : 0); @@ -54273,6 +50597,7 @@ ${lanes.join("\n")} } return widenTypeInferredFromInitializer(declaration, getUnionType([getNonUndefinedType(type), checkDeclarationInitializer(declaration, 0 /* Normal */)], 2 /* Subtype */)); } + function getTypeForDeclarationFromJSDocComment(declaration) { const jsdocType = getJSDocType(declaration); if (jsdocType) { @@ -54281,19 +50606,13 @@ ${lanes.join("\n")} return void 0; } function isNullOrUndefined3(node) { - const expr = skipParentheses( - node, - /*excludeJSDocTypeAssertions*/ - true - ); + const expr = skipParentheses(node, /*excludeJSDocTypeAssertions*/ + true); return expr.kind === 106 /* NullKeyword */ || expr.kind === 80 /* Identifier */ && getResolvedSymbol(expr) === undefinedSymbol; } function isEmptyArrayLiteral2(node) { - const expr = skipParentheses( - node, - /*excludeJSDocTypeAssertions*/ - true - ); + const expr = skipParentheses(node, /*excludeJSDocTypeAssertions*/ + true); return expr.kind === 209 /* ArrayLiteralExpression */ && expr.elements.length === 0; } function addOptionality(type, isProperty = false, isOptional = true) { @@ -54301,11 +50620,8 @@ ${lanes.join("\n")} } function getTypeForVariableLikeDeclaration(declaration, includeOptionality, checkMode) { if (isVariableDeclaration(declaration) && declaration.parent.parent.kind === 249 /* ForInStatement */) { - const indexType = getIndexType(getNonNullableTypeIfNeeded(checkExpression( - declaration.parent.parent.expression, - /*checkMode*/ - checkMode - ))); + const indexType = getIndexType(getNonNullableTypeIfNeeded(checkExpression(declaration.parent.parent.expression, /*checkMode*/ + checkMode))); return indexType.flags & (262144 /* TypeParameter */ | 4194304 /* Index */) ? getExtractStringType(indexType) : stringType; } if (isVariableDeclaration(declaration) && declaration.parent.parent.kind === 250 /* ForOfStatement */) { @@ -54350,16 +50666,11 @@ ${lanes.join("\n")} } } 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( - type, - /*isProperty*/ - false, - isOptional - ); + return addOptionality(type, /*isProperty*/ + false, isOptional); } } if (hasOnlyExpressionInitializer(declaration) && !!declaration.initializer) { @@ -54376,34 +50687,22 @@ ${lanes.join("\n")} if (!hasStaticModifier(declaration)) { const constructor = findConstructorDeclaration(declaration.parent); const type = constructor ? getFlowTypeInConstructor(declaration.symbol, constructor) : getEffectiveModifierFlags(declaration) & 128 /* Ambient */ ? getTypeOfPropertyInBaseClass(declaration.symbol) : void 0; - return type && addOptionality( - type, - /*isProperty*/ - true, - isOptional - ); + return type && addOptionality(type, /*isProperty*/ + true, isOptional); } else { const staticBlocks = filter(declaration.parent.members, isClassStaticBlockDeclaration); const type = staticBlocks.length ? getFlowTypeInStaticBlocks(declaration.symbol, staticBlocks) : getEffectiveModifierFlags(declaration) & 128 /* Ambient */ ? getTypeOfPropertyInBaseClass(declaration.symbol) : void 0; - return type && addOptionality( - type, - /*isProperty*/ - true, - isOptional - ); + return type && addOptionality(type, /*isProperty*/ + true, isOptional); } } if (isJsxAttribute(declaration)) { return trueType; } if (isBindingPattern(declaration.name)) { - return getTypeFromBindingPattern( - declaration.name, - /*includePatternInType*/ - false, - /*reportErrors*/ - true - ); + return getTypeFromBindingPattern(declaration.name, /*includePatternInType*/ + false, /*reportErrors*/ + true); } return void 0; } @@ -54412,13 +50711,8 @@ ${lanes.join("\n")} const links = getSymbolLinks(symbol); if (links.isConstructorDeclaredProperty === void 0) { links.isConstructorDeclaredProperty = false; - links.isConstructorDeclaredProperty = !!getDeclaringConstructor(symbol) && every(symbol.declarations, (declaration) => isBinaryExpression(declaration) && isPossiblyAliasedThisProperty(declaration) && (declaration.left.kind !== 212 /* ElementAccessExpression */ || isStringOrNumericLiteralLike(declaration.left.argumentExpression)) && !getAnnotatedTypeForAssignmentDeclaration( - /*declaredType*/ - void 0, - declaration, - symbol, - declaration - )); + links.isConstructorDeclaredProperty = !!getDeclaringConstructor(symbol) && every(symbol.declarations, declaration => isBinaryExpression(declaration) && isPossiblyAliasedThisProperty(declaration) && (declaration.left.kind !== 212 /* ElementAccessExpression */ || isStringOrNumericLiteralLike(declaration.left.argumentExpression)) && !getAnnotatedTypeForAssignmentDeclaration( /*declaredType*/ + void 0, declaration, symbol, declaration)); } return links.isConstructorDeclaredProperty; } @@ -54433,13 +50727,9 @@ ${lanes.join("\n")} return; } for (const declaration of symbol.declarations) { - const container = getThisContainer( - declaration, - /*includeArrowFunctions*/ - false, - /*includeClassComputedPropertyName*/ - false - ); + const container = getThisContainer(declaration, /*includeArrowFunctions*/ + false, /*includeClassComputedPropertyName*/ + false); if (container && (container.kind === 176 /* Constructor */ || isJSConstructor(container))) { return container; } @@ -54448,7 +50738,7 @@ ${lanes.join("\n")} function getFlowTypeFromCommonJSExport(symbol) { const file = getSourceFileOfNode(symbol.declarations[0]); const accessName = unescapeLeadingUnderscores(symbol.escapedName); - const areAllModuleExports = symbol.declarations.every((d) => isInJSFile(d) && isAccessExpression(d) && isModuleExportsAccessExpression(d.expression)); + const areAllModuleExports = symbol.declarations.every(d => isInJSFile(d) && isAccessExpression(d) && isModuleExportsAccessExpression(d.expression)); const reference = areAllModuleExports ? factory.createPropertyAccessExpression(factory.createPropertyAccessExpression(factory.createIdentifier("module"), factory.createIdentifier("exports")), accessName) : factory.createPropertyAccessExpression(factory.createIdentifier("exports"), accessName); if (areAllModuleExports) { setParent(reference.expression.expression, reference.expression); @@ -54545,17 +50835,13 @@ ${lanes.join("\n")} definedInConstructor = true; } } - const sourceTypes = some(constructorTypes, (t) => !!(t.flags & ~98304 /* Nullable */)) ? constructorTypes : types; + const sourceTypes = some(constructorTypes, t => !!(t.flags & ~98304 /* Nullable */)) ? constructorTypes : types; type = getUnionType(sourceTypes); } } - const widened = getWidenedType(addOptionality( - type, - /*isProperty*/ - false, - definedInMethod && !definedInConstructor - )); - if (symbol.valueDeclaration && isInJSFile(symbol.valueDeclaration) && filterType(widened, (t) => !!(t.flags & ~98304 /* Nullable */)) === neverType) { + const widened = getWidenedType(addOptionality(type, /*isProperty*/ + false, definedInMethod && !definedInConstructor)); + if (symbol.valueDeclaration && isInJSFile(symbol.valueDeclaration) && filterType(widened, t => !!(t.flags & ~98304 /* Nullable */)) === neverType) { reportImplicitAny(symbol.valueDeclaration, anyType); return anyType; } @@ -54590,13 +50876,8 @@ ${lanes.join("\n")} if (!declaredType) { return type; } else if (!isErrorType(declaredType) && !isErrorType(type) && !isTypeIdenticalTo(declaredType, type)) { - errorNextVariableOrPropertyDeclarationMustHaveSameType( - /*firstDeclaration*/ - void 0, - declaredType, - declaration, - type - ); + errorNextVariableOrPropertyDeclarationMustHaveSameType( /*firstDeclaration*/ + void 0, declaredType, declaration, type); } } if ((_a = symbol.parent) == null ? void 0 : _a.valueDeclaration) { @@ -54657,14 +50938,8 @@ ${lanes.join("\n")} if (s.valueDeclaration && exportedMember.valueDeclaration && getSourceFileOfNode(s.valueDeclaration) !== getSourceFileOfNode(exportedMember.valueDeclaration)) { const unescapedName = unescapeLeadingUnderscores(s.escapedName); const exportedMemberName = ((_a = tryCast(exportedMember.valueDeclaration, isNamedDeclaration)) == null ? void 0 : _a.name) || exportedMember.valueDeclaration; - addRelatedInfo( - error2(s.valueDeclaration, Diagnostics.Duplicate_identifier_0, unescapedName), - createDiagnosticForNode(exportedMemberName, Diagnostics._0_was_also_declared_here, unescapedName) - ); - addRelatedInfo( - error2(exportedMemberName, Diagnostics.Duplicate_identifier_0, unescapedName), - createDiagnosticForNode(s.valueDeclaration, Diagnostics._0_was_also_declared_here, unescapedName) - ); + addRelatedInfo(error2(s.valueDeclaration, Diagnostics.Duplicate_identifier_0, unescapedName), createDiagnosticForNode(exportedMemberName, Diagnostics._0_was_also_declared_here, unescapedName)); + addRelatedInfo(error2(exportedMemberName, Diagnostics.Duplicate_identifier_0, unescapedName), createDiagnosticForNode(s.valueDeclaration, Diagnostics._0_was_also_declared_here, unescapedName)); } const union = createSymbol(s.flags | exportedMember.flags, name); union.links.type = getUnionType([getTypeOfSymbol(s), getTypeOfSymbol(exportedMember)]); @@ -54678,14 +50953,9 @@ ${lanes.join("\n")} members.set(name, s); } }); - const result = createAnonymousType( - initialSize !== members.size ? void 0 : exportedType.symbol, - // Only set the type's symbol if it looks to be the same as the original type - members, - exportedType.callSignatures, - exportedType.constructSignatures, - exportedType.indexInfos - ); + const result = createAnonymousType(initialSize !== members.size ? void 0 : exportedType.symbol, + // Only set the type's symbol if it looks to be the same as the original type + members, exportedType.callSignatures, exportedType.constructSignatures, exportedType.indexInfos); if (initialSize === members.size) { if (type.aliasSymbol) { result.aliasSymbol = type.aliasSymbol; @@ -54701,6 +50971,7 @@ ${lanes.join("\n")} if (result.symbol && result.symbol.flags & 32 /* Class */ && type === getDeclaredTypeOfClassOrInterface(result.symbol)) { result.objectFlags |= 16777216 /* IsClassInstanceClone */; } + return result; } if (isEmptyArrayLiteralType(type)) { @@ -54710,16 +50981,12 @@ ${lanes.join("\n")} return type; } function containsSameNamedThisProperty(thisProperty, expression) { - return isPropertyAccessExpression(thisProperty) && thisProperty.expression.kind === 110 /* ThisKeyword */ && forEachChildRecursively(expression, (n) => isMatchingReference(thisProperty, n)); + return isPropertyAccessExpression(thisProperty) && thisProperty.expression.kind === 110 /* ThisKeyword */ && forEachChildRecursively(expression, n => isMatchingReference(thisProperty, n)); } function isDeclarationInConstructor(expression) { - const thisContainer = getThisContainer( - expression, - /*includeArrowFunctions*/ - false, - /*includeClassComputedPropertyName*/ - false - ); + const thisContainer = getThisContainer(expression, /*includeArrowFunctions*/ + false, /*includeClassComputedPropertyName*/ + false); return thisContainer.kind === 176 /* Constructor */ || thisContainer.kind === 262 /* FunctionDeclaration */ || thisContainer.kind === 218 /* FunctionExpression */ && !isPrototypePropertyAssignment(thisContainer.parent); } function getConstructorDefinedThisAssignmentTypes(types, declarations) { @@ -54732,13 +50999,9 @@ ${lanes.join("\n")} } function getTypeFromBindingElement(element, includePatternInType, reportErrors2) { if (element.initializer) { - const contextualType = isBindingPattern(element.name) ? getTypeFromBindingPattern( - element.name, - /*includePatternInType*/ - true, - /*reportErrors*/ - false - ) : unknownType; + const contextualType = isBindingPattern(element.name) ? getTypeFromBindingPattern(element.name, /*includePatternInType*/ + true, /*reportErrors*/ + false) : unknownType; return addOptionality(widenTypeInferredFromInitializer(element, checkDeclarationInitializer(element, 0 /* Normal */, contextualType))); } if (isBindingPattern(element.name)) { @@ -54753,15 +51016,11 @@ ${lanes.join("\n")} const members = createSymbolTable(); let stringIndexInfo; let objectFlags = 128 /* ObjectLiteral */ | 131072 /* ContainsObjectOrArrayLiteral */; - forEach(pattern.elements, (e) => { + forEach(pattern.elements, e => { const name = e.propertyName || e.name; if (e.dotDotDotToken) { - stringIndexInfo = createIndexInfo( - stringType, - anyType, - /*isReadonly*/ - false - ); + stringIndexInfo = createIndexInfo(stringType, anyType, /*isReadonly*/ + false); return; } const exprType = getLiteralTypeFromPropertyName(name); @@ -54776,19 +51035,14 @@ ${lanes.join("\n")} symbol.links.bindingElement = e; members.set(symbol.escapedName, symbol); }); - const result = createAnonymousType( - /*symbol*/ - void 0, - members, - emptyArray, - emptyArray, - stringIndexInfo ? [stringIndexInfo] : emptyArray - ); + const result = createAnonymousType( /*symbol*/ + void 0, members, emptyArray, emptyArray, stringIndexInfo ? [stringIndexInfo] : emptyArray); result.objectFlags |= objectFlags; if (includePatternInType) { result.pattern = pattern; result.objectFlags |= 131072 /* ContainsObjectOrArrayLiteral */; } + return result; } function getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors2) { @@ -54798,8 +51052,8 @@ ${lanes.join("\n")} if (elements.length === 0 || elements.length === 1 && restElement) { return languageVersion >= 2 /* ES2015 */ ? createIterableType(anyType) : anyArrayType; } - const elementTypes = map(elements, (e) => isOmittedExpression(e) ? anyType : getTypeFromBindingElement(e, includePatternInType, reportErrors2)); - const minLength = findLastIndex(elements, (e) => !(e === restElement || isOmittedExpression(e) || hasDefaultValue(e)), elements.length - 1) + 1; + const elementTypes = map(elements, e => isOmittedExpression(e) ? anyType : getTypeFromBindingElement(e, includePatternInType, reportErrors2)); + const minLength = findLastIndex(elements, e => !(e === restElement || isOmittedExpression(e) || hasDefaultValue(e)), elements.length - 1) + 1; const elementFlags = map(elements, (e, i) => e === restElement ? 4 /* Rest */ : i >= minLength ? 2 /* Optional */ : 1 /* Required */); let result = createTupleType(elementTypes, elementFlags); if (includePatternInType) { @@ -54807,25 +51061,20 @@ ${lanes.join("\n")} result.pattern = pattern; result.objectFlags |= 131072 /* ContainsObjectOrArrayLiteral */; } + return result; } function getTypeFromBindingPattern(pattern, includePatternInType = false, reportErrors2 = false) { return pattern.kind === 206 /* ObjectBindingPattern */ ? getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors2) : getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors2); } function getWidenedTypeForVariableLikeDeclaration(declaration, reportErrors2) { - return widenTypeForVariableLikeDeclaration(getTypeForVariableLikeDeclaration( - declaration, - /*includeOptionality*/ - true, - 0 /* Normal */ - ), declaration, reportErrors2); + return widenTypeForVariableLikeDeclaration(getTypeForVariableLikeDeclaration(declaration, /*includeOptionality*/ + true, 0 /* Normal */), declaration, reportErrors2); } function isGlobalSymbolConstructor(node) { const symbol = getSymbolOfNode(node); - const globalSymbol = getGlobalESSymbolConstructorTypeSymbol( - /*reportErrors*/ - false - ); + const globalSymbol = getGlobalESSymbolConstructorTypeSymbol( /*reportErrors*/ + false); return globalSymbol && symbol && symbol === globalSymbol; } function widenTypeForVariableLikeDeclaration(type, declaration, reportErrors2) { @@ -54897,12 +51146,9 @@ ${lanes.join("\n")} 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); @@ -54943,11 +51189,8 @@ ${lanes.join("\n")} } else if (isObjectLiteralMethod(declaration)) { type = tryGetTypeFromEffectiveTypeNode(declaration) || checkObjectLiteralMethod(declaration, 0 /* Normal */); } else if (isParameter(declaration) || isPropertyDeclaration(declaration) || isPropertySignature(declaration) || isVariableDeclaration(declaration) || isBindingElement(declaration) || isJSDocPropertyLikeTag(declaration)) { - type = getWidenedTypeForVariableLikeDeclaration( - declaration, - /*reportErrors*/ - true - ); + type = getWidenedTypeForVariableLikeDeclaration(declaration, /*reportErrors*/ + true); } else if (isEnumDeclaration(declaration)) { type = getTypeOfFuncClassEnumModule(symbol); } else if (isEnumMember(declaration)) { @@ -55000,11 +51243,8 @@ ${lanes.join("\n")} const getter = getDeclarationOfKind(symbol, 177 /* GetAccessor */); const setter = getDeclarationOfKind(symbol, 178 /* SetAccessor */); const accessor = tryCast(getDeclarationOfKind(symbol, 172 /* PropertyDeclaration */), isAutoAccessorPropertyDeclaration); - let type = getter && isInJSFile(getter) && getTypeForDeclarationFromJSDocComment(getter) || getAnnotatedAccessorType(getter) || getAnnotatedAccessorType(setter) || getAnnotatedAccessorType(accessor) || getter && getter.body && getReturnTypeFromBody(getter) || accessor && accessor.initializer && getWidenedTypeForVariableLikeDeclaration( - accessor, - /*reportErrors*/ - true - ); + let type = getter && isInJSFile(getter) && getTypeForDeclarationFromJSDocComment(getter) || getAnnotatedAccessorType(getter) || getAnnotatedAccessorType(setter) || getAnnotatedAccessorType(accessor) || getter && getter.body && getReturnTypeFromBody(getter) || accessor && accessor.initializer && getWidenedTypeForVariableLikeDeclaration(accessor, /*reportErrors*/ + true); if (!type) { if (setter && !isPrivateWithinAmbient(setter)) { errorOrSuggestion(noImplicitAny, setter, Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation, symbolToString(symbol)); @@ -55034,10 +51274,11 @@ ${lanes.join("\n")} function getWriteTypeOfAccessors(symbol) { const links = getSymbolLinks(symbol); if (!links.writeType) { + var _getDeclarationOfKind; if (!pushTypeResolution(symbol, 8 /* WriteType */)) { return errorType; } - const setter = getDeclarationOfKind(symbol, 178 /* SetAccessor */) ?? tryCast(getDeclarationOfKind(symbol, 172 /* PropertyDeclaration */), isAutoAccessorPropertyDeclaration); + const setter = (_getDeclarationOfKind = getDeclarationOfKind(symbol, 178 /* SetAccessor */)) !== null && _getDeclarationOfKind !== void 0 ? _getDeclarationOfKind : tryCast(getDeclarationOfKind(symbol, 172 /* PropertyDeclaration */), isAutoAccessorPropertyDeclaration); let writeType = getAnnotatedAccessorType(setter); if (!popTypeResolution()) { if (getAnnotatedAccessorTypeNode(setter)) { @@ -55051,17 +51292,14 @@ ${lanes.join("\n")} } function getBaseTypeVariableOfClass(symbol) { const baseConstructorType = getBaseConstructorTypeOfClass(getDeclaredTypeOfClassOrInterface(symbol)); - return baseConstructorType.flags & 8650752 /* TypeVariable */ ? baseConstructorType : baseConstructorType.flags & 2097152 /* Intersection */ ? find(baseConstructorType.types, (t) => !!(t.flags & 8650752 /* TypeVariable */)) : void 0; + return baseConstructorType.flags & 8650752 /* TypeVariable */ ? baseConstructorType : baseConstructorType.flags & 2097152 /* Intersection */ ? find(baseConstructorType.types, t => !!(t.flags & 8650752 /* TypeVariable */)) : void 0; } function getTypeOfFuncClassEnumModule(symbol) { let links = getSymbolLinks(symbol); const originalLinks = links; if (!links.type) { - const expando = symbol.valueDeclaration && getSymbolOfExpando( - symbol.valueDeclaration, - /*allowDeclaration*/ - false - ); + const expando = symbol.valueDeclaration && getSymbolOfExpando(symbol.valueDeclaration, /*allowDeclaration*/ + false); if (expando) { const merged = mergeJSSymbols(symbol, expando); if (merged) { @@ -55098,11 +51336,8 @@ ${lanes.join("\n")} const baseTypeVariable = getBaseTypeVariableOfClass(symbol); return baseTypeVariable ? getIntersectionType([type, baseTypeVariable]) : type; } else { - return strictNullChecks && symbol.flags & 16777216 /* Optional */ ? getOptionalType( - type, - /*isProperty*/ - true - ) : type; + return strictNullChecks && symbol.flags & 16777216 /* Optional */ ? getOptionalType(type, /*isProperty*/ + true) : type; } } function getTypeOfEnumMember(symbol) { @@ -55116,15 +51351,12 @@ ${lanes.join("\n")} return errorType; } const targetSymbol = resolveAlias(symbol); - const exportSymbol = symbol.declarations && getTargetOfAliasDeclaration( - getDeclarationOfAliasSymbol(symbol), - /*dontRecursivelyResolve*/ - true - ); - const declaredType = firstDefined(exportSymbol == null ? void 0 : exportSymbol.declarations, (d) => isExportAssignment(d) ? tryGetTypeFromEffectiveTypeNode(d) : void 0); + const exportSymbol = symbol.declarations && getTargetOfAliasDeclaration(getDeclarationOfAliasSymbol(symbol), /*dontRecursivelyResolve*/ + true); + const declaredType = firstDefined(exportSymbol == null ? void 0 : exportSymbol.declarations, d => isExportAssignment(d) ? tryGetTypeFromEffectiveTypeNode(d) : void 0); links.type = (exportSymbol == null ? void 0 : exportSymbol.declarations) && isDuplicatedCommonJSExport(exportSymbol.declarations) && symbol.declarations.length ? getFlowTypeFromCommonJSExport(exportSymbol) : isDuplicatedCommonJSExport(symbol.declarations) ? autoType : declaredType ? declaredType : getSymbolFlags(targetSymbol) & 111551 /* Value */ ? getTypeOfSymbol(targetSymbol) : errorType; if (!popTypeResolution()) { - reportCircularityError(exportSymbol ?? symbol); + reportCircularityError(exportSymbol !== null && exportSymbol !== void 0 ? exportSymbol : symbol); return links.type = errorType; } } @@ -55177,11 +51409,11 @@ ${lanes.join("\n")} function getWriteTypeOfSymbol(symbol) { const checkFlags = getCheckFlags(symbol); if (symbol.flags & 4 /* Property */) { - return checkFlags & 2 /* SyntheticProperty */ ? checkFlags & 65536 /* DeferredType */ ? getWriteTypeOfSymbolWithDeferredType(symbol) || getTypeOfSymbolWithDeferredType(symbol) : ( - // NOTE: cast to TransientSymbol should be safe because only TransientSymbols can have CheckFlags.SyntheticProperty - symbol.links.writeType || symbol.links.type - ) : removeMissingType(getTypeOfSymbol(symbol), !!(symbol.flags & 16777216 /* Optional */)); + return checkFlags & 2 /* SyntheticProperty */ ? checkFlags & 65536 /* DeferredType */ ? getWriteTypeOfSymbolWithDeferredType(symbol) || getTypeOfSymbolWithDeferredType(symbol) : + // NOTE: cast to TransientSymbol should be safe because only TransientSymbols can have CheckFlags.SyntheticProperty + symbol.links.writeType || symbol.links.type : removeMissingType(getTypeOfSymbol(symbol), !!(symbol.flags & 16777216 /* Optional */)); } + if (symbol.flags & 98304 /* Accessor */) { return checkFlags & 1 /* Instantiated */ ? getWriteTypeOfInstantiatedSymbol(symbol) : getWriteTypeOfAccessors(symbol); } @@ -55221,6 +51453,7 @@ ${lanes.join("\n")} function getNonMissingTypeOfSymbol(symbol) { return removeMissingType(getTypeOfSymbol(symbol), !!(symbol.flags & 16777216 /* Optional */)); } + function isReferenceToType2(type, target) { return type !== void 0 && target !== void 0 && (getObjectFlags(type) & 4 /* Reference */) !== 0 && type.target === target; } @@ -55252,7 +51485,7 @@ ${lanes.join("\n")} const assignmentKind = getAssignmentDeclarationKind(node); if (assignmentKind === 6 /* Prototype */ || assignmentKind === 3 /* PrototypeProperty */) { const symbol = getSymbolOfDeclaration(node.left); - if (symbol && symbol.parent && !findAncestor(symbol.parent.valueDeclaration, (d) => node === d)) { + if (symbol && symbol.parent && !findAncestor(symbol.parent.valueDeclaration, d => node === d)) { node = symbol.parent.valueDeclaration; } } @@ -55280,33 +51513,35 @@ ${lanes.join("\n")} case 347 /* JSDocEnumTag */: case 345 /* JSDocCallbackTag */: case 200 /* MappedType */: - case 194 /* ConditionalType */: { - const outerTypeParameters = getOuterTypeParameters(node, includeThisTypes); - if (node.kind === 200 /* MappedType */) { - return append(outerTypeParameters, getDeclaredTypeOfTypeParameter(getSymbolOfDeclaration(node.typeParameter))); - } else if (node.kind === 194 /* ConditionalType */) { - return concatenate(outerTypeParameters, getInferTypeParameters(node)); + case 194 /* ConditionalType */: + { + const outerTypeParameters = getOuterTypeParameters(node, includeThisTypes); + if (node.kind === 200 /* MappedType */) { + return append(outerTypeParameters, getDeclaredTypeOfTypeParameter(getSymbolOfDeclaration(node.typeParameter))); + } else if (node.kind === 194 /* ConditionalType */) { + return concatenate(outerTypeParameters, getInferTypeParameters(node)); + } + const outerAndOwnTypeParameters = appendTypeParameters(outerTypeParameters, getEffectiveTypeParameterDeclarations(node)); + const thisType = includeThisTypes && (node.kind === 263 /* ClassDeclaration */ || node.kind === 231 /* ClassExpression */ || node.kind === 264 /* InterfaceDeclaration */ || isJSConstructor(node)) && getDeclaredTypeOfClassOrInterface(getSymbolOfDeclaration(node)).thisType; + return thisType ? append(outerAndOwnTypeParameters, thisType) : outerAndOwnTypeParameters; } - const outerAndOwnTypeParameters = appendTypeParameters(outerTypeParameters, getEffectiveTypeParameterDeclarations(node)); - const thisType = includeThisTypes && (node.kind === 263 /* ClassDeclaration */ || node.kind === 231 /* ClassExpression */ || node.kind === 264 /* InterfaceDeclaration */ || isJSConstructor(node)) && getDeclaredTypeOfClassOrInterface(getSymbolOfDeclaration(node)).thisType; - return thisType ? append(outerAndOwnTypeParameters, thisType) : outerAndOwnTypeParameters; - } case 348 /* JSDocParameterTag */: const paramSymbol = getParameterSymbolFromJSDoc(node); if (paramSymbol) { node = paramSymbol.valueDeclaration; } break; - case 327 /* JSDoc */: { - const outerTypeParameters = getOuterTypeParameters(node, includeThisTypes); - return node.tags ? appendTypeParameters(outerTypeParameters, flatMap(node.tags, (t) => isJSDocTemplateTag(t) ? t.typeParameters : void 0)) : outerTypeParameters; - } + case 327 /* JSDoc */: + { + const outerTypeParameters = getOuterTypeParameters(node, includeThisTypes); + return node.tags ? appendTypeParameters(outerTypeParameters, flatMap(node.tags, t => isJSDocTemplateTag(t) ? t.typeParameters : void 0)) : outerTypeParameters; + } } } } function getOuterTypeParametersOfClassOrInterface(symbol) { var _a; - const declaration = symbol.flags & 32 /* Class */ || symbol.flags & 16 /* Function */ ? symbol.valueDeclaration : (_a = symbol.declarations) == null ? void 0 : _a.find((decl) => { + const declaration = symbol.flags & 32 /* Class */ || symbol.flags & 16 /* Function */ ? symbol.valueDeclaration : (_a = symbol.declarations) == null ? void 0 : _a.find(decl => { if (decl.kind === 264 /* InterfaceDeclaration */) { return true; } @@ -55316,6 +51551,7 @@ ${lanes.join("\n")} const initializer = decl.initializer; return !!initializer && (initializer.kind === 218 /* FunctionExpression */ || initializer.kind === 219 /* ArrowFunction */); }); + Debug.assert(!!declaration, "Class was missing valueDeclaration -OR- non-class had no interface declarations"); return getOuterTypeParameters(declaration); } @@ -55363,12 +51599,12 @@ ${lanes.join("\n")} function getConstructorsForTypeArguments(type, typeArgumentNodes, location) { const typeArgCount = length(typeArgumentNodes); const isJavascript = isInJSFile(location); - return filter(getSignaturesOfType(type, 1 /* Construct */), (sig) => (isJavascript || typeArgCount >= getMinTypeArgumentCount(sig.typeParameters)) && typeArgCount <= length(sig.typeParameters)); + return filter(getSignaturesOfType(type, 1 /* Construct */), sig => (isJavascript || typeArgCount >= getMinTypeArgumentCount(sig.typeParameters)) && typeArgCount <= length(sig.typeParameters)); } function getInstantiatedConstructorsForTypeArguments(type, typeArgumentNodes, location) { const signatures = getConstructorsForTypeArguments(type, typeArgumentNodes, location); const typeArguments = map(typeArgumentNodes, getTypeFromTypeNode); - return sameMap(signatures, (sig) => some(sig.typeParameters) ? getSignatureInstantiation(sig, typeArguments, isInJSFile(location)) : sig); + return sameMap(signatures, sig => some(sig.typeParameters) ? getSignatureInstantiation(sig, typeArguments, isInJSFile(location)) : sig); } function getBaseConstructorTypeOfClass(type) { if (!type.resolvedBaseConstructorType) { @@ -55419,8 +51655,7 @@ ${lanes.join("\n")} 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)) { @@ -55436,13 +51671,10 @@ ${lanes.join("\n")} return resolvedImplementsTypes; } function reportCircularBaseType(node, type) { - error2(node, Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString( - type, - /*enclosingDeclaration*/ - void 0, - 2 /* WriteArrayAsGenericType */ - )); + error2(node, Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, /*enclosingDeclaration*/ + void 0, 2 /* WriteArrayAsGenericType */)); } + function getBaseTypes(type) { if (!type.baseTypesResolved) { if (pushTypeResolution(type, 7 /* ResolvedBaseTypes */)) { @@ -55500,22 +51732,16 @@ ${lanes.join("\n")} } const reducedBaseType = getReducedType(baseType); if (!isValidBaseType(reducedBaseType)) { - const elaboration = elaborateNeverIntersection( - /*errorInfo*/ - void 0, - baseType - ); + const elaboration = elaborateNeverIntersection( /*errorInfo*/ + void 0, baseType); const diagnostic = chainDiagnosticMessages(elaboration, Diagnostics.Base_constructor_return_type_0_is_not_an_object_type_or_intersection_of_object_types_with_statically_known_members, typeToString(reducedBaseType)); diagnostics.add(createDiagnosticForNodeFromMessageChain(getSourceFileOfNode(baseTypeNode.expression), baseTypeNode.expression, diagnostic)); return type.resolvedBaseTypes = emptyArray; } if (type === reducedBaseType || hasBaseType(reducedBaseType, type)) { - error2(type.symbol.valueDeclaration, Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString( - type, - /*enclosingDeclaration*/ - void 0, - 2 /* WriteArrayAsGenericType */ - )); + error2(type.symbol.valueDeclaration, Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, /*enclosingDeclaration*/ + void 0, 2 /* WriteArrayAsGenericType */)); + return type.resolvedBaseTypes = emptyArray; } if (type.resolvedBaseTypes === resolvingEmptyArray) { @@ -55581,12 +51807,8 @@ ${lanes.join("\n")} if (baseTypeNodes) { for (const node of baseTypeNodes) { if (isEntityNameExpression(node.expression)) { - const baseSymbol = resolveEntityName( - node.expression, - 788968 /* Type */, - /*ignoreErrors*/ - true - ); + const baseSymbol = resolveEntityName(node.expression, 788968 /* Type */, /*ignoreErrors*/ + true); if (!baseSymbol || !(baseSymbol.flags & 64 /* Interface */) || getDeclaredTypeOfClassOrInterface(baseSymbol).thisType) { return false; } @@ -55615,7 +51837,7 @@ ${lanes.join("\n")} type.typeParameters = concatenate(outerTypeParameters, localTypeParameters); type.outerTypeParameters = outerTypeParameters; type.localTypeParameters = localTypeParameters; - type.instantiations = /* @__PURE__ */ new Map(); + type.instantiations = /* @__PURE__ */new Map(); type.instantiations.set(getTypeListId(type.typeParameters), type); type.target = type; type.resolvedTypeArguments = type.typeParameters; @@ -55640,7 +51862,7 @@ ${lanes.join("\n")} const typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); if (typeParameters) { links.typeParameters = typeParameters; - links.instantiations = /* @__PURE__ */ new Map(); + links.instantiations = /* @__PURE__ */new Map(); links.instantiations.set(getTypeListId(typeParameters), type); } } else { @@ -55669,9 +51891,7 @@ ${lanes.join("\n")} if (hasBindableName(member)) { const memberSymbol = getSymbolOfDeclaration(member); const value = getEnumMemberValue(member); - const memberType = getFreshTypeOfLiteralType( - value !== void 0 ? getEnumLiteralType(value, getSymbolId(symbol), memberSymbol) : createComputedEnumType(memberSymbol) - ); + const memberType = getFreshTypeOfLiteralType(value !== void 0 ? getEnumLiteralType(value, getSymbolId(symbol), memberSymbol) : createComputedEnumType(memberSymbol)); getSymbolLinks(memberSymbol).declaredType = memberType; memberTypeList.push(getRegularTypeOfLiteralType(memberType)); } @@ -55679,13 +51899,8 @@ ${lanes.join("\n")} } } } - const enumType = memberTypeList.length ? getUnionType( - memberTypeList, - 1 /* Literal */, - symbol, - /*aliasTypeArguments*/ - void 0 - ) : createComputedEnumType(symbol); + const enumType = memberTypeList.length ? getUnionType(memberTypeList, 1 /* Literal */, symbol, /*aliasTypeArguments*/ + void 0) : createComputedEnumType(symbol); if (enumType.flags & 1048576 /* Union */) { enumType.flags |= 1024 /* EnumLiteral */; enumType.symbol = symbol; @@ -55845,6 +52060,7 @@ ${lanes.join("\n")} function isLateBoundName(name) { return name.charCodeAt(0) === 95 /* _ */ && name.charCodeAt(1) === 95 /* _ */ && name.charCodeAt(2) === 64 /* at */; } + function hasLateBindableName(node) { const name = getNameOfDeclaration(node); return !!name && isLateBindableName(name); @@ -55881,16 +52097,16 @@ ${lanes.join("\n")} 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) || earlySymbol)) { const declarations = earlySymbol ? concatenate(earlySymbol.declarations, lateSymbol.declarations) : lateSymbol.declarations; const name = !(type.flags & 8192 /* UniqueESSymbol */) && unescapeLeadingUnderscores(memberName) || declarationNameToString(declName); - forEach(declarations, (declaration) => error2(getNameOfDeclaration(declaration) || declaration, Diagnostics.Property_0_was_also_declared_here, name)); + forEach(declarations, declaration => error2(getNameOfDeclaration(declaration) || declaration, Diagnostics.Property_0_was_also_declared_here, name)); error2(declName || decl, Diagnostics.Duplicate_property_0, name); lateSymbol = createSymbol(0 /* None */, memberName, 4096 /* Late */); } + lateSymbol.links.nameType = type; addDeclarationToLateBoundSymbol(lateSymbol, decl, symbolFlags); if (lateSymbol.parent) { @@ -55944,16 +52160,10 @@ ${lanes.join("\n")} 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)); }); } } @@ -55985,7 +52195,7 @@ ${lanes.join("\n")} const typeArguments = getTypeArguments(type); return length(target.typeParameters) === length(typeArguments) ? createTypeReference(target, concatenate(typeArguments, [thisArgument || target.thisType])) : type; } else if (type.flags & 2097152 /* Intersection */) { - const types = sameMap(type.types, (t) => getTypeWithThisArgument(t, thisArgument, needApparentType)); + const types = sameMap(type.types, t => getTypeWithThisArgument(t, thisArgument, needApparentType)); return types !== type.types ? getIntersectionType(types) : type; } return needApparentType ? getApparentType(type) : type; @@ -56003,12 +52213,8 @@ ${lanes.join("\n")} indexInfos = source.declaredIndexInfos; } else { mapper = createTypeMapper(typeParameters, typeArguments); - members = createInstantiatedSymbolTable( - source.declaredProperties, - mapper, - /*mappingThisOnly*/ - typeParameters.length === 1 - ); + members = createInstantiatedSymbolTable(source.declaredProperties, mapper, /*mappingThisOnly*/ + typeParameters.length === 1); callSignatures = instantiateSignatures(source.declaredCallSignatures, mapper); constructSignatures = instantiateSignatures(source.declaredConstructSignatures, mapper); indexInfos = instantiateIndexInfos(source.declaredIndexInfos, mapper); @@ -56031,13 +52237,9 @@ ${lanes.join("\n")} addInheritedMembers(members, getPropertiesOfType(instantiatedBaseType)); callSignatures = concatenate(callSignatures, getSignaturesOfType(instantiatedBaseType, 0 /* Call */)); constructSignatures = concatenate(constructSignatures, getSignaturesOfType(instantiatedBaseType, 1 /* Construct */)); - const inheritedIndexInfos = instantiatedBaseType !== anyType ? getIndexInfosOfType(instantiatedBaseType) : [createIndexInfo( - stringType, - anyType, - /*isReadonly*/ - false - )]; - indexInfos = concatenate(indexInfos, filter(inheritedIndexInfos, (info) => !findIndexInfo(indexInfos, info.keyType))); + const inheritedIndexInfos = instantiatedBaseType !== anyType ? getIndexInfosOfType(instantiatedBaseType) : [createIndexInfo(stringType, anyType, /*isReadonly*/ + false)]; + indexInfos = concatenate(indexInfos, filter(inheritedIndexInfos, info => !findIndexInfo(indexInfos, info.keyType))); } } setStructuredTypeMembers(type, members, callSignatures, constructSignatures, indexInfos); @@ -56069,18 +52271,10 @@ ${lanes.join("\n")} return sig; } function cloneSignature(sig) { - const result = createSignature( - sig.declaration, - sig.typeParameters, - sig.thisParameter, - sig.parameters, - /*resolvedReturnType*/ - void 0, - /*resolvedTypePredicate*/ - void 0, - sig.minArgumentCount, - sig.flags & 167 /* PropagatingFlags */ - ); + const result = createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, /*resolvedReturnType*/ + void 0, /*resolvedTypePredicate*/ + void 0, sig.minArgumentCount, sig.flags & 167 /* PropagatingFlags */); + result.target = sig.target; result.mapper = sig.mapper; result.compositeSignatures = sig.compositeSignatures; @@ -56119,7 +52313,7 @@ ${lanes.join("\n")} if (isTupleType(restType)) { return [expandSignatureParametersWithTupleMembers(restType, restIndex, restName)]; } else if (!skipUnionExpanding && restType.flags & 1048576 /* Union */ && every(restType.types, isTupleType)) { - return map(restType.types, (t) => expandSignatureParametersWithTupleMembers(t, restIndex, restName)); + return map(restType.types, t => expandSignatureParametersWithTupleMembers(t, restIndex, restName)); } } return [sig.parameters]; @@ -56137,7 +52331,7 @@ ${lanes.join("\n")} return concatenate(sig.parameters.slice(0, restIndex), restParams); } function getUniqAssociatedNamesFromTupleType(type, restName) { - const associatedNamesMap = /* @__PURE__ */ new Map(); + const associatedNamesMap = /* @__PURE__ */new Map(); return map(type.target.labeledElementDeclarations, (labeledElement, i) => { const name = getTupleElementLabel(labeledElement, i, restName); const prevCounter = associatedNamesMap.get(name); @@ -56157,20 +52351,12 @@ ${lanes.join("\n")} const declaration = getClassLikeDeclarationOfSymbol(classType.symbol); const isAbstract = !!declaration && hasSyntacticModifier(declaration, 64 /* Abstract */); if (baseSignatures.length === 0) { - return [createSignature( - /*declaration*/ - void 0, - classType.localTypeParameters, - /*thisParameter*/ - void 0, - emptyArray, - classType, - /*resolvedTypePredicate*/ - void 0, - 0, - isAbstract ? 4 /* Abstract */ : 0 /* None */ - )]; + return [createSignature( /*declaration*/ + void 0, classType.localTypeParameters, /*thisParameter*/ + void 0, emptyArray, classType, /*resolvedTypePredicate*/ + void 0, 0, isAbstract ? 4 /* Abstract */ : 0 /* None */)]; } + const baseTypeNode = getBaseTypeNodeOfClass(classType); const isJavaScript = isInJSFile(baseTypeNode); const typeArguments = typeArgumentsFromTypeReferenceNode(baseTypeNode); @@ -56202,16 +52388,10 @@ ${lanes.join("\n")} return void 0; } for (let i = 1; i < signatureLists.length; i++) { - if (!findMatchingSignature( - signatureLists[i], - signature, - /*partialMatch*/ - false, - /*ignoreThisTypes*/ - false, - /*ignoreReturnTypes*/ - false - )) { + if (!findMatchingSignature(signatureLists[i], signature, /*partialMatch*/ + false, /*ignoreThisTypes*/ + false, /*ignoreReturnTypes*/ + false)) { return void 0; } } @@ -56219,16 +52399,10 @@ ${lanes.join("\n")} } let result; for (let i = 0; i < signatureLists.length; i++) { - const match = i === listIndex ? signature : findMatchingSignature( - signatureLists[i], - signature, - /*partialMatch*/ - true, - /*ignoreThisTypes*/ - false, - /*ignoreReturnTypes*/ - true - ); + const match = i === listIndex ? signature : findMatchingSignature(signatureLists[i], signature, /*partialMatch*/ + true, /*ignoreThisTypes*/ + false, /*ignoreReturnTypes*/ + true); if (!match) { return void 0; } @@ -56240,30 +52414,23 @@ ${lanes.join("\n")} 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; } for (const signature of signatureLists[i]) { - if (!result || !findMatchingSignature( - result, - signature, - /*partialMatch*/ - false, - /*ignoreThisTypes*/ - false, - /*ignoreReturnTypes*/ - true - )) { + if (!result || !findMatchingSignature(result, signature, /*partialMatch*/ + false, /*ignoreThisTypes*/ + false, /*ignoreReturnTypes*/ + true)) { const unionSignatures = findMatchingSignatures(signatureLists, signature, i); if (unionSignatures) { let s = signature; if (unionSignatures.length > 1) { let thisParameter = signature.thisParameter; - const firstThisParameterOfUnionSignatures = forEach(unionSignatures, (sig) => sig.thisParameter); + const firstThisParameterOfUnionSignatures = forEach(unionSignatures, sig => sig.thisParameter); if (firstThisParameterOfUnionSignatures) { - const thisType = getIntersectionType(mapDefined(unionSignatures, (sig) => sig.thisParameter && getTypeOfSymbol(sig.thisParameter))); + const thisType = getIntersectionType(mapDefined(unionSignatures, sig => sig.thisParameter && getTypeOfSymbol(sig.thisParameter))); thisParameter = createSymbolWithType(firstThisParameterOfUnionSignatures, thisType); } s = createUnionSignature(signature, unionSignatures); @@ -56281,7 +52448,7 @@ ${lanes.join("\n")} if (signatures !== masterList) { const signature = signatures[0]; Debug.assert(!!signature, "getUnionSignatures bails early on empty signature lists and should not have empty lists on second pass"); - results = !!signature.typeParameters && some(results, (s) => !!s.typeParameters && !compareTypeParametersIdentical(signature.typeParameters, s.typeParameters)) ? void 0 : map(results, (sig) => combineSignaturesOfUnionMembers(sig, signature)); + results = !!signature.typeParameters && some(results, s => !!s.typeParameters && !compareTypeParametersIdentical(signature.typeParameters, s.typeParameters)) ? void 0 : map(results, sig => combineSignaturesOfUnionMembers(sig, signature)); if (!results) { break; } @@ -56302,10 +52469,8 @@ ${lanes.join("\n")} 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; } @@ -56340,11 +52505,7 @@ ${lanes.join("\n")} const leftName = i >= leftCount ? void 0 : getParameterNameAtPosition(left, i); const rightName = i >= rightCount ? void 0 : getParameterNameAtPosition(right, i); const paramName = leftName === rightName ? leftName : !leftName ? rightName : !rightName ? leftName : void 0; - const paramSymbol = createSymbol( - 1 /* FunctionScopedVariable */ | (isOptional && !isRestParam ? 16777216 /* Optional */ : 0), - paramName || `arg${i}`, - isRestParam ? 32768 /* RestParameter */ : isOptional ? 16384 /* OptionalParameter */ : 0 - ); + const paramSymbol = createSymbol(1 /* FunctionScopedVariable */ | (isOptional && !isRestParam ? 16777216 /* Optional */ : 0), paramName || `arg${i}`, isRestParam ? 32768 /* RestParameter */ : isOptional ? 16384 /* OptionalParameter */ : 0); paramSymbol.links.type = isRestParam ? createArrayType(unionParamType) : unionParamType; params[i] = paramSymbol; } @@ -56368,18 +52529,10 @@ ${lanes.join("\n")} const params = combineUnionParameters(left, right, paramMapper); const thisParam = combineUnionThisParam(left.thisParameter, right.thisParameter, paramMapper); const minArgCount = Math.max(left.minArgumentCount, right.minArgumentCount); - const result = createSignature( - declaration, - typeParams, - thisParam, - params, - /*resolvedReturnType*/ - void 0, - /*resolvedTypePredicate*/ - void 0, - minArgCount, - (left.flags | right.flags) & 167 /* PropagatingFlags */ - ); + const result = createSignature(declaration, typeParams, thisParam, params, /*resolvedReturnType*/ + void 0, /*resolvedTypePredicate*/ + void 0, minArgCount, (left.flags | right.flags) & 167 /* PropagatingFlags */); + result.compositeKind = 1048576 /* Union */; result.compositeSignatures = concatenate(left.compositeKind !== 2097152 /* Intersection */ && left.compositeSignatures || [left], [right]); if (paramMapper) { @@ -56393,8 +52546,8 @@ ${lanes.join("\n")} const result = []; for (const info of sourceInfos) { const indexType = info.keyType; - if (every(types, (t) => !!getIndexInfoOfType(t, indexType))) { - result.push(createIndexInfo(indexType, getUnionType(map(types, (t) => getIndexTypeOfType(t, indexType))), some(types, (t) => getIndexInfoOfType(t, indexType).isReadonly))); + if (every(types, t => !!getIndexInfoOfType(t, indexType))) { + result.push(createIndexInfo(indexType, getUnionType(map(types, t => getIndexTypeOfType(t, indexType))), some(types, t => getIndexInfoOfType(t, indexType).isReadonly))); } } return result; @@ -56402,8 +52555,8 @@ ${lanes.join("\n")} return emptyArray; } function resolveUnionTypeMembers(type) { - const callSignatures = getUnionSignatures(map(type.types, (t) => t === globalFunctionType ? [unknownSignature] : getSignaturesOfType(t, 0 /* Call */))); - const constructSignatures = getUnionSignatures(map(type.types, (t) => getSignaturesOfType(t, 1 /* Construct */))); + const callSignatures = getUnionSignatures(map(type.types, t => t === globalFunctionType ? [unknownSignature] : getSignaturesOfType(t, 0 /* Call */))); + const constructSignatures = getUnionSignatures(map(type.types, t => getSignaturesOfType(t, 1 /* Construct */))); const indexInfos = getUnionIndexInfos(type.types); setStructuredTypeMembers(type, emptySymbols, callSignatures, constructSignatures, indexInfos); } @@ -56411,13 +52564,11 @@ ${lanes.join("\n")} return !type1 ? type2 : !type2 ? type1 : getIntersectionType([type1, type2]); } function findMixins(types) { - const constructorTypeCount = countWhere(types, (t) => getSignaturesOfType(t, 1 /* Construct */).length > 0); + const constructorTypeCount = countWhere(types, t => getSignaturesOfType(t, 1 /* Construct */).length > 0); const mixinFlags = map(types, isMixinConstructorType); - if (constructorTypeCount > 0 && constructorTypeCount === countWhere(mixinFlags, (b) => b)) { - const firstMixinIndex = mixinFlags.indexOf( - /*searchElement*/ - true - ); + if (constructorTypeCount > 0 && constructorTypeCount === countWhere(mixinFlags, b => b)) { + const firstMixinIndex = mixinFlags.indexOf( /*searchElement*/ + true); mixinFlags[firstMixinIndex] = false; } return mixinFlags; @@ -56439,13 +52590,13 @@ ${lanes.join("\n")} let indexInfos; const types = type.types; const mixinFlags = findMixins(types); - const mixinCount = countWhere(mixinFlags, (b) => b); + const mixinCount = countWhere(mixinFlags, b => b); for (let i = 0; i < types.length; i++) { const t = type.types[i]; if (!mixinFlags[i]) { let signatures = getSignaturesOfType(t, 1 /* Construct */); if (signatures.length && mixinCount > 0) { - signatures = map(signatures, (s) => { + signatures = map(signatures, s => { const clone2 = cloneSignature(s); clone2.resolvedReturnType = includeMixinType(getReturnTypeOfSignature(s), types, mixinFlags, i); return clone2; @@ -56454,28 +52605,17 @@ ${lanes.join("\n")} constructSignatures = appendSignatures(constructSignatures, signatures); } callSignatures = appendSignatures(callSignatures, getSignaturesOfType(t, 0 /* Call */)); - indexInfos = reduceLeft(getIndexInfosOfType(t), (infos, newInfo) => appendIndexInfo( - infos, - newInfo, - /*union*/ - false - ), indexInfos); + indexInfos = reduceLeft(getIndexInfosOfType(t), (infos, newInfo) => appendIndexInfo(infos, newInfo, /*union*/ + false), indexInfos); } setStructuredTypeMembers(type, emptySymbols, callSignatures || emptyArray, constructSignatures || emptyArray, indexInfos || emptyArray); } function appendSignatures(signatures, newSignatures) { for (const sig of newSignatures) { - if (!signatures || every(signatures, (s) => !compareSignaturesIdentical( - s, - sig, - /*partialMatch*/ - false, - /*ignoreThisTypes*/ - false, - /*ignoreReturnTypes*/ - false, - compareTypesIdentical - ))) { + if (!signatures || every(signatures, s => !compareSignaturesIdentical(s, sig, /*partialMatch*/ + false, /*ignoreThisTypes*/ + false, /*ignoreReturnTypes*/ + false, compareTypesIdentical))) { signatures = append(signatures, sig); } } @@ -56496,12 +52636,8 @@ ${lanes.join("\n")} function resolveAnonymousTypeMembers(type) { if (type.target) { setStructuredTypeMembers(type, emptySymbols, emptyArray, emptyArray, emptyArray); - const members2 = createInstantiatedSymbolTable( - getPropertiesOfObjectType(type.target), - type.mapper, - /*mappingThisOnly*/ - false - ); + const members2 = createInstantiatedSymbolTable(getPropertiesOfObjectType(type.target), type.mapper, /*mappingThisOnly*/ + false); const callSignatures = instantiateSignatures(getSignaturesOfType(type.target, 0 /* Call */), type.mapper); const constructSignatures = instantiateSignatures(getSignaturesOfType(type.target, 1 /* Construct */), type.mapper); const indexInfos2 = instantiateIndexInfos(getIndexInfosOfType(type.target), type.mapper); @@ -56521,8 +52657,8 @@ ${lanes.join("\n")} let members = getExportsOfSymbol(symbol); let indexInfos; if (symbol === globalThisSymbol) { - const varsOnly = /* @__PURE__ */ new Map(); - members.forEach((p) => { + const varsOnly = /* @__PURE__ */new Map(); + members.forEach(p => { var _a; if (!(p.flags & 418 /* BlockScoped */) && !(p.flags & 512 /* ValueModule */ && ((_a = p.declarations) == null ? void 0 : _a.length) && every(p.declarations, isAmbientModule))) { varsOnly.set(p.escapedName, p); @@ -56539,12 +52675,8 @@ ${lanes.join("\n")} members = createSymbolTable(getNamedOrIndexSignatureMembers(members)); addInheritedMembers(members, getPropertiesOfType(baseConstructorType)); } else if (baseConstructorType === anyType) { - baseConstructorIndexInfo = createIndexInfo( - stringType, - anyType, - /*isReadonly*/ - false - ); + baseConstructorIndexInfo = createIndexInfo(stringType, anyType, /*isReadonly*/ + false); } } const indexSymbol = getIndexSymbolFromSymbolTable(members); @@ -56554,7 +52686,7 @@ ${lanes.join("\n")} if (baseConstructorIndexInfo) { indexInfos = append(indexInfos, baseConstructorIndexInfo); } - if (symbol.flags & 384 /* Enum */ && (getDeclaredTypeOfSymbol(symbol).flags & 32 /* Enum */ || some(type.properties, (prop) => !!(getTypeOfSymbol(prop).flags & 296 /* NumberLike */)))) { + if (symbol.flags & 384 /* Enum */ && (getDeclaredTypeOfSymbol(symbol).flags & 32 /* Enum */ || some(type.properties, prop => !!(getTypeOfSymbol(prop).flags & 296 /* NumberLike */)))) { indexInfos = append(indexInfos, enumNumberIndexInfo); } } @@ -56566,23 +52698,8 @@ ${lanes.join("\n")} const classType = getDeclaredTypeOfClassOrInterface(symbol); let constructSignatures = symbol.members ? getSignaturesOfSymbol(symbol.members.get("__constructor" /* Constructor */)) : emptyArray; if (symbol.flags & 16 /* Function */) { - constructSignatures = addRange( - constructSignatures.slice(), - mapDefined( - type.callSignatures, - (sig) => isJSConstructor(sig.declaration) ? createSignature( - sig.declaration, - sig.typeParameters, - sig.thisParameter, - sig.parameters, - classType, - /*resolvedTypePredicate*/ - void 0, - sig.minArgumentCount, - sig.flags & 167 /* PropagatingFlags */ - ) : void 0 - ) - ); + constructSignatures = addRange(constructSignatures.slice(), mapDefined(type.callSignatures, sig => isJSConstructor(sig.declaration) ? createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, classType, /*resolvedTypePredicate*/ + void 0, sig.minArgumentCount, sig.flags & 167 /* PropagatingFlags */) : void 0)); } if (!constructSignatures.length) { constructSignatures = getDefaultConstructSignatures(classType); @@ -56635,12 +52752,8 @@ ${lanes.join("\n")} return type; } if (type.flags & 1048576 /* Union */) { - return mapType( - type, - getLowerBoundOfKeyType, - /*noReductions*/ - true - ); + return mapType(type, getLowerBoundOfKeyType, /*noReductions*/ + true); } if (type.flags & 2097152 /* Intersection */) { const types = type.types; @@ -56654,6 +52767,7 @@ ${lanes.join("\n")} function getIsLateCheckFlag(s) { return getCheckFlags(s) & 4096 /* Late */; } + function forEachMappedTypePropertyKeyTypeAndIndexSignatureKeyType(type, include, stringsOnly, cb) { for (const prop of getPropertiesOfType(type)) { cb(getLiteralTypeFromProperty(prop, include)); @@ -56689,7 +52803,7 @@ ${lanes.join("\n")} setStructuredTypeMembers(type, members, emptyArray, emptyArray, indexInfos || emptyArray); function addMemberForKeyType(keyType) { const propNameType = nameType ? instantiateType(nameType, appendTypeMapping(type.mapper, typeParameter, keyType)) : keyType; - forEachType(propNameType, (t) => addMemberForKeyTypeWorker(keyType, t)); + forEachType(propNameType, t => addMemberForKeyTypeWorker(keyType, t)); } function addMemberForKeyTypeWorker(keyType, propNameType) { if (isTypeUsableAsPropertyName(propNameType)) { @@ -56720,12 +52834,8 @@ ${lanes.join("\n")} const modifiersIndexInfo = getApplicableIndexInfo(modifiersType, propNameType); const isReadonly = !!(templateModifiers & 1 /* IncludeReadonly */ || !(templateModifiers & 2 /* ExcludeReadonly */) && (modifiersIndexInfo == null ? void 0 : modifiersIndexInfo.isReadonly)); const indexInfo = createIndexInfo(indexKeyType, propType, isReadonly); - indexInfos = appendIndexInfo( - indexInfos, - indexInfo, - /*union*/ - true - ); + indexInfos = appendIndexInfo(indexInfos, indexInfo, /*union*/ + true); } } } @@ -56739,11 +52849,8 @@ ${lanes.join("\n")} const templateType = getTemplateTypeFromMappedType(mappedType.target || mappedType); const mapper = appendTypeMapping(mappedType.mapper, getTypeParameterFromMappedType(mappedType), symbol.links.keyType); const propType = instantiateType(templateType, mapper); - let type = strictNullChecks && symbol.flags & 16777216 /* Optional */ && !maybeTypeOfKind(propType, 32768 /* Undefined */ | 16384 /* Void */) ? getOptionalType( - propType, - /*isProperty*/ - true - ) : symbol.links.checkFlags & 524288 /* StripOptional */ ? removeMissingOrUndefinedType(propType) : propType; + let type = strictNullChecks && symbol.flags & 16777216 /* Optional */ && !maybeTypeOfKind(propType, 32768 /* Undefined */ | 16384 /* Void */) ? getOptionalType(propType, /*isProperty*/ + true) : symbol.links.checkFlags & 524288 /* StripOptional */ ? removeMissingOrUndefinedType(propType) : propType; if (!popTypeResolution()) { error2(currentNode, Diagnostics.Type_of_property_0_circularly_references_itself_in_mapped_type_1, symbolToString(symbol), typeToString(mappedType)); type = errorType; @@ -56762,12 +52869,8 @@ ${lanes.join("\n")} return type.declaration.nameType ? type.nameType || (type.nameType = instantiateType(getTypeFromTypeNode(type.declaration.nameType), type.mapper)) : void 0; } function getTemplateTypeFromMappedType(type) { - return type.templateType || (type.templateType = type.declaration.type ? instantiateType(addOptionality( - getTypeFromTypeNode(type.declaration.type), - /*isProperty*/ - true, - !!(getMappedTypeModifiers(type) & 4 /* IncludeOptional */) - ), type.mapper) : errorType); + return type.templateType || (type.templateType = type.declaration.type ? instantiateType(addOptionality(getTypeFromTypeNode(type.declaration.type), /*isProperty*/ + true, !!(getMappedTypeModifiers(type) & 4 /* IncludeOptional */)), type.mapper) : errorType); } function getConstraintDeclarationForMappedType(type) { return getEffectiveConstraintOfTypeParameter(type.declaration.typeParameter); @@ -56776,6 +52879,7 @@ ${lanes.join("\n")} const constraintDeclaration = getConstraintDeclarationForMappedType(type); return constraintDeclaration.kind === 198 /* TypeOperator */ && constraintDeclaration.operator === 143 /* KeyOfKeyword */; } + function getModifiersTypeFromMappedType(type) { if (!type.modifiersType) { if (isMappedTypeWithKeyofConstraintDeclaration(type)) { @@ -56805,6 +52909,7 @@ ${lanes.join("\n")} function isPartialMappedType(type) { return !!(getObjectFlags(type) & 32 /* Mapped */ && getMappedTypeModifiers(type) & 4 /* IncludeOptional */); } + function isGenericMappedType(type) { if (getObjectFlags(type) & 32 /* Mapped */) { const constraint = getConstraintTypeFromMappedType(type); @@ -56899,7 +53004,7 @@ ${lanes.join("\n")} } function isTypeInvalidDueToUnionDiscriminant(contextualType, obj) { const list = obj.properties; - return list.some((property) => { + return list.some(property => { const nameType = property.name && (isJsxNamespacedName(property.name) ? getStringLiteralType(getTextOfJsxAttributeName(property.name)) : getLiteralTypeFromPropertyName(property.name)); const name = nameType && isTypeUsableAsPropertyName(nameType) ? getPropertyNameFromType(nameType) : void 0; const expected = name === void 0 ? void 0 : getTypeOfPropertyOfType(contextualType, name); @@ -56913,11 +53018,12 @@ ${lanes.join("\n")} } const props = createSymbolTable(); for (const memberType of types) { - for (const { escapedName } of getAugmentedPropertiesOfType(memberType)) { + 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); } } } @@ -56931,17 +53037,14 @@ ${lanes.join("\n")} } function isConstTypeVariable(type, depth = 0) { var _a; - return depth < 5 && !!(type && (type.flags & 262144 /* TypeParameter */ && some((_a = type.symbol) == null ? void 0 : _a.declarations, (d) => hasSyntacticModifier(d, 4096 /* Const */)) || type.flags & 3145728 /* UnionOrIntersection */ && some(type.types, (t) => isConstTypeVariable(t, depth)) || type.flags & 8388608 /* IndexedAccess */ && isConstTypeVariable(type.objectType, depth + 1) || type.flags & 16777216 /* Conditional */ && isConstTypeVariable(getConstraintOfConditionalType(type), depth + 1) || type.flags & 33554432 /* Substitution */ && isConstTypeVariable(type.baseType, depth) || isGenericTupleType(type) && findIndex(getElementTypes(type), (t, i) => !!(type.target.elementFlags[i] & 8 /* Variadic */) && isConstTypeVariable(t, depth)) >= 0)); + return depth < 5 && !!(type && (type.flags & 262144 /* TypeParameter */ && some((_a = type.symbol) == null ? void 0 : _a.declarations, d => hasSyntacticModifier(d, 4096 /* Const */)) || type.flags & 3145728 /* UnionOrIntersection */ && some(type.types, t => isConstTypeVariable(t, depth)) || type.flags & 8388608 /* IndexedAccess */ && isConstTypeVariable(type.objectType, depth + 1) || type.flags & 16777216 /* Conditional */ && isConstTypeVariable(getConstraintOfConditionalType(type), depth + 1) || type.flags & 33554432 /* Substitution */ && isConstTypeVariable(type.baseType, depth) || isGenericTupleType(type) && findIndex(getElementTypes(type), (t, i) => !!(type.target.elementFlags[i] & 8 /* Variadic */) && isConstTypeVariable(t, depth)) >= 0)); } function getConstraintOfIndexedAccess(type) { return hasNonCircularBaseConstraint(type) ? getConstraintFromIndexedAccess(type) : void 0; } function getSimplifiedTypeOrConstraint(type) { - const simplified = getSimplifiedType( - type, - /*writing*/ - false - ); + const simplified = getSimplifiedType(type, /*writing*/ + false); return simplified !== type ? simplified : getConstraintOfType(type); } function getConstraintFromIndexedAccess(type) { @@ -56974,11 +53077,8 @@ ${lanes.join("\n")} return type.resolvedConstraintOfDistributive || void 0; } if (type.root.isDistributive && type.restrictiveInstantiation !== type) { - const simplified = getSimplifiedType( - type.checkType, - /*writing*/ - false - ); + const simplified = getSimplifiedType(type.checkType, /*writing*/ + false); const constraint = simplified === type.checkType ? getConstraintOfType(simplified) : simplified; if (constraint && constraint !== type.checkType) { const instantiated = getConditionalTypeInstantiation(type, prependTypeMapping(type.root.checkType, constraint, type.mapper)); @@ -57024,11 +53124,8 @@ ${lanes.join("\n")} } } } - return getNormalizedType( - getIntersectionType(constraints), - /*writing*/ - false - ); + return getNormalizedType(getIntersectionType(constraints), /*writing*/ + false); } return void 0; } @@ -57060,11 +53157,8 @@ ${lanes.join("\n")} const identity2 = getRecursionIdentity(t); if (stack.length < 10 || stack.length < 50 && !contains(stack, identity2)) { stack.push(identity2); - result = computeBaseConstraint(getSimplifiedType( - t, - /*writing*/ - false - )); + result = computeBaseConstraint(getSimplifiedType(t, /*writing*/ + false)); stack.pop(); } if (!popTypeResolution()) { @@ -57143,7 +53237,7 @@ ${lanes.join("\n")} if (isGenericTupleType(t)) { const newElements = map(getElementTypes(t), (v, i) => { const constraint = v.flags & 262144 /* TypeParameter */ && t.target.elementFlags[i] & 8 /* Variadic */ && getBaseConstraint(v) || v; - return constraint !== v && everyType(constraint, (c) => isArrayOrTupleType(c) && !isGenericTupleType(c)) ? constraint : v; + return constraint !== v && everyType(constraint, c => isArrayOrTupleType(c) && !isGenericTupleType(c)) ? constraint : v; }); return createTupleType(newElements, t.target.elementFlags, t.target.readonly, t.target.labeledElementDeclarations); } @@ -57151,12 +53245,8 @@ ${lanes.join("\n")} } } function getApparentTypeOfIntersectionType(type, thisArgument) { - return type.resolvedApparentType || (type.resolvedApparentType = getTypeWithThisArgument( - type, - thisArgument, - /*needApparentType*/ - true - )); + return type.resolvedApparentType || (type.resolvedApparentType = getTypeWithThisArgument(type, thisArgument, /*needApparentType*/ + true)); } function getResolvedTypeParameterDefault(typeParameter) { if (!typeParameter.default) { @@ -57165,7 +53255,7 @@ ${lanes.join("\n")} typeParameter.default = targetDefault ? instantiateType(targetDefault, typeParameter.mapper) : noConstraintType; } else { typeParameter.default = resolvingDefaultType; - const defaultDeclaration = typeParameter.symbol && forEach(typeParameter.symbol.declarations, (decl) => isTypeParameterDeclaration(decl) && decl.default); + const defaultDeclaration = typeParameter.symbol && forEach(typeParameter.symbol.declarations, decl => isTypeParameterDeclaration(decl) && decl.default); const defaultType = defaultDeclaration ? getTypeFromTypeNode(defaultDeclaration) : noConstraintType; if (typeParameter.default === resolvingDefaultType) { typeParameter.default = defaultType; @@ -57184,7 +53274,7 @@ ${lanes.join("\n")} return getResolvedTypeParameterDefault(typeParameter) !== circularConstraintType; } function hasTypeParameterDefault(typeParameter) { - return !!(typeParameter.symbol && forEach(typeParameter.symbol.declarations, (decl) => isTypeParameterDeclaration(decl) && decl.default)); + return !!(typeParameter.symbol && forEach(typeParameter.symbol.declarations, decl => isTypeParameterDeclaration(decl) && decl.default)); } function getApparentTypeOfMappedType(type) { return type.resolvedApparentType || (type.resolvedApparentType = getResolvedApparentTypeOfMappedType(type)); @@ -57212,6 +53302,7 @@ ${lanes.join("\n")} return getReducedType(getApparentType(getReducedType(type))); } function createUnionOrIntersectionProperty(containingType, name, skipObjectFunctionPropertyAugment) { + var _optionalFlag2; var _a, _b, _c; let singleProp; let propSet; @@ -57228,7 +53319,8 @@ ${lanes.join("\n")} const modifiers = prop ? getDeclarationModifierFlagsFromSymbol(prop) : 0; if (prop) { if (prop.flags & 106500 /* ClassMember */) { - optionalFlag ?? (optionalFlag = isUnion ? 0 /* None */ : 16777216 /* Optional */); + var _optionalFlag; + (_optionalFlag = optionalFlag) !== null && _optionalFlag !== void 0 ? _optionalFlag : optionalFlag = isUnion ? 0 /* None */ : 16777216 /* Optional */; if (isUnion) { optionalFlag |= prop.flags & 16777216 /* Optional */; } else { @@ -57243,7 +53335,7 @@ ${lanes.join("\n")} mergedInstantiations = !!singleProp.parent && !!length(getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(singleProp.parent)); } else { if (!propSet) { - propSet = /* @__PURE__ */ new Map(); + propSet = /* @__PURE__ */new Map(); propSet.set(getSymbolId(singleProp), singleProp); } const id = getSymbolId(prop); @@ -57257,6 +53349,7 @@ ${lanes.join("\n")} } else if (!isUnion && !isReadonlySymbol(prop)) { checkFlags &= ~8 /* Readonly */; } + checkFlags |= (!(modifiers & 6 /* NonPublicAccessibilityModifier */) ? 256 /* ContainsPublic */ : 0) | (modifiers & 4 /* Protected */ ? 512 /* ContainsProtected */ : 0) | (modifiers & 2 /* Private */ ? 1024 /* ContainsPrivate */ : 0) | (modifiers & 256 /* Static */ ? 2048 /* ContainsStatic */ : 0); if (!isPrototypeProperty(prop)) { syntheticFlag = 2 /* SyntheticProperty */; @@ -57275,6 +53368,7 @@ ${lanes.join("\n")} } } } + if (!singleProp || isUnion && (propSet || checkFlags & 48 /* Partial */) && checkFlags & (1024 /* ContainsPrivate */ | 512 /* ContainsProtected */) && !(propSet && getCommonDeclarationsOfSymbols(propSet.values()))) { return void 0; } @@ -57317,16 +53411,19 @@ ${lanes.join("\n")} if (type !== firstType) { checkFlags |= 64 /* HasNonUniformType */; } + if (isLiteralType(type) || isPatternLiteralType(type)) { checkFlags |= 128 /* HasLiteralType */; } + if (type.flags & 131072 /* Never */ && type !== uniqueLiteralType) { checkFlags |= 131072 /* HasNeverType */; } + propTypes.push(type); } addRange(propTypes, indexTypes); - const result = createSymbol(4 /* Property */ | (optionalFlag ?? 0), name, syntheticFlag | checkFlags); + const result = createSymbol(4 /* Property */ | ((_optionalFlag2 = optionalFlag) !== null && _optionalFlag2 !== void 0 ? _optionalFlag2 : 0), name, syntheticFlag | checkFlags); result.links.containingType = containingType; if (!hasNonUniformValueDeclaration && firstValueDeclaration) { result.valueDeclaration = firstValueDeclaration; @@ -57371,7 +53468,7 @@ ${lanes.join("\n")} commonDeclarations = new Set(symbol.declarations); continue; } - commonDeclarations.forEach((declaration) => { + commonDeclarations.forEach(declaration => { if (!contains(symbol.declarations, declaration)) { commonDeclarations.delete(declaration); } @@ -57414,9 +53511,11 @@ ${lanes.join("\n")} function isDiscriminantWithNeverType(prop) { return !(prop.flags & 16777216 /* Optional */) && (getCheckFlags(prop) & (192 /* Discriminant */ | 131072 /* HasNeverType */)) === 192 /* Discriminant */ && !!(getTypeOfSymbol(prop).flags & 131072 /* Never */); } + function isConflictingPrivateProperty(prop) { return !prop.valueDeclaration && !!(getCheckFlags(prop) & 1024 /* ContainsPrivate */); } + function isGenericReducibleType(type) { return !!(type.flags & 1048576 /* Union */ && type.objectFlags & 16777216 /* ContainsIntersections */ && some(type.types, isGenericReducibleType) || type.flags & 2097152 /* Intersection */ && isReducibleIntersection(type)); } @@ -57428,21 +53527,13 @@ ${lanes.join("\n")} if (type.flags & 2097152 /* Intersection */ && getObjectFlags(type) & 33554432 /* IsNeverIntersection */) { const neverProp = find(getPropertiesOfUnionOrIntersectionType(type), isDiscriminantWithNeverType); if (neverProp) { - return chainDiagnosticMessages(errorInfo, Diagnostics.The_intersection_0_was_reduced_to_never_because_property_1_has_conflicting_types_in_some_constituents, typeToString( - type, - /*enclosingDeclaration*/ - void 0, - 536870912 /* NoTypeReduction */ - ), symbolToString(neverProp)); + return chainDiagnosticMessages(errorInfo, Diagnostics.The_intersection_0_was_reduced_to_never_because_property_1_has_conflicting_types_in_some_constituents, typeToString(type, /*enclosingDeclaration*/ + void 0, 536870912 /* NoTypeReduction */), symbolToString(neverProp)); } const privateProp = find(getPropertiesOfUnionOrIntersectionType(type), isConflictingPrivateProperty); if (privateProp) { - return chainDiagnosticMessages(errorInfo, Diagnostics.The_intersection_0_was_reduced_to_never_because_property_1_exists_in_multiple_constituents_and_is_private_in_some, typeToString( - type, - /*enclosingDeclaration*/ - void 0, - 536870912 /* NoTypeReduction */ - ), symbolToString(privateProp)); + return chainDiagnosticMessages(errorInfo, Diagnostics.The_intersection_0_was_reduced_to_never_because_property_1_exists_in_multiple_constituents_and_is_private_in_some, typeToString(type, /*enclosingDeclaration*/ + void 0, 536870912 /* NoTypeReduction */), symbolToString(privateProp)); } } return errorInfo; @@ -57455,8 +53546,7 @@ ${lanes.join("\n")} 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); @@ -57485,12 +53575,12 @@ ${lanes.join("\n")} return type.arrayFallbackSignatures; } let memberName; - if (everyType(type, (t) => { + if (everyType(type, t => { var _a; return !!((_a = t.symbol) == null ? void 0 : _a.parent) && isArrayOrTupleSymbol(t.symbol.parent) && (!memberName ? (memberName = t.symbol.escapedName, true) : memberName === t.symbol.escapedName); })) { - const arrayArg = mapType(type, (t) => getMappedType((isReadonlyArraySymbol(t.symbol.parent) ? globalReadonlyArrayType : globalArrayType).typeParameters[0], t.mapper)); - const arrayType = createArrayType(arrayArg, someType(type, (t) => isReadonlyArraySymbol(t.symbol.parent))); + const arrayArg = mapType(type, t => getMappedType((isReadonlyArraySymbol(t.symbol.parent) ? globalReadonlyArrayType : globalArrayType).typeParameters[0], t.mapper)); + const arrayType = createArrayType(arrayArg, someType(type, t => isReadonlyArraySymbol(t.symbol.parent))); return type.arrayFallbackSignatures = getSignaturesOfType(getTypeOfPropertyOfType(arrayType, memberName), kind); } type.arrayFallbackSignatures = result; @@ -57510,7 +53600,7 @@ ${lanes.join("\n")} return !!getSymbolIfSameReference(symbol, globalReadonlyArrayType.symbol); } function findIndexInfo(indexInfos, keyType) { - return find(indexInfos, (info) => info.keyType === keyType); + return find(indexInfos, info => info.keyType === keyType); } function findApplicableIndexInfo(indexInfos, keyType) { let stringIndexInfo; @@ -57527,12 +53617,8 @@ ${lanes.join("\n")} } } } - return applicableInfos ? createIndexInfo(unknownType, getIntersectionType(map(applicableInfos, (info) => info.type)), reduceLeft( - applicableInfos, - (isReadonly, info) => isReadonly && info.isReadonly, - /*initial*/ - true - )) : applicableInfo ? applicableInfo : stringIndexInfo && isApplicableIndexType(keyType, stringType) ? stringIndexInfo : void 0; + return applicableInfos ? createIndexInfo(unknownType, getIntersectionType(map(applicableInfos, info => info.type)), reduceLeft(applicableInfos, (isReadonly, info) => isReadonly && info.isReadonly, /*initial*/ + true)) : applicableInfo ? applicableInfo : stringIndexInfo && isApplicableIndexType(keyType, stringType) ? stringIndexInfo : void 0; } function isApplicableIndexType(source, target) { return isTypeAssignableTo(source, target) || target === stringType && isTypeAssignableTo(source, numberType) || target === numberType && (source === numericStringType || !!(source.flags & 128 /* StringLiteral */) && isNumericLiteralName(source.value)); @@ -57555,7 +53641,7 @@ ${lanes.join("\n")} return (_a = getIndexInfoOfType(type, keyType)) == null ? void 0 : _a.type; } function getApplicableIndexInfos(type, keyType) { - return getIndexInfosOfType(type).filter((info) => isApplicableIndexType(keyType, info.keyType)); + return getIndexInfosOfType(type).filter(info => isApplicableIndexType(keyType, info.keyType)); } function getApplicableIndexInfo(type, keyType) { return findApplicableIndexInfo(getIndexInfosOfType(type), keyType); @@ -57597,6 +53683,7 @@ ${lanes.join("\n")} Debug.assert(parameterIndex >= 0); return parameterIndex >= getMinArgumentCount(signature, 1 /* StrongArityForUntypedJS */ | 2 /* VoidIsNonOptional */); } + const iife = getImmediatelyInvokedFunctionExpression(node.parent); if (iife) { return !node.type && !node.dotDotDotToken && node.parent.parameters.indexOf(node) >= getEffectiveCallArguments(iife).length; @@ -57607,7 +53694,12 @@ ${lanes.join("\n")} return isPropertyDeclaration(node) && !hasAccessorModifier(node) && node.questionToken; } function createTypePredicate(kind, parameterName, parameterIndex, type) { - return { kind, parameterName, parameterIndex, type }; + return { + kind, + parameterName, + parameterIndex, + type + }; } function getMinTypeArgumentCount(typeParameters) { let minTypeArgumentCount = 0; @@ -57658,22 +53750,16 @@ ${lanes.join("\n")} if (isUntypedSignatureInJSFile) { flags |= 32 /* IsUntypedSignatureInJSFile */; } + for (let i = isJSConstructSignature ? 1 : 0; i < declaration.parameters.length; i++) { const param = declaration.parameters[i]; let paramSymbol = param.symbol; const type = isJSDocParameterTag(param) ? param.typeExpression && param.typeExpression.type : param.type; if (paramSymbol && !!(paramSymbol.flags & 4 /* Property */) && !isBindingPattern(param.name)) { - const resolvedSymbol = resolveName( - param, - paramSymbol.escapedName, - 111551 /* Value */, - /*nameNotFoundMessage*/ - void 0, - /*nameArg*/ - void 0, - /*isUse*/ - false - ); + const resolvedSymbol = resolveName(param, paramSymbol.escapedName, 111551 /* Value */, /*nameNotFoundMessage*/ + void 0, /*nameArg*/ + void 0, /*isUse*/ + false); paramSymbol = resolvedSymbol; } if (i === 0 && paramSymbol.escapedName === "this" /* This */) { @@ -57685,6 +53771,7 @@ ${lanes.join("\n")} if (type && type.kind === 201 /* LiteralType */) { flags |= 2 /* HasLiteralTypes */; } + const isOptionalParameter2 = isOptionalJSDocPropertyLikeTag(param) || param.initializer || param.questionToken || isRestParameter(param) || iife && parameters.length > iife.arguments.length && !type || isJSDocOptionalParameter(param); if (!isOptionalParameter2) { minArgumentCount = parameters.length; @@ -57709,21 +53796,14 @@ ${lanes.join("\n")} if (hasRestParameter(declaration) || isInJSFile(declaration) && maybeAddJsSyntheticRestParameter(declaration, parameters)) { flags |= 1 /* HasRestParameter */; } + if (isConstructorTypeNode(declaration) && hasSyntacticModifier(declaration, 64 /* Abstract */) || isConstructorDeclaration(declaration) && hasSyntacticModifier(declaration.parent, 64 /* Abstract */)) { flags |= 4 /* Abstract */; } - links.resolvedSignature = createSignature( - declaration, - typeParameters, - thisParameter, - parameters, - /*resolvedReturnType*/ - void 0, - /*resolvedTypePredicate*/ - void 0, - minArgumentCount, - flags - ); + + links.resolvedSignature = createSignature(declaration, typeParameters, thisParameter, parameters, /*resolvedReturnType*/ + void 0, /*resolvedTypePredicate*/ + void 0, minArgumentCount, flags); } return links.resolvedSignature; } @@ -57733,7 +53813,7 @@ ${lanes.join("\n")} } const lastParam = lastOrUndefined(declaration.parameters); const lastParamTags = lastParam ? getJSDocParameterTags(lastParam) : getJSDocTags(declaration).filter(isJSDocParameterTag); - const lastParamVariadicType = firstDefined(lastParamTags, (p) => p.typeExpression && isJSDocVariadicType(p.typeExpression.type) ? p.typeExpression.type : void 0); + const lastParamVariadicType = firstDefined(lastParamTags, p => p.typeExpression && isJSDocVariadicType(p.typeExpression.type) ? p.typeExpression.type : void 0); const syntheticArgsSymbol = createSymbol(3 /* Variable */, "args", 32768 /* RestParameter */); if (lastParamVariadicType) { syntheticArgsSymbol.links.type = createArrayType(getTypeFromTypeNode(lastParamVariadicType.type)); @@ -57750,15 +53830,13 @@ ${lanes.join("\n")} 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); } @@ -57777,8 +53855,7 @@ ${lanes.join("\n")} } 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; @@ -57798,13 +53875,11 @@ ${lanes.join("\n")} } } 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) { @@ -57831,9 +53906,7 @@ ${lanes.join("\n")} continue; } } - result.push( - !isFunctionExpressionOrArrowFunction(decl) && !isObjectLiteralMethod(decl) && getSignatureOfTypeTag(decl) || getSignatureFromDeclaration(decl) - ); + result.push(!isFunctionExpressionOrArrowFunction(decl) && !isObjectLiteralMethod(decl) && getSignatureOfTypeTag(decl) || getSignatureFromDeclaration(decl)); } return result; } @@ -57877,14 +53950,9 @@ ${lanes.join("\n")} function createTypePredicateFromTypePredicateNode(node, signature) { const parameterName = node.parameterName; const type = node.type && getTypeFromTypeNode(node.type); - return parameterName.kind === 197 /* ThisType */ ? createTypePredicate( - node.assertsModifier ? 2 /* AssertsThis */ : 0 /* This */, - /*parameterName*/ - void 0, - /*parameterIndex*/ - void 0, - type - ) : createTypePredicate(node.assertsModifier ? 3 /* AssertsIdentifier */ : 1 /* Identifier */, parameterName.escapedText, findIndex(signature.parameters, (p) => p.escapedName === parameterName.escapedText), type); + return parameterName.kind === 197 /* ThisType */ ? createTypePredicate(node.assertsModifier ? 2 /* AssertsThis */ : 0 /* This */, /*parameterName*/ + void 0, /*parameterIndex*/ + void 0, type) : createTypePredicate(node.assertsModifier ? 3 /* AssertsIdentifier */ : 1 /* Identifier */, parameterName.escapedText, findIndex(signature.parameters, p => p.escapedName === parameterName.escapedText), type); } function getUnionOrIntersectionType(types, kind, unionReduction) { return kind !== 2097152 /* Intersection */ ? getUnionType(types, unionReduction) : getIntersectionType(types); @@ -57980,7 +54048,7 @@ ${lanes.join("\n")} return instantiatedSignature; } function getSignatureInstantiationWithoutFillingInTypeArguments(signature, typeArguments) { - const instantiations = signature.instantiations || (signature.instantiations = /* @__PURE__ */ new Map()); + const instantiations = signature.instantiations || (signature.instantiations = /* @__PURE__ */new Map()); const id = getTypeListId(typeArguments); let instantiation = instantiations.get(id); if (!instantiation) { @@ -57989,12 +54057,8 @@ ${lanes.join("\n")} return instantiation; } function createSignatureInstantiation(signature, typeArguments) { - return instantiateSignature( - signature, - createSignatureTypeMapper(signature, typeArguments), - /*eraseTypeParameters*/ - true - ); + return instantiateSignature(signature, createSignatureTypeMapper(signature, typeArguments), /*eraseTypeParameters*/ + true); } function createSignatureTypeMapper(signature, typeArguments) { return createTypeMapper(signature.typeParameters, typeArguments); @@ -58003,22 +54067,14 @@ ${lanes.join("\n")} return signature.typeParameters ? signature.erasedSignatureCache || (signature.erasedSignatureCache = createErasedSignature(signature)) : signature; } function createErasedSignature(signature) { - return instantiateSignature( - signature, - createTypeEraser(signature.typeParameters), - /*eraseTypeParameters*/ - true - ); + return instantiateSignature(signature, createTypeEraser(signature.typeParameters), /*eraseTypeParameters*/ + true); } function getCanonicalSignature(signature) { return signature.typeParameters ? signature.canonicalSignatureCache || (signature.canonicalSignatureCache = createCanonicalSignature(signature)) : signature; } function createCanonicalSignature(signature) { - return getSignatureInstantiation( - signature, - map(signature.typeParameters, (tp) => tp.target && !getConstraintOfTypeParameter(tp.target) ? tp.target : tp), - isInJSFile(signature.declaration) - ); + return getSignatureInstantiation(signature, map(signature.typeParameters, tp => tp.target && !getConstraintOfTypeParameter(tp.target) ? tp.target : tp), isInJSFile(signature.declaration)); } function getBaseSignature(signature) { const typeParameters = signature.typeParameters; @@ -58027,18 +54083,14 @@ ${lanes.join("\n")} return signature.baseSignatureCache; } const typeEraser = createTypeEraser(typeParameters); - const baseConstraintMapper = createTypeMapper(typeParameters, map(typeParameters, (tp) => getConstraintOfTypeParameter(tp) || unknownType)); - let baseConstraints = map(typeParameters, (tp) => instantiateType(tp, baseConstraintMapper) || unknownType); + const baseConstraintMapper = createTypeMapper(typeParameters, map(typeParameters, tp => getConstraintOfTypeParameter(tp) || unknownType)); + let baseConstraints = map(typeParameters, tp => instantiateType(tp, baseConstraintMapper) || unknownType); for (let i = 0; i < typeParameters.length - 1; i++) { baseConstraints = instantiateTypes(baseConstraints, baseConstraintMapper); } baseConstraints = instantiateTypes(baseConstraints, typeEraser); - return signature.baseSignatureCache = instantiateSignature( - signature, - createTypeMapper(typeParameters, baseConstraints), - /*eraseTypeParameters*/ - true - ); + return signature.baseSignatureCache = instantiateSignature(signature, createTypeMapper(typeParameters, baseConstraints), /*eraseTypeParameters*/ + true); } return signature; } @@ -58063,8 +54115,14 @@ ${lanes.join("\n")} function getIndexSymbolFromSymbolTable(symbolTable) { return symbolTable.get("__index" /* Index */); } + function createIndexInfo(keyType, type, isReadonly, declaration) { - return { keyType, type, isReadonly, declaration }; + return { + keyType, + type, + isReadonly, + declaration + }; } function getIndexInfosOfSymbol(symbol) { const indexSymbol = getIndexSymbol(symbol); @@ -58077,7 +54135,7 @@ ${lanes.join("\n")} if (declaration.parameters.length === 1) { const parameter = declaration.parameters[0]; if (parameter.type) { - forEachType(getTypeFromTypeNode(parameter.type), (keyType) => { + forEachType(getTypeFromTypeNode(parameter.type), keyType => { if (isValidIndexKeyType(keyType) && !findIndexInfo(indexInfos, keyType)) { indexInfos.push(createIndexInfo(keyType, declaration.type ? getTypeFromTypeNode(declaration.type) : anyType, hasEffectiveModifier(declaration, 8 /* Readonly */), declaration)); } @@ -58110,12 +54168,9 @@ ${lanes.join("\n")} if (index < typeParameters.length) { const declaredConstraint = getConstraintOfTypeParameter(typeParameters[index]); if (declaredConstraint) { - const mapper = makeDeferredTypeMapper( - typeParameters, - typeParameters.map((_, index2) => () => { - return getEffectiveTypeArgumentAtIndex(typeReference, typeParameters, index2); - }) - ); + const mapper = makeDeferredTypeMapper(typeParameters, typeParameters.map((_, index2) => () => { + return getEffectiveTypeArgumentAtIndex(typeReference, typeParameters, index2); + })); const constraint = instantiateType(declaredConstraint, mapper); if (constraint !== typeParameter) { inferences = append(inferences, constraint); @@ -58199,6 +54254,7 @@ ${lanes.join("\n")} } return result & 458752 /* PropagatingFlags */; } + function tryCreateTypeReference(target, typeArguments) { if (some(typeArguments) && target === emptyGenericType) { return unknownType; @@ -58250,11 +54306,7 @@ ${lanes.join("\n")} type.resolvedTypeArguments = type.mapper ? instantiateTypes(typeArguments, type.mapper) : typeArguments; } else { 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, - type.target.symbol && symbolToString(type.target.symbol) - ); + error2(type.node || currentNode, type.target.symbol ? Diagnostics.Type_arguments_for_0_circularly_reference_themselves : Diagnostics.Tuple_type_arguments_circularly_reference_themselves, type.target.symbol && symbolToString(type.target.symbol)); } } return type.resolvedTypeArguments; @@ -58273,24 +54325,17 @@ ${lanes.join("\n")} if (!isJsImplicitAny && (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length)) { const missingAugmentsTag = isJs && isExpressionWithTypeArguments(node) && !isJSDocAugmentsTag(node.parent); const diag2 = minTypeArgumentCount === typeParameters.length ? missingAugmentsTag ? Diagnostics.Expected_0_type_arguments_provide_these_with_an_extends_tag : Diagnostics.Generic_type_0_requires_1_type_argument_s : missingAugmentsTag ? Diagnostics.Expected_0_1_type_arguments_provide_these_with_an_extends_tag : Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments; - const typeStr = typeToString( - type, - /*enclosingDeclaration*/ - void 0, - 2 /* WriteArrayAsGenericType */ - ); + const typeStr = typeToString(type, /*enclosingDeclaration*/ + void 0, 2 /* WriteArrayAsGenericType */); + error2(node, diag2, typeStr, minTypeArgumentCount, typeParameters.length); if (!isJs) { return errorType; } } if (node.kind === 183 /* TypeReference */ && isDeferredTypeReferenceNode(node, length(node.typeArguments) !== typeParameters.length)) { - return createDeferredTypeReference( - type, - node, - /*mapper*/ - void 0 - ); + return createDeferredTypeReference(type, node, /*mapper*/ + void 0); } const typeArguments = concatenate(type.outerTypeParameters, fillMissingTypeArguments(typeArgumentsFromTypeReferenceNode(node), typeParameters, minTypeArgumentCount, isJs)); return createTypeReference(type, typeArguments); @@ -58317,13 +54362,8 @@ ${lanes.join("\n")} const id = getAliasId(symbol, typeArguments); let errorType2 = errorTypes.get(id); if (!errorType2) { - errorType2 = createIntrinsicType( - 1 /* Any */, - "error", - /*objectFlags*/ - void 0, - `alias ${id}` - ); + errorType2 = createIntrinsicType(1 /* Any */, "error", /*objectFlags*/ + void 0, `alias ${id}`); errorType2.aliasSymbol = symbol; errorType2.aliasTypeArguments = typeArguments; errorTypes.set(id, errorType2); @@ -58336,13 +54376,7 @@ ${lanes.join("\n")} const numTypeArguments = length(node.typeArguments); const minTypeArgumentCount = getMinTypeArgumentCount(typeParameters); if (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length) { - error2( - node, - minTypeArgumentCount === typeParameters.length ? Diagnostics.Generic_type_0_requires_1_type_argument_s : Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments, - symbolToString(symbol), - minTypeArgumentCount, - typeParameters.length - ); + error2(node, minTypeArgumentCount === typeParameters.length ? Diagnostics.Generic_type_0_requires_1_type_argument_s : Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments, symbolToString(symbol), minTypeArgumentCount, typeParameters.length); return errorType; } const aliasSymbol = getAliasSymbolForTypeNode(node); @@ -58351,12 +54385,8 @@ ${lanes.join("\n")} if (newAliasSymbol) { aliasTypeArguments = getTypeArgumentsForAliasSymbol(newAliasSymbol); } else if (isTypeReferenceType(node)) { - const aliasSymbol2 = resolveTypeReferenceName( - node, - 2097152 /* Alias */, - /*ignoreErrors*/ - true - ); + const aliasSymbol2 = resolveTypeReferenceName(node, 2097152 /* Alias */, /*ignoreErrors*/ + true); if (aliasSymbol2 && aliasSymbol2 !== unknownSymbol) { const resolved = resolveAlias(aliasSymbol2); if (resolved && resolved.flags & 524288 /* TypeAlias */) { @@ -58510,6 +54540,7 @@ ${lanes.join("\n")} function isJSDocTypeReference(node) { return !!(node.flags & 16777216 /* JSDoc */) && (node.kind === 183 /* TypeReference */ || node.kind === 205 /* ImportType */); } + function checkNoTypeArguments(node, symbol) { if (node.typeArguments) { error2(node, Diagnostics.Type_0_is_not_generic, symbol ? symbolToString(symbol) : node.typeName ? declarationNameToString(node.typeName) : anon); @@ -58552,20 +54583,10 @@ ${lanes.join("\n")} if (isJSDocIndexSignature(node)) { const indexed = getTypeFromTypeNode(typeArgs[0]); const target = getTypeFromTypeNode(typeArgs[1]); - const indexInfo = indexed === stringType || indexed === numberType ? [createIndexInfo( - indexed, - target, - /*isReadonly*/ - false - )] : emptyArray; - return createAnonymousType( - /*symbol*/ - void 0, - emptySymbols, - emptyArray, - emptyArray, - indexInfo - ); + const indexInfo = indexed === stringType || indexed === numberType ? [createIndexInfo(indexed, target, /*isReadonly*/ + false)] : emptyArray; + return createAnonymousType( /*symbol*/ + void 0, emptySymbols, emptyArray, emptyArray, indexInfo); } return anyType; } @@ -58591,12 +54612,8 @@ ${lanes.join("\n")} if (isJSDocTypeReference(node)) { type = getIntendedTypeFromJSDocTypeReference(node); if (!type) { - symbol = resolveTypeReferenceName( - node, - meaning, - /*ignoreErrors*/ - true - ); + symbol = resolveTypeReferenceName(node, meaning, /*ignoreErrors*/ + true); if (symbol === unknownSymbol) { symbol = resolveTypeReferenceName(node, meaning | 111551 /* Value */); } else { @@ -58672,51 +54689,30 @@ ${lanes.join("\n")} return symbol; } function getGlobalSymbol(name, meaning, diagnostic) { - return resolveName( - /*location*/ - void 0, - name, - meaning, - diagnostic, - name, - /*isUse*/ - false, - /*excludeGlobals*/ - false, - /*getSpellingSuggestions*/ - false - ); + return resolveName( /*location*/ + void 0, name, meaning, diagnostic, name, /*isUse*/ + false, /*excludeGlobals*/ + false, /*getSpellingSuggestions*/ + false); } function getGlobalType(name, arity, reportErrors2) { const symbol = getGlobalTypeSymbol(name, reportErrors2); return symbol || reportErrors2 ? getTypeOfGlobalSymbol(symbol, arity) : void 0; } function getGlobalTypedPropertyDescriptorType() { - return deferredGlobalTypedPropertyDescriptorType || (deferredGlobalTypedPropertyDescriptorType = getGlobalType( - "TypedPropertyDescriptor", - /*arity*/ - 1, - /*reportErrors*/ - true - ) || emptyGenericType); + return deferredGlobalTypedPropertyDescriptorType || (deferredGlobalTypedPropertyDescriptorType = getGlobalType("TypedPropertyDescriptor", /*arity*/ + 1, /*reportErrors*/ + true) || emptyGenericType); } function getGlobalTemplateStringsArrayType() { - return deferredGlobalTemplateStringsArrayType || (deferredGlobalTemplateStringsArrayType = getGlobalType( - "TemplateStringsArray", - /*arity*/ - 0, - /*reportErrors*/ - true - ) || emptyObjectType); + return deferredGlobalTemplateStringsArrayType || (deferredGlobalTemplateStringsArrayType = getGlobalType("TemplateStringsArray", /*arity*/ + 0, /*reportErrors*/ + true) || emptyObjectType); } function getGlobalImportMetaType() { - return deferredGlobalImportMetaType || (deferredGlobalImportMetaType = getGlobalType( - "ImportMeta", - /*arity*/ - 0, - /*reportErrors*/ - true - ) || emptyObjectType); + return deferredGlobalImportMetaType || (deferredGlobalImportMetaType = getGlobalType("ImportMeta", /*arity*/ + 0, /*reportErrors*/ + true) || emptyObjectType); } function getGlobalImportMetaExpressionType() { if (!deferredGlobalImportMetaExpressionType) { @@ -58732,12 +54728,8 @@ ${lanes.join("\n")} return deferredGlobalImportMetaExpressionType; } function getGlobalImportCallOptionsType(reportErrors2) { - return deferredGlobalImportCallOptionsType || (deferredGlobalImportCallOptionsType = getGlobalType( - "ImportCallOptions", - /*arity*/ - 0, - reportErrors2 - )) || emptyObjectType; + return deferredGlobalImportCallOptionsType || (deferredGlobalImportCallOptionsType = getGlobalType("ImportCallOptions", /*arity*/ + 0, reportErrors2)) || emptyObjectType; } function getGlobalESSymbolConstructorSymbol(reportErrors2) { return deferredGlobalESSymbolConstructorSymbol || (deferredGlobalESSymbolConstructorSymbol = getGlobalValueSymbol("Symbol", reportErrors2)); @@ -58746,263 +54738,148 @@ ${lanes.join("\n")} return deferredGlobalESSymbolConstructorTypeSymbol || (deferredGlobalESSymbolConstructorTypeSymbol = getGlobalTypeSymbol("SymbolConstructor", reportErrors2)); } function getGlobalESSymbolType() { - return deferredGlobalESSymbolType || (deferredGlobalESSymbolType = getGlobalType( - "Symbol", - /*arity*/ - 0, - /*reportErrors*/ - false - )) || emptyObjectType; + return deferredGlobalESSymbolType || (deferredGlobalESSymbolType = getGlobalType("Symbol", /*arity*/ + 0, /*reportErrors*/ + false)) || emptyObjectType; } function getGlobalPromiseType(reportErrors2) { - return deferredGlobalPromiseType || (deferredGlobalPromiseType = getGlobalType( - "Promise", - /*arity*/ - 1, - reportErrors2 - )) || emptyGenericType; + return deferredGlobalPromiseType || (deferredGlobalPromiseType = getGlobalType("Promise", /*arity*/ + 1, reportErrors2)) || emptyGenericType; } function getGlobalPromiseLikeType(reportErrors2) { - return deferredGlobalPromiseLikeType || (deferredGlobalPromiseLikeType = getGlobalType( - "PromiseLike", - /*arity*/ - 1, - reportErrors2 - )) || emptyGenericType; + return deferredGlobalPromiseLikeType || (deferredGlobalPromiseLikeType = getGlobalType("PromiseLike", /*arity*/ + 1, reportErrors2)) || emptyGenericType; } function getGlobalPromiseConstructorSymbol(reportErrors2) { return deferredGlobalPromiseConstructorSymbol || (deferredGlobalPromiseConstructorSymbol = getGlobalValueSymbol("Promise", reportErrors2)); } function getGlobalPromiseConstructorLikeType(reportErrors2) { - return deferredGlobalPromiseConstructorLikeType || (deferredGlobalPromiseConstructorLikeType = getGlobalType( - "PromiseConstructorLike", - /*arity*/ - 0, - reportErrors2 - )) || emptyObjectType; + return deferredGlobalPromiseConstructorLikeType || (deferredGlobalPromiseConstructorLikeType = getGlobalType("PromiseConstructorLike", /*arity*/ + 0, reportErrors2)) || emptyObjectType; } function getGlobalAsyncIterableType(reportErrors2) { - return deferredGlobalAsyncIterableType || (deferredGlobalAsyncIterableType = getGlobalType( - "AsyncIterable", - /*arity*/ - 1, - reportErrors2 - )) || emptyGenericType; + return deferredGlobalAsyncIterableType || (deferredGlobalAsyncIterableType = getGlobalType("AsyncIterable", /*arity*/ + 1, reportErrors2)) || emptyGenericType; } function getGlobalAsyncIteratorType(reportErrors2) { - return deferredGlobalAsyncIteratorType || (deferredGlobalAsyncIteratorType = getGlobalType( - "AsyncIterator", - /*arity*/ - 3, - reportErrors2 - )) || emptyGenericType; + return deferredGlobalAsyncIteratorType || (deferredGlobalAsyncIteratorType = getGlobalType("AsyncIterator", /*arity*/ + 3, reportErrors2)) || emptyGenericType; } function getGlobalAsyncIterableIteratorType(reportErrors2) { - return deferredGlobalAsyncIterableIteratorType || (deferredGlobalAsyncIterableIteratorType = getGlobalType( - "AsyncIterableIterator", - /*arity*/ - 1, - reportErrors2 - )) || emptyGenericType; + return deferredGlobalAsyncIterableIteratorType || (deferredGlobalAsyncIterableIteratorType = getGlobalType("AsyncIterableIterator", /*arity*/ + 1, reportErrors2)) || emptyGenericType; } function getGlobalAsyncGeneratorType(reportErrors2) { - return deferredGlobalAsyncGeneratorType || (deferredGlobalAsyncGeneratorType = getGlobalType( - "AsyncGenerator", - /*arity*/ - 3, - reportErrors2 - )) || emptyGenericType; + return deferredGlobalAsyncGeneratorType || (deferredGlobalAsyncGeneratorType = getGlobalType("AsyncGenerator", /*arity*/ + 3, reportErrors2)) || emptyGenericType; } function getGlobalIterableType(reportErrors2) { - return deferredGlobalIterableType || (deferredGlobalIterableType = getGlobalType( - "Iterable", - /*arity*/ - 1, - reportErrors2 - )) || emptyGenericType; + return deferredGlobalIterableType || (deferredGlobalIterableType = getGlobalType("Iterable", /*arity*/ + 1, reportErrors2)) || emptyGenericType; } function getGlobalIteratorType(reportErrors2) { - return deferredGlobalIteratorType || (deferredGlobalIteratorType = getGlobalType( - "Iterator", - /*arity*/ - 3, - reportErrors2 - )) || emptyGenericType; + return deferredGlobalIteratorType || (deferredGlobalIteratorType = getGlobalType("Iterator", /*arity*/ + 3, reportErrors2)) || emptyGenericType; } function getGlobalIterableIteratorType(reportErrors2) { - return deferredGlobalIterableIteratorType || (deferredGlobalIterableIteratorType = getGlobalType( - "IterableIterator", - /*arity*/ - 1, - reportErrors2 - )) || emptyGenericType; + return deferredGlobalIterableIteratorType || (deferredGlobalIterableIteratorType = getGlobalType("IterableIterator", /*arity*/ + 1, reportErrors2)) || emptyGenericType; } function getGlobalGeneratorType(reportErrors2) { - return deferredGlobalGeneratorType || (deferredGlobalGeneratorType = getGlobalType( - "Generator", - /*arity*/ - 3, - reportErrors2 - )) || emptyGenericType; + return deferredGlobalGeneratorType || (deferredGlobalGeneratorType = getGlobalType("Generator", /*arity*/ + 3, reportErrors2)) || emptyGenericType; } function getGlobalIteratorYieldResultType(reportErrors2) { - return deferredGlobalIteratorYieldResultType || (deferredGlobalIteratorYieldResultType = getGlobalType( - "IteratorYieldResult", - /*arity*/ - 1, - reportErrors2 - )) || emptyGenericType; + return deferredGlobalIteratorYieldResultType || (deferredGlobalIteratorYieldResultType = getGlobalType("IteratorYieldResult", /*arity*/ + 1, reportErrors2)) || emptyGenericType; } function getGlobalIteratorReturnResultType(reportErrors2) { - return deferredGlobalIteratorReturnResultType || (deferredGlobalIteratorReturnResultType = getGlobalType( - "IteratorReturnResult", - /*arity*/ - 1, - reportErrors2 - )) || emptyGenericType; + return deferredGlobalIteratorReturnResultType || (deferredGlobalIteratorReturnResultType = getGlobalType("IteratorReturnResult", /*arity*/ + 1, reportErrors2)) || emptyGenericType; } function getGlobalDisposableType(reportErrors2) { - return deferredGlobalDisposableType || (deferredGlobalDisposableType = getGlobalType( - "Disposable", - /*arity*/ - 0, - reportErrors2 - )) || emptyObjectType; + return deferredGlobalDisposableType || (deferredGlobalDisposableType = getGlobalType("Disposable", /*arity*/ + 0, reportErrors2)) || emptyObjectType; } function getGlobalAsyncDisposableType(reportErrors2) { - return deferredGlobalAsyncDisposableType || (deferredGlobalAsyncDisposableType = getGlobalType( - "AsyncDisposable", - /*arity*/ - 0, - reportErrors2 - )) || emptyObjectType; + return deferredGlobalAsyncDisposableType || (deferredGlobalAsyncDisposableType = getGlobalType("AsyncDisposable", /*arity*/ + 0, reportErrors2)) || emptyObjectType; } function getGlobalTypeOrUndefined(name, arity = 0) { - const symbol = getGlobalSymbol( - name, - 788968 /* Type */, - /*diagnostic*/ - void 0 - ); + const symbol = getGlobalSymbol(name, 788968 /* Type */, /*diagnostic*/ + void 0); return symbol && getTypeOfGlobalSymbol(symbol, arity); } function getGlobalExtractSymbol() { - deferredGlobalExtractSymbol || (deferredGlobalExtractSymbol = getGlobalTypeAliasSymbol( - "Extract", - /*arity*/ - 2, - /*reportErrors*/ - true - ) || unknownSymbol); + deferredGlobalExtractSymbol || (deferredGlobalExtractSymbol = getGlobalTypeAliasSymbol("Extract", /*arity*/ + 2, /*reportErrors*/ + true) || unknownSymbol); return deferredGlobalExtractSymbol === unknownSymbol ? void 0 : deferredGlobalExtractSymbol; } function getGlobalOmitSymbol() { - deferredGlobalOmitSymbol || (deferredGlobalOmitSymbol = getGlobalTypeAliasSymbol( - "Omit", - /*arity*/ - 2, - /*reportErrors*/ - true - ) || unknownSymbol); + deferredGlobalOmitSymbol || (deferredGlobalOmitSymbol = getGlobalTypeAliasSymbol("Omit", /*arity*/ + 2, /*reportErrors*/ + true) || unknownSymbol); return deferredGlobalOmitSymbol === unknownSymbol ? void 0 : deferredGlobalOmitSymbol; } function getGlobalAwaitedSymbol(reportErrors2) { - deferredGlobalAwaitedSymbol || (deferredGlobalAwaitedSymbol = getGlobalTypeAliasSymbol( - "Awaited", - /*arity*/ - 1, - reportErrors2 - ) || (reportErrors2 ? unknownSymbol : void 0)); + deferredGlobalAwaitedSymbol || (deferredGlobalAwaitedSymbol = getGlobalTypeAliasSymbol("Awaited", /*arity*/ + 1, reportErrors2) || (reportErrors2 ? unknownSymbol : void 0)); return deferredGlobalAwaitedSymbol === unknownSymbol ? void 0 : deferredGlobalAwaitedSymbol; } function getGlobalBigIntType() { - return deferredGlobalBigIntType || (deferredGlobalBigIntType = getGlobalType( - "BigInt", - /*arity*/ - 0, - /*reportErrors*/ - false - )) || emptyObjectType; + return deferredGlobalBigIntType || (deferredGlobalBigIntType = getGlobalType("BigInt", /*arity*/ + 0, /*reportErrors*/ + false)) || emptyObjectType; } function getGlobalClassDecoratorContextType(reportErrors2) { - return deferredGlobalClassDecoratorContextType ?? (deferredGlobalClassDecoratorContextType = getGlobalType( - "ClassDecoratorContext", - /*arity*/ - 1, - reportErrors2 - )) ?? emptyGenericType; + var _ref17, _deferredGlobalClassD; + return (_ref17 = (_deferredGlobalClassD = deferredGlobalClassDecoratorContextType) !== null && _deferredGlobalClassD !== void 0 ? _deferredGlobalClassD : deferredGlobalClassDecoratorContextType = getGlobalType("ClassDecoratorContext", /*arity*/ + 1, reportErrors2)) !== null && _ref17 !== void 0 ? _ref17 : emptyGenericType; } function getGlobalClassMethodDecoratorContextType(reportErrors2) { - return deferredGlobalClassMethodDecoratorContextType ?? (deferredGlobalClassMethodDecoratorContextType = getGlobalType( - "ClassMethodDecoratorContext", - /*arity*/ - 2, - reportErrors2 - )) ?? emptyGenericType; + var _ref18, _deferredGlobalClassM; + return (_ref18 = (_deferredGlobalClassM = deferredGlobalClassMethodDecoratorContextType) !== null && _deferredGlobalClassM !== void 0 ? _deferredGlobalClassM : deferredGlobalClassMethodDecoratorContextType = getGlobalType("ClassMethodDecoratorContext", /*arity*/ + 2, reportErrors2)) !== null && _ref18 !== void 0 ? _ref18 : emptyGenericType; } function getGlobalClassGetterDecoratorContextType(reportErrors2) { - return deferredGlobalClassGetterDecoratorContextType ?? (deferredGlobalClassGetterDecoratorContextType = getGlobalType( - "ClassGetterDecoratorContext", - /*arity*/ - 2, - reportErrors2 - )) ?? emptyGenericType; + var _ref19, _deferredGlobalClassG; + return (_ref19 = (_deferredGlobalClassG = deferredGlobalClassGetterDecoratorContextType) !== null && _deferredGlobalClassG !== void 0 ? _deferredGlobalClassG : deferredGlobalClassGetterDecoratorContextType = getGlobalType("ClassGetterDecoratorContext", /*arity*/ + 2, reportErrors2)) !== null && _ref19 !== void 0 ? _ref19 : emptyGenericType; } function getGlobalClassSetterDecoratorContextType(reportErrors2) { - return deferredGlobalClassSetterDecoratorContextType ?? (deferredGlobalClassSetterDecoratorContextType = getGlobalType( - "ClassSetterDecoratorContext", - /*arity*/ - 2, - reportErrors2 - )) ?? emptyGenericType; + var _ref20, _deferredGlobalClassS; + return (_ref20 = (_deferredGlobalClassS = deferredGlobalClassSetterDecoratorContextType) !== null && _deferredGlobalClassS !== void 0 ? _deferredGlobalClassS : deferredGlobalClassSetterDecoratorContextType = getGlobalType("ClassSetterDecoratorContext", /*arity*/ + 2, reportErrors2)) !== null && _ref20 !== void 0 ? _ref20 : emptyGenericType; } function getGlobalClassAccessorDecoratorContextType(reportErrors2) { - return deferredGlobalClassAccessorDecoratorContextType ?? (deferredGlobalClassAccessorDecoratorContextType = getGlobalType( - "ClassAccessorDecoratorContext", - /*arity*/ - 2, - reportErrors2 - )) ?? emptyGenericType; + var _ref21, _deferredGlobalClassA; + return (_ref21 = (_deferredGlobalClassA = deferredGlobalClassAccessorDecoratorContextType) !== null && _deferredGlobalClassA !== void 0 ? _deferredGlobalClassA : deferredGlobalClassAccessorDecoratorContextType = getGlobalType("ClassAccessorDecoratorContext", /*arity*/ + 2, reportErrors2)) !== null && _ref21 !== void 0 ? _ref21 : emptyGenericType; } function getGlobalClassAccessorDecoratorTargetType(reportErrors2) { - return deferredGlobalClassAccessorDecoratorTargetType ?? (deferredGlobalClassAccessorDecoratorTargetType = getGlobalType( - "ClassAccessorDecoratorTarget", - /*arity*/ - 2, - reportErrors2 - )) ?? emptyGenericType; + var _ref22, _deferredGlobalClassA2; + return (_ref22 = (_deferredGlobalClassA2 = deferredGlobalClassAccessorDecoratorTargetType) !== null && _deferredGlobalClassA2 !== void 0 ? _deferredGlobalClassA2 : deferredGlobalClassAccessorDecoratorTargetType = getGlobalType("ClassAccessorDecoratorTarget", /*arity*/ + 2, reportErrors2)) !== null && _ref22 !== void 0 ? _ref22 : emptyGenericType; } function getGlobalClassAccessorDecoratorResultType(reportErrors2) { - return deferredGlobalClassAccessorDecoratorResultType ?? (deferredGlobalClassAccessorDecoratorResultType = getGlobalType( - "ClassAccessorDecoratorResult", - /*arity*/ - 2, - reportErrors2 - )) ?? emptyGenericType; + var _ref23, _deferredGlobalClassA3; + return (_ref23 = (_deferredGlobalClassA3 = deferredGlobalClassAccessorDecoratorResultType) !== null && _deferredGlobalClassA3 !== void 0 ? _deferredGlobalClassA3 : deferredGlobalClassAccessorDecoratorResultType = getGlobalType("ClassAccessorDecoratorResult", /*arity*/ + 2, reportErrors2)) !== null && _ref23 !== void 0 ? _ref23 : emptyGenericType; } function getGlobalClassFieldDecoratorContextType(reportErrors2) { - return deferredGlobalClassFieldDecoratorContextType ?? (deferredGlobalClassFieldDecoratorContextType = getGlobalType( - "ClassFieldDecoratorContext", - /*arity*/ - 2, - reportErrors2 - )) ?? emptyGenericType; + var _ref24, _deferredGlobalClassF; + return (_ref24 = (_deferredGlobalClassF = deferredGlobalClassFieldDecoratorContextType) !== null && _deferredGlobalClassF !== void 0 ? _deferredGlobalClassF : deferredGlobalClassFieldDecoratorContextType = getGlobalType("ClassFieldDecoratorContext", /*arity*/ + 2, reportErrors2)) !== null && _ref24 !== void 0 ? _ref24 : emptyGenericType; } function getGlobalNaNSymbol() { - return deferredGlobalNaNSymbol || (deferredGlobalNaNSymbol = getGlobalValueSymbol( - "NaN", - /*reportErrors*/ - false - )); + return deferredGlobalNaNSymbol || (deferredGlobalNaNSymbol = getGlobalValueSymbol("NaN", /*reportErrors*/ + false)); } function getGlobalRecordSymbol() { - deferredGlobalRecordSymbol || (deferredGlobalRecordSymbol = getGlobalTypeAliasSymbol( - "Record", - /*arity*/ - 2, - /*reportErrors*/ - true - ) || unknownSymbol); + deferredGlobalRecordSymbol || (deferredGlobalRecordSymbol = getGlobalTypeAliasSymbol("Record", /*arity*/ + 2, /*reportErrors*/ + true) || unknownSymbol); return deferredGlobalRecordSymbol === unknownSymbol ? void 0 : deferredGlobalRecordSymbol; } function createTypeFromGenericGlobalType(genericGlobalType, typeArguments) { @@ -59012,10 +54889,8 @@ ${lanes.join("\n")} return createTypeFromGenericGlobalType(getGlobalTypedPropertyDescriptorType(), [propertyType]); } function createIterableType(iteratedType) { - return createTypeFromGenericGlobalType(getGlobalIterableType( - /*reportErrors*/ - true - ), [iteratedType]); + return createTypeFromGenericGlobalType(getGlobalIterableType( /*reportErrors*/ + true), [iteratedType]); } function createArrayType(elementType, readonly) { return createTypeFromGenericGlobalType(readonly ? globalReadonlyArrayType : globalArrayType, [elementType]); @@ -59032,9 +54907,11 @@ ${lanes.join("\n")} return 1 /* Required */; } } + function getRestTypeElementFlags(node) { return getArrayElementTypeNode(node.type) ? 4 /* Rest */ : 8 /* Variadic */; } + function getArrayOrTupleTargetType(node) { const readonly = isReadonlyTypeOperator(node.parent); const elementType = getArrayElementTypeNode(node); @@ -59103,13 +54980,9 @@ ${lanes.join("\n")} const target = getArrayOrTupleTargetType(node); if (target === emptyGenericType) { links.resolvedType = emptyObjectType; - } else if (!(node.kind === 189 /* TupleType */ && some(node.elements, (e) => !!(getTupleElementFlags(e) & 8 /* Variadic */))) && isDeferredTypeReferenceNode(node)) { - links.resolvedType = node.kind === 189 /* TupleType */ && node.elements.length === 0 ? target : createDeferredTypeReference( - target, - node, - /*mapper*/ - void 0 - ); + } else if (!(node.kind === 189 /* TupleType */ && some(node.elements, e => !!(getTupleElementFlags(e) & 8 /* Variadic */))) && isDeferredTypeReferenceNode(node)) { + links.resolvedType = node.kind === 189 /* TupleType */ && node.elements.length === 0 ? target : createDeferredTypeReference(target, node, /*mapper*/ + void 0); } else { const elementTypes = node.kind === 188 /* ArrayType */ ? [getTypeFromTypeNode(node.elementType)] : map(node.elements, getTypeFromTypeNode); links.resolvedType = createNormalizedTypeReference(target, elementTypes); @@ -59120,15 +54993,16 @@ ${lanes.join("\n")} function isReadonlyTypeOperator(node) { return isTypeOperatorNode(node) && node.operator === 148 /* ReadonlyKeyword */; } + function createTupleType(elementTypes, elementFlags, readonly = false, namedMemberDeclarations = []) { - const tupleTarget = getTupleTargetType(elementFlags || map(elementTypes, (_) => 1 /* Required */), readonly, namedMemberDeclarations); + const tupleTarget = getTupleTargetType(elementFlags || map(elementTypes, _ => 1 /* Required */), readonly, namedMemberDeclarations); return tupleTarget === emptyGenericType ? emptyObjectType : elementTypes.length ? createNormalizedTypeReference(tupleTarget, elementTypes) : tupleTarget; } function getTupleTargetType(elementFlags, readonly, namedMemberDeclarations) { if (elementFlags.length === 1 && elementFlags[0] & 4 /* Rest */) { return readonly ? globalReadonlyArrayType : globalArrayType; } - const key = map(elementFlags, (f) => f & 1 /* Required */ ? "#" : f & 2 /* Optional */ ? "?" : f & 4 /* Rest */ ? "." : "*").join() + (readonly ? "R" : "") + (some(namedMemberDeclarations, (node) => !!node) ? "," + map(namedMemberDeclarations, (node) => node ? getNodeId(node) : "_").join(",") : ""); + const key = map(elementFlags, f => f & 1 /* Required */ ? "#" : f & 2 /* Optional */ ? "?" : f & 4 /* Rest */ ? "." : "*").join() + (readonly ? "R" : "") + (some(namedMemberDeclarations, node => !!node) ? "," + map(namedMemberDeclarations, node => node ? getNodeId(node) : "_").join(",") : ""); let type = tupleTypes.get(key); if (!type) { tupleTypes.set(key, type = createTupleTargetType(elementFlags, readonly, namedMemberDeclarations)); @@ -59137,7 +55011,7 @@ ${lanes.join("\n")} } function createTupleTargetType(elementFlags, readonly, namedMemberDeclarations) { const arity = elementFlags.length; - const minLength = countWhere(elementFlags, (f) => !!(f & (1 /* Required */ | 8 /* Variadic */))); + const minLength = countWhere(elementFlags, f => !!(f & (1 /* Required */ | 8 /* Variadic */))); let typeParameters; const properties = []; let combinedFlags = 0; @@ -59161,8 +55035,7 @@ ${lanes.join("\n")} 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); @@ -59170,7 +55043,7 @@ ${lanes.join("\n")} type.typeParameters = typeParameters; type.outerTypeParameters = void 0; type.localTypeParameters = typeParameters; - type.instantiations = /* @__PURE__ */ new Map(); + type.instantiations = /* @__PURE__ */new Map(); type.instantiations.set(getTypeListId(type.typeParameters), type); type.target = type; type.resolvedTypeArguments = type.typeParameters; @@ -59201,7 +55074,7 @@ ${lanes.join("\n")} if (target.combinedFlags & 8 /* Variadic */) { const unionIndex = findIndex(elementTypes, (t, i) => !!(target.elementFlags[i] & 8 /* Variadic */ && t.flags & (131072 /* Never */ | 1048576 /* Union */))); if (unionIndex >= 0) { - return checkCrossProductUnion(map(elementTypes, (t, i) => target.elementFlags[i] & 8 /* Variadic */ ? t : unknownType)) ? mapType(elementTypes[unionIndex], (t) => createNormalizedTupleType(target, replaceElement(elementTypes, unionIndex, t))) : errorType; + return checkCrossProductUnion(map(elementTypes, (t, i) => target.elementFlags[i] & 8 /* Variadic */ ? t : unknownType)) ? mapType(elementTypes[unionIndex], t => createNormalizedTupleType(target, replaceElement(elementTypes, unionIndex, t))) : errorType; } } const expandedTypes = []; @@ -59219,10 +55092,7 @@ ${lanes.join("\n")} } else if (isTupleType(type)) { const elements = getElementTypes(type); if (elements.length + expandedTypes.length >= 1e4) { - error2( - currentNode, - isPartOfTypeNode(currentNode) ? Diagnostics.Type_produces_a_tuple_type_that_is_too_large_to_represent : Diagnostics.Expression_produces_a_tuple_type_that_is_too_large_to_represent - ); + error2(currentNode, isPartOfTypeNode(currentNode) ? Diagnostics.Type_produces_a_tuple_type_that_is_too_large_to_represent : Diagnostics.Expression_produces_a_tuple_type_that_is_too_large_to_represent); return errorType; } forEach(elements, (t, n) => { @@ -59237,9 +55107,9 @@ ${lanes.join("\n")} } } 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)); expandedTypes.splice(firstRestIndex + 1, lastOptionalOrRestIndex - firstRestIndex); @@ -59258,11 +55128,8 @@ ${lanes.join("\n")} if (flags & (2 /* Optional */ | 4 /* Rest */)) { lastOptionalOrRestIndex = expandedFlags.length; } - expandedTypes.push(flags & 2 /* Optional */ ? addOptionality( - type, - /*isProperty*/ - true - ) : type); + expandedTypes.push(flags & 2 /* Optional */ ? addOptionality(type, /*isProperty*/ + true) : type); expandedFlags.push(flags); expandedDeclarations.push(declaration); } @@ -59270,38 +55137,31 @@ ${lanes.join("\n")} function sliceTupleType(type, index, endSkipCount = 0) { const target = type.target; const endIndex = getTypeReferenceArity(type) - endSkipCount; - return index > target.fixedLength ? getRestArrayTypeOfTupleType(type) || createTupleType(emptyArray) : createTupleType( - getTypeArguments(type).slice(index, endIndex), - target.elementFlags.slice(index, endIndex), - /*readonly*/ - false, - target.labeledElementDeclarations && target.labeledElementDeclarations.slice(index, endIndex) - ); + return index > target.fixedLength ? getRestArrayTypeOfTupleType(type) || createTupleType(emptyArray) : createTupleType(getTypeArguments(type).slice(index, endIndex), target.elementFlags.slice(index, endIndex), /*readonly*/ + false, target.labeledElementDeclarations && target.labeledElementDeclarations.slice(index, endIndex)); } function getKnownKeysOfTupleType(type) { - return getUnionType(append(arrayOf(type.target.fixedLength, (i) => getStringLiteralType("" + i)), getIndexType(type.target.readonly ? globalReadonlyArrayType : globalArrayType))); + return getUnionType(append(arrayOf(type.target.fixedLength, i => getStringLiteralType("" + i)), getIndexType(type.target.readonly ? globalReadonlyArrayType : globalArrayType))); } function getStartElementCount(type, flags) { - const index = findIndex(type.elementFlags, (f) => !(f & flags)); + const index = findIndex(type.elementFlags, f => !(f & flags)); return index >= 0 ? index : type.elementFlags.length; } function getEndElementCount(type, flags) { - return type.elementFlags.length - findLastIndex(type.elementFlags, (f) => !(f & flags)) - 1; + return type.elementFlags.length - findLastIndex(type.elementFlags, f => !(f & flags)) - 1; } function getTotalFixedElementCount(type) { return type.fixedLength + getEndElementCount(type, 3 /* Fixed */); } + function getElementTypes(type) { const typeArguments = getTypeArguments(type); const arity = getTypeReferenceArity(type); return typeArguments.length === arity ? typeArguments : typeArguments.slice(0, arity); } function getTypeFromOptionalTypeNode(node) { - return addOptionality( - getTypeFromTypeNode(node.type), - /*isProperty*/ - true - ); + return addOptionality(getTypeFromTypeNode(node.type), /*isProperty*/ + true); } function getTypeId(type) { return type.id; @@ -59321,13 +55181,10 @@ ${lanes.join("\n")} const flags = type.flags; if (!(flags & 131072 /* Never */)) { includes |= flags & 473694207 /* IncludesMask */; - if (flags & 465829888 /* Instantiable */) - includes |= 33554432 /* IncludesInstantiable */; - if (type === wildcardType) - includes |= 8388608 /* IncludesWildcard */; + if (flags & 465829888 /* Instantiable */) includes |= 33554432 /* IncludesInstantiable */; + if (type === wildcardType) includes |= 8388608 /* IncludesWildcard */; 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); @@ -59358,7 +55215,7 @@ ${lanes.join("\n")} if (match) { return match; } - const hasEmptyObject = hasObjectTypes && some(types, (t) => !!(t.flags & 524288 /* Object */) && !isGenericMappedType(t) && isEmptyResolvedType(resolveStructuredTypeMembers(t))); + const hasEmptyObject = hasObjectTypes && some(types, t => !!(t.flags & 524288 /* Object */) && !isGenericMappedType(t) && isEmptyResolvedType(resolveStructuredTypeMembers(t))); const len = types.length; let i = len; let count = 0; @@ -59367,19 +55224,21 @@ ${lanes.join("\n")} const source = types[i]; if (hasEmptyObject || source.flags & 469499904 /* StructuredOrInstantiable */) { if (source.flags & 262144 /* TypeParameter */ && getBaseConstraintOrType(source).flags & 1048576 /* Union */) { - if (isTypeRelatedTo(source, getUnionType(map(types, (t) => t === source ? neverType : t)), strictSubtypeRelation)) { + if (isTypeRelatedTo(source, getUnionType(map(types, t => t === source ? neverType : t)), strictSubtypeRelation)) { orderedRemoveItemAt(types, i); } continue; } - const keyProperty = source.flags & (524288 /* Object */ | 2097152 /* Intersection */ | 58982400 /* InstantiableNonPrimitive */) ? find(getPropertiesOfType(source), (p) => isUnitType(getTypeOfSymbol(p))) : void 0; + const keyProperty = source.flags & (524288 /* Object */ | 2097152 /* Intersection */ | 58982400 /* InstantiableNonPrimitive */) ? find(getPropertiesOfType(source), p => isUnitType(getTypeOfSymbol(p))) : void 0; const keyPropertyType = keyProperty && getRegularTypeOfLiteralType(getTypeOfSymbol(keyProperty)); for (const target of types) { if (source !== target) { if (count === 1e5) { const estimatedCount = count / (len - i) * len; if (estimatedCount > 1e6) { - (_a = tracing) == null ? void 0 : _a.instant(tracing.Phase.CheckTypes, "removeSubtypes_DepthLimit", { typeIds: types.map((t) => t.id) }); + (_a = tracing) == null ? void 0 : _a.instant(tracing.Phase.CheckTypes, "removeSubtypes_DepthLimit", { + typeIds: types.map(t => t.id) + }); error2(currentNode, Diagnostics.Expression_produces_a_union_type_that_is_too_complex_to_represent); return void 0; } @@ -59415,13 +55274,13 @@ ${lanes.join("\n")} } } function removeStringLiteralsMatchedByTemplateLiterals(types) { - const templates = filter(types, (t) => !!(t.flags & 134217728 /* TemplateLiteral */) && isPatternLiteralType(t)); + const templates = filter(types, t => !!(t.flags & 134217728 /* TemplateLiteral */) && isPatternLiteralType(t)); if (templates.length) { let i = types.length; while (i > 0) { i--; const t = types[i]; - if (t.flags & 128 /* StringLiteral */ && some(templates, (template) => isTypeMatchedByTemplateLiteralType(t, template))) { + if (t.flags & 128 /* StringLiteral */ && some(templates, template => isTypeMatchedByTemplateLiteralType(t, template))) { orderedRemoveItemAt(types, i); } } @@ -59460,14 +55319,8 @@ ${lanes.join("\n")} const id = types[index].id + infix + types[1 - index].id + getAliasId(aliasSymbol, aliasTypeArguments); let type = unionOfUnionTypes.get(id); if (!type) { - type = getUnionTypeWorker( - types, - unionReduction, - aliasSymbol, - aliasTypeArguments, - /*origin*/ - void 0 - ); + type = getUnionTypeWorker(types, unionReduction, aliasSymbol, aliasTypeArguments, /*origin*/ + void 0); unionOfUnionTypes.set(id, type); } return type; @@ -59489,6 +55342,7 @@ ${lanes.join("\n")} if (includes & (32 /* Enum */ | 2944 /* Literal */ | 8192 /* UniqueESSymbol */ | 134217728 /* TemplateLiteral */ | 268435456 /* StringMapping */) || includes & 16384 /* Void */ && includes & 32768 /* Undefined */) { removeRedundantLiteralTypes(typeSet, includes, !!(unionReduction & 2 /* Subtype */)); } + if (includes & 128 /* StringLiteral */ && includes & 134217728 /* TemplateLiteral */) { removeStringLiteralsMatchedByTemplateLiterals(typeSet); } @@ -59507,7 +55361,7 @@ ${lanes.join("\n")} addNamedUnions(namedUnions, types); const reducedTypes = []; for (const t of typeSet) { - if (!some(namedUnions, (union) => containsType(union.types, t))) { + if (!some(namedUnions, union => containsType(union.types, t))) { reducedTypes.push(t); } } @@ -59564,11 +55418,9 @@ ${lanes.join("\n")} let type = unionTypes.get(id); if (!type) { type = createType(1048576 /* Union */); - type.objectFlags = precomputedObjectFlags | getPropagatingFlagsOfTypes( - types, - /*excludeKinds*/ - 98304 /* Nullable */ - ); + type.objectFlags = precomputedObjectFlags | getPropagatingFlagsOfTypes(types, /*excludeKinds*/ + 98304 /* Nullable */); + type.types = types; type.origin = origin; type.aliasSymbol = aliasSymbol; @@ -59601,8 +55453,7 @@ ${lanes.join("\n")} } } else { if (flags & 3 /* AnyOrUnknown */) { - if (type === wildcardType) - includes |= 8388608 /* IncludesWildcard */; + if (type === wildcardType) includes |= 8388608 /* IncludesWildcard */; } else if (strictNullChecks || !(flags & 98304 /* Nullable */)) { if (type === missingType) { includes |= 262144 /* IncludesMissingType */; @@ -59612,11 +55463,13 @@ ${lanes.join("\n")} if (type.flags & 109472 /* Unit */ && includes & 109472 /* Unit */) { includes |= 67108864 /* NonPrimitive */; } + typeSet.set(type.id.toString(), type); } } includes |= flags & 473694207 /* IncludesMask */; } + return includes; } function addTypesToIntersection(typeSet, includes, types) { @@ -59649,12 +55502,11 @@ ${lanes.join("\n")} } function extractRedundantTemplateLiterals(types) { let i = types.length; - const literals = filter(types, (t) => !!(t.flags & 128 /* StringLiteral */)); + const literals = filter(types, t => !!(t.flags & 128 /* StringLiteral */)); while (i > 0) { i--; const t = types[i]; - if (!(t.flags & 134217728 /* TemplateLiteral */)) - continue; + if (!(t.flags & 134217728 /* TemplateLiteral */)) continue; for (const t2 of literals) { if (isTypeSubtypeOf(t2, t)) { orderedRemoveItemAt(types, i); @@ -59668,12 +55520,12 @@ ${lanes.join("\n")} } function removeFromEach(types, flag) { for (let i = 0; i < types.length; i++) { - types[i] = filterType(types[i], (t) => !(t.flags & flag)); + types[i] = filterType(types[i], t => !(t.flags & flag)); } } function intersectUnionsOfPrimitiveTypes(types) { let unionTypes2; - const index = findIndex(types, (t) => !!(getObjectFlags(t) & 32768 /* PrimitiveUnion */)); + const index = findIndex(types, t => !!(getObjectFlags(t) & 32768 /* PrimitiveUnion */)); if (index < 0) { return false; } @@ -59706,18 +55558,16 @@ ${lanes.join("\n")} } function createIntersectionType(types, aliasSymbol, aliasTypeArguments) { const result = createType(2097152 /* Intersection */); - result.objectFlags = getPropagatingFlagsOfTypes( - types, - /*excludeKinds*/ - 98304 /* Nullable */ - ); + result.objectFlags = getPropagatingFlagsOfTypes(types, /*excludeKinds*/ + 98304 /* Nullable */); + result.types = types; result.aliasSymbol = aliasSymbol; result.aliasTypeArguments = aliasTypeArguments; return result; } function getIntersectionType(types, aliasSymbol, aliasTypeArguments, noSupertypeReduction) { - const typeMembershipMap = /* @__PURE__ */ new Map(); + const typeMembershipMap = /* @__PURE__ */new Map(); const includes = addTypesToIntersection(typeMembershipMap, 0, types); const typeSet = arrayFrom(typeMembershipMap.values()); if (includes & 131072 /* Never */) { @@ -59736,8 +55586,7 @@ ${lanes.join("\n")} 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 (!noSupertypeReduction) removeRedundantSupertypes(typeSet, includes); } if (includes & 262144 /* IncludesMissingType */) { typeSet[typeSet.indexOf(undefinedType)] = missingType; @@ -59754,11 +55603,11 @@ ${lanes.join("\n")} if (includes & 1048576 /* Union */) { if (intersectUnionsOfPrimitiveTypes(typeSet)) { result = getIntersectionType(typeSet, aliasSymbol, aliasTypeArguments); - } else if (every(typeSet, (t) => !!(t.flags & 1048576 /* Union */ && t.types[0].flags & 32768 /* Undefined */))) { + } else if (every(typeSet, t => !!(t.flags & 1048576 /* Union */ && t.types[0].flags & 32768 /* Undefined */))) { const containedUndefinedType = some(typeSet, containsMissingType) ? missingType : undefinedType; removeFromEach(typeSet, 32768 /* Undefined */); result = getUnionType([getIntersectionType(typeSet), containedUndefinedType], 1 /* Literal */, aliasSymbol, aliasTypeArguments); - } else if (every(typeSet, (t) => !!(t.flags & 1048576 /* Union */ && (t.types[0].flags & 65536 /* Null */ || t.types[1].flags & 65536 /* Null */)))) { + } else if (every(typeSet, t => !!(t.flags & 1048576 /* Union */ && (t.types[0].flags & 65536 /* Null */ || t.types[1].flags & 65536 /* Null */)))) { removeFromEach(typeSet, 65536 /* Null */); result = getUnionType([getIntersectionType(typeSet), nullType], 1 /* Literal */, aliasSymbol, aliasTypeArguments); } else { @@ -59766,7 +55615,7 @@ ${lanes.join("\n")} return errorType; } const constituents = getCrossProductIntersections(typeSet); - const origin = some(constituents, (t) => !!(t.flags & 2097152 /* Intersection */)) && getConstituentCountOfTypes(constituents) > getConstituentCountOfTypes(typeSet) ? createOriginUnionOrIntersectionType(2097152 /* Intersection */, typeSet) : void 0; + 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); } } else { @@ -59783,7 +55632,10 @@ ${lanes.join("\n")} var _a; const size = getCrossProductUnionSize(types); if (size >= 1e5) { - (_a = tracing) == null ? void 0 : _a.instant(tracing.Phase.CheckTypes, "checkCrossProductUnion_DepthLimit", { typeIds: types.map((t) => t.id), size }); + (_a = tracing) == null ? void 0 : _a.instant(tracing.Phase.CheckTypes, "checkCrossProductUnion_DepthLimit", { + typeIds: types.map(t => t.id), + size + }); error2(currentNode, Diagnostics.Expression_produces_a_union_type_that_is_too_complex_to_represent); return false; } @@ -59804,8 +55656,7 @@ ${lanes.join("\n")} } } const t = getIntersectionType(constituents); - if (!(t.flags & 131072 /* Never */)) - intersections.push(t); + if (!(t.flags & 131072 /* Never */)) intersections.push(t); } return intersections; } @@ -59841,6 +55692,7 @@ ${lanes.join("\n")} function getIndexTypeForGenericType(type, indexFlags) { return indexFlags & 1 /* StringsOnly */ ? type.resolvedStringIndexType || (type.resolvedStringIndexType = createIndexType(type, 1 /* StringsOnly */)) : type.resolvedIndexType || (type.resolvedIndexType = createIndexType(type, 0 /* None */)); } + function getIndexTypeForMappedType(type, indexFlags) { const typeParameter = getTypeParameterFromMappedType(type); const constraintType = getConstraintTypeFromMappedType(type); @@ -59862,7 +55714,7 @@ ${lanes.join("\n")} if (isGenericIndexType(constraintType)) { forEachType(constraintType, addMemberForKeyType); } - const result = indexFlags & 2 /* NoIndexSignatures */ ? filterType(getUnionType(keyTypes), (t) => !(t.flags & (1 /* Any */ | 4 /* String */))) : getUnionType(keyTypes); + const result = indexFlags & 2 /* NoIndexSignatures */ ? filterType(getUnionType(keyTypes), t => !(t.flags & (1 /* Any */ | 4 /* String */))) : getUnionType(keyTypes); if (result.flags & 1048576 /* Union */ && constraintType.flags & 1048576 /* Union */ && getTypeListId(result.types) === getTypeListId(constraintType.types)) { return constraintType; } @@ -59912,28 +55764,22 @@ ${lanes.join("\n")} return neverType; } function isKeyTypeIncluded(keyType, include) { - return !!(keyType.flags & include || keyType.flags & 2097152 /* Intersection */ && some(keyType.types, (t) => isKeyTypeIncluded(t, include))); + return !!(keyType.flags & include || keyType.flags & 2097152 /* Intersection */ && some(keyType.types, t => isKeyTypeIncluded(t, include))); } function getLiteralTypeFromProperties(type, include, includeOrigin) { const origin = includeOrigin && (getObjectFlags(type) & (3 /* ClassOrInterface */ | 4 /* Reference */) || type.aliasSymbol) ? createOriginIndexType(type) : void 0; - const propertyTypes = map(getPropertiesOfType(type), (prop) => getLiteralTypeFromProperty(prop, include)); - const indexKeyTypes = map(getIndexInfosOfType(type), (info) => info !== enumNumberIndexInfo && isKeyTypeIncluded(info.keyType, include) ? info.keyType === stringType && include & 8 /* Number */ ? stringOrNumberType : info.keyType : neverType); - return getUnionType( - concatenate(propertyTypes, indexKeyTypes), - 1 /* Literal */, - /*aliasSymbol*/ - void 0, - /*aliasTypeArguments*/ - void 0, - origin - ); + const propertyTypes = map(getPropertiesOfType(type), prop => getLiteralTypeFromProperty(prop, include)); + const indexKeyTypes = map(getIndexInfosOfType(type), info => info !== enumNumberIndexInfo && isKeyTypeIncluded(info.keyType, include) ? info.keyType === stringType && include & 8 /* Number */ ? stringOrNumberType : info.keyType : neverType); + return getUnionType(concatenate(propertyTypes, indexKeyTypes), 1 /* Literal */, /*aliasSymbol*/ + void 0, /*aliasTypeArguments*/ + void 0, origin); } function shouldDeferIndexType(type, indexFlags = 0 /* None */) { return !!(type.flags & 58982400 /* InstantiableNonPrimitive */ || isGenericTupleType(type) || isGenericMappedType(type) && !hasDistributiveNameType(type) || type.flags & 1048576 /* Union */ && !(indexFlags & 4 /* NoReducibleCheck */) && isGenericReducibleType(type) || type.flags & 2097152 /* Intersection */ && maybeTypeOfKind(type, 465829888 /* Instantiable */) && some(type.types, isEmptyAnonymousObjectType)); } function getIndexType(type, indexFlags = defaultIndexFlags) { type = getReducedType(type); - return shouldDeferIndexType(type, indexFlags) ? getIndexTypeForGenericType(type, indexFlags) : type.flags & 1048576 /* Union */ ? getIntersectionType(map(type.types, (t) => getIndexType(t, indexFlags))) : type.flags & 2097152 /* Intersection */ ? getUnionType(map(type.types, (t) => getIndexType(t, indexFlags))) : getObjectFlags(type) & 32 /* Mapped */ ? getIndexTypeForMappedType(type, indexFlags) : type === wildcardType ? wildcardType : type.flags & 2 /* Unknown */ ? neverType : type.flags & (1 /* Any */ | 131072 /* Never */) ? keyofConstraintType : getLiteralTypeFromProperties(type, (indexFlags & 2 /* NoIndexSignatures */ ? 128 /* StringLiteral */ : 402653316 /* StringLike */) | (indexFlags & 1 /* StringsOnly */ ? 0 : 296 /* NumberLike */ | 12288 /* ESSymbolLike */), indexFlags === defaultIndexFlags); + return shouldDeferIndexType(type, indexFlags) ? getIndexTypeForGenericType(type, indexFlags) : type.flags & 1048576 /* Union */ ? getIntersectionType(map(type.types, t => getIndexType(t, indexFlags))) : type.flags & 2097152 /* Intersection */ ? getUnionType(map(type.types, t => getIndexType(t, indexFlags))) : getObjectFlags(type) & 32 /* Mapped */ ? getIndexTypeForMappedType(type, indexFlags) : type === wildcardType ? wildcardType : type.flags & 2 /* Unknown */ ? neverType : type.flags & (1 /* Any */ | 131072 /* Never */) ? keyofConstraintType : getLiteralTypeFromProperties(type, (indexFlags & 2 /* NoIndexSignatures */ ? 128 /* StringLiteral */ : 402653316 /* StringLike */) | (indexFlags & 1 /* StringsOnly */ ? 0 : 296 /* NumberLike */ | 12288 /* ESSymbolLike */), indexFlags === defaultIndexFlags); } function getExtractStringType(type) { if (keyofStringsOnly) { @@ -59968,17 +55814,14 @@ ${lanes.join("\n")} function getTypeFromTemplateTypeNode(node) { const links = getNodeLinks(node); if (!links.resolvedType) { - links.resolvedType = getTemplateLiteralType( - [node.head.text, ...map(node.templateSpans, (span) => span.literal.text)], - map(node.templateSpans, (span) => getTypeFromTypeNode(span.type)) - ); + links.resolvedType = getTemplateLiteralType([node.head.text, ...map(node.templateSpans, span => span.literal.text)], map(node.templateSpans, span => getTypeFromTypeNode(span.type))); } return links.resolvedType; } function getTemplateLiteralType(texts, types) { - const unionIndex = findIndex(types, (t) => !!(t.flags & (131072 /* Never */ | 1048576 /* Union */))); + 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; + return checkCrossProductUnion(types) ? mapType(types[unionIndex], t => getTemplateLiteralType(texts, replaceElement(types, unionIndex, t))) : errorType; } if (contains(types, wildcardType)) { return wildcardType; @@ -59993,15 +55836,15 @@ ${lanes.join("\n")} return getStringLiteralType(text); } newTexts.push(text); - if (every(newTexts, (t) => t === "")) { - if (every(newTypes, (t) => !!(t.flags & 4 /* String */))) { + if (every(newTexts, t => t === "")) { + if (every(newTypes, t => !!(t.flags & 4 /* String */))) { return stringType; } if (newTypes.length === 1 && isPatternLiteralType(newTypes[0])) { return newTypes[0]; } } - const id = `${getTypeListId(newTypes)}|${map(newTexts, (t) => t.length).join(",")}|${newTexts.join("")}`; + const id = `${getTypeListId(newTypes)}|${map(newTexts, t => t.length).join(",")}|${newTexts.join("")}`; let type = templateLiteralTypes.get(id); if (!type) { templateLiteralTypes.set(id, type = createTemplateLiteralType(newTexts, newTypes)); @@ -60015,8 +55858,7 @@ ${lanes.join("\n")} 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); @@ -60039,13 +55881,11 @@ ${lanes.join("\n")} return type; } function getStringMappingType(symbol, type) { - return type.flags & (1048576 /* Union */ | 131072 /* Never */) ? mapType(type, (t) => getStringMappingType(symbol, t)) : type.flags & 128 /* StringLiteral */ ? getStringLiteralType(applyStringMapping(symbol, type.value)) : type.flags & 134217728 /* TemplateLiteral */ ? getTemplateLiteralType(...applyTemplateStringMapping(symbol, type.texts, type.types)) : ( - // Mapping> === Mapping - type.flags & 268435456 /* StringMapping */ && symbol === type.symbol ? type : type.flags & (1 /* Any */ | 4 /* String */ | 268435456 /* StringMapping */) || isGenericIndexType(type) ? getStringMappingTypeForGenericType(symbol, type) : ( - // This handles Mapping<`${number}`> and Mapping<`${bigint}`> - isPatternLiteralPlaceholderType(type) ? getStringMappingTypeForGenericType(symbol, getTemplateLiteralType(["", ""], [type])) : type - ) - ); + return type.flags & (1048576 /* Union */ | 131072 /* Never */) ? mapType(type, t => getStringMappingType(symbol, t)) : type.flags & 128 /* StringLiteral */ ? getStringLiteralType(applyStringMapping(symbol, type.value)) : type.flags & 134217728 /* TemplateLiteral */ ? getTemplateLiteralType(...applyTemplateStringMapping(symbol, type.texts, type.types)) : + // Mapping> === Mapping + type.flags & 268435456 /* StringMapping */ && symbol === type.symbol ? type : type.flags & (1 /* Any */ | 4 /* String */ | 268435456 /* StringMapping */) || isGenericIndexType(type) ? getStringMappingTypeForGenericType(symbol, type) : + // This handles Mapping<`${number}`> and Mapping<`${bigint}`> + isPatternLiteralPlaceholderType(type) ? getStringMappingTypeForGenericType(symbol, getTemplateLiteralType(["", ""], [type])) : type; } function applyStringMapping(symbol, str) { switch (intrinsicTypeKinds.get(symbol.escapedName)) { @@ -60063,9 +55903,9 @@ ${lanes.join("\n")} function applyTemplateStringMapping(symbol, texts, types) { switch (intrinsicTypeKinds.get(symbol.escapedName)) { case 0 /* Uppercase */: - return [texts.map((t) => t.toUpperCase()), types.map((t) => getStringMappingType(symbol, t))]; + return [texts.map(t => t.toUpperCase()), types.map(t => getStringMappingType(symbol, t))]; case 1 /* Lowercase */: - return [texts.map((t) => t.toLowerCase()), types.map((t) => getStringMappingType(symbol, t))]; + return [texts.map(t => t.toLowerCase()), types.map(t => getStringMappingType(symbol, t))]; case 2 /* Capitalize */: return [texts[0] === "" ? texts : [texts[0].charAt(0).toUpperCase() + texts[0].slice(1), ...texts.slice(1)], texts[0] === "" ? [getStringMappingType(symbol, types[0]), ...types.slice(1)] : types]; case 3 /* Uncapitalize */: @@ -60115,18 +55955,17 @@ ${lanes.join("\n")} return false; } function getPropertyNameFromIndex(indexType, accessNode) { - return isTypeUsableAsPropertyName(indexType) ? getPropertyNameFromType(indexType) : accessNode && isPropertyName(accessNode) ? ( - // late bound names are handled in the first branch, so here we only need to handle normal names - getPropertyNameForPropertyNameNode(accessNode) - ) : void 0; + return isTypeUsableAsPropertyName(indexType) ? getPropertyNameFromType(indexType) : accessNode && isPropertyName(accessNode) ? + // late bound names are handled in the first branch, so here we only need to handle normal names + getPropertyNameForPropertyNameNode(accessNode) : void 0; } function isUncalledFunctionReference(node, symbol) { if (symbol.flags & (16 /* Function */ | 8192 /* Method */)) { - const parent2 = findAncestor(node.parent, (n) => !isAccessExpression(n)) || node.parent; + const parent2 = findAncestor(node.parent, n => !isAccessExpression(n)) || node.parent; if (isCallLikeExpression(parent2)) { return isCallOrNewExpression(parent2) && isIdentifier(node) && hasMatchingArgument(parent2, node); } - return every(symbol.declarations, (d) => !isFunctionLike(d) || isDeprecatedDeclaration2(d)); + return every(symbol.declarations, d => !isFunctionLike(d) || isDeprecatedDeclaration2(d)); } return true; } @@ -60140,7 +55979,8 @@ ${lanes.join("\n")} const prop = getPropertyOfType(objectType, propName); if (prop) { if (accessFlags & 64 /* ReportDeprecated */ && accessNode && prop.declarations && isDeprecatedSymbol(prop) && isUncalledFunctionReference(accessNode, prop)) { - const deprecatedNode = (accessExpression == null ? void 0 : accessExpression.argumentExpression) ?? (isIndexedAccessTypeNode(accessNode) ? accessNode.indexType : accessNode); + var _ref25; + const deprecatedNode = (_ref25 = accessExpression == null ? void 0 : accessExpression.argumentExpression) !== null && _ref25 !== void 0 ? _ref25 : isIndexedAccessTypeNode(accessNode) ? accessNode.indexType : accessNode; addDeprecatedSuggestion(deprecatedNode, prop.declarations, propName); } if (accessExpression) { @@ -60161,7 +56001,7 @@ ${lanes.join("\n")} } if (everyType(objectType, isTupleType) && isNumericLiteralName(propName)) { const index = +propName; - if (accessNode && everyType(objectType, (t) => !t.target.hasRestElement) && !(accessFlags & 16 /* NoTupleBoundsCheck */)) { + if (accessNode && everyType(objectType, t => !t.target.hasRestElement) && !(accessFlags & 16 /* NoTupleBoundsCheck */)) { const indexNode = getIndexNodeForAccessExpression(accessNode); if (isTupleType(objectType)) { if (index < 0) { @@ -60201,7 +56041,7 @@ ${lanes.join("\n")} return accessFlags & 1 /* IncludeUndefined */ ? getUnionType([indexInfo.type, missingType]) : indexInfo.type; } errorIfWritingToReadonlyIndex(indexInfo); - if (accessFlags & 1 /* IncludeUndefined */ && !(objectType.symbol && objectType.symbol.flags & (256 /* RegularEnum */ | 128 /* ConstEnum */) && (indexType.symbol && indexType.flags & 1024 /* EnumLiteral */ && getParentOfSymbol(indexType.symbol) === objectType.symbol))) { + if (accessFlags & 1 /* IncludeUndefined */ && !(objectType.symbol && objectType.symbol.flags & (256 /* RegularEnum */ | 128 /* ConstEnum */) && indexType.symbol && indexType.flags & 1024 /* EnumLiteral */ && getParentOfSymbol(indexType.symbol) === objectType.symbol)) { return getUnionType([indexInfo.type, missingType]); } return indexInfo.type; @@ -60218,7 +56058,7 @@ ${lanes.join("\n")} diagnostics.add(createDiagnosticForNode(accessExpression, Diagnostics.Property_0_does_not_exist_on_type_1, indexType.value, typeToString(objectType))); return undefinedType; } else if (indexType.flags & (8 /* Number */ | 4 /* String */)) { - const types = map(objectType.properties, (property) => { + const types = map(objectType.properties, property => { return getTypeOfSymbol(property); }); return getUnionType(append(types, undefinedType)); @@ -60245,53 +56085,23 @@ ${lanes.join("\n")} } else { let errorInfo; if (indexType.flags & 1024 /* EnumLiteral */) { - errorInfo = chainDiagnosticMessages( - /*details*/ - void 0, - Diagnostics.Property_0_does_not_exist_on_type_1, - "[" + typeToString(indexType) + "]", - typeToString(objectType) - ); + errorInfo = chainDiagnosticMessages( /*details*/ + void 0, Diagnostics.Property_0_does_not_exist_on_type_1, "[" + typeToString(indexType) + "]", typeToString(objectType)); } else if (indexType.flags & 8192 /* UniqueESSymbol */) { const symbolName2 = getFullyQualifiedName(indexType.symbol, accessExpression); - errorInfo = chainDiagnosticMessages( - /*details*/ - void 0, - Diagnostics.Property_0_does_not_exist_on_type_1, - "[" + symbolName2 + "]", - typeToString(objectType) - ); + errorInfo = chainDiagnosticMessages( /*details*/ + void 0, Diagnostics.Property_0_does_not_exist_on_type_1, "[" + symbolName2 + "]", typeToString(objectType)); } else if (indexType.flags & 128 /* StringLiteral */) { - errorInfo = chainDiagnosticMessages( - /*details*/ - void 0, - Diagnostics.Property_0_does_not_exist_on_type_1, - indexType.value, - typeToString(objectType) - ); + errorInfo = chainDiagnosticMessages( /*details*/ + void 0, Diagnostics.Property_0_does_not_exist_on_type_1, indexType.value, typeToString(objectType)); } else if (indexType.flags & 256 /* NumberLiteral */) { - errorInfo = chainDiagnosticMessages( - /*details*/ - void 0, - Diagnostics.Property_0_does_not_exist_on_type_1, - indexType.value, - typeToString(objectType) - ); + errorInfo = chainDiagnosticMessages( /*details*/ + void 0, Diagnostics.Property_0_does_not_exist_on_type_1, indexType.value, typeToString(objectType)); } else if (indexType.flags & (8 /* Number */ | 4 /* String */)) { - errorInfo = chainDiagnosticMessages( - /*details*/ - void 0, - Diagnostics.No_index_signature_with_a_parameter_of_type_0_was_found_on_type_1, - typeToString(indexType), - typeToString(objectType) - ); + errorInfo = chainDiagnosticMessages( /*details*/ + void 0, Diagnostics.No_index_signature_with_a_parameter_of_type_0_was_found_on_type_1, typeToString(indexType), typeToString(objectType)); } - errorInfo = chainDiagnosticMessages( - errorInfo, - Diagnostics.Element_implicitly_has_an_any_type_because_expression_of_type_0_can_t_be_used_to_index_type_1, - typeToString(fullIndexType), - typeToString(objectType) - ); + errorInfo = chainDiagnosticMessages(errorInfo, Diagnostics.Element_implicitly_has_an_any_type_because_expression_of_type_0_can_t_be_used_to_index_type_1, typeToString(fullIndexType), typeToString(objectType)); diagnostics.add(createDiagnosticForNodeFromMessageChain(getSourceFileOfNode(accessExpression), accessExpression, errorInfo)); } } @@ -60349,9 +56159,11 @@ ${lanes.join("\n")} function isGenericObjectType(type) { return !!(getGenericObjectFlags(type) & 4194304 /* IsGenericObjectType */); } + function isGenericIndexType(type) { return !!(getGenericObjectFlags(type) & 8388608 /* IsGenericIndexType */); } + function getGenericObjectFlags(type) { if (type.flags & 3145728 /* UnionOrIntersection */) { if (!(type.objectFlags & 2097152 /* IsGenericTypeComputed */)) { @@ -60359,12 +56171,14 @@ ${lanes.join("\n")} } return type.objectFlags & 12582912 /* IsGenericType */; } + if (type.flags & 33554432 /* Substitution */) { if (!(type.objectFlags & 2097152 /* IsGenericTypeComputed */)) { type.objectFlags |= 2097152 /* IsGenericTypeComputed */ | getGenericObjectFlags(type.baseType) | getGenericObjectFlags(type.constraint); } return type.objectFlags & 12582912 /* IsGenericType */; } + return (type.flags & 58982400 /* InstantiableNonPrimitive */ || isGenericMappedType(type) || isGenericTupleType(type) ? 4194304 /* IsGenericObjectType */ : 0) | (type.flags & (58982400 /* InstantiableNonPrimitive */ | 4194304 /* Index */ | 134217728 /* TemplateLiteral */ | 268435456 /* StringMapping */) && !isPatternLiteralType(type) ? 8388608 /* IsGenericIndexType */ : 0); } function getSimplifiedType(type, writing) { @@ -60372,13 +56186,13 @@ ${lanes.join("\n")} } function distributeIndexOverObjectType(objectType, indexType, writing) { if (objectType.flags & 1048576 /* Union */ || objectType.flags & 2097152 /* Intersection */ && !shouldDeferIndexType(objectType)) { - const types = map(objectType.types, (t) => getSimplifiedType(getIndexedAccessType(t, indexType), writing)); + const types = map(objectType.types, t => getSimplifiedType(getIndexedAccessType(t, indexType), writing)); return objectType.flags & 2097152 /* Intersection */ || writing ? getIntersectionType(types) : getUnionType(types); } } function distributeObjectOverIndexType(objectType, indexType, writing) { if (indexType.flags & 1048576 /* Union */) { - const types = map(indexType.types, (t) => getSimplifiedType(getIndexedAccessType(objectType, t), writing)); + const types = map(indexType.types, t => getSimplifiedType(getIndexedAccessType(objectType, t), writing)); return writing ? getIntersectionType(types) : getUnionType(types); } } @@ -60401,20 +56215,15 @@ ${lanes.join("\n")} } } if (isGenericTupleType(objectType) && indexType.flags & 296 /* NumberLike */) { - const elementType = getElementTypeOfSliceOfTupleType( - objectType, - indexType.flags & 8 /* Number */ ? 0 : objectType.target.fixedLength, - /*endSkipCount*/ - 0, - writing - ); + const elementType = getElementTypeOfSliceOfTupleType(objectType, indexType.flags & 8 /* Number */ ? 0 : objectType.target.fixedLength, /*endSkipCount*/ + 0, writing); if (elementType) { return type[cache] = elementType; } } if (isGenericMappedType(objectType)) { if (!getNameTypeFromMappedType(objectType) || isFilteringMappedType(objectType)) { - return type[cache] = mapType(substituteIndexedMappedType(objectType, type.indexType), (t) => getSimplifiedType(t, writing)); + return type[cache] = mapType(substituteIndexedMappedType(objectType, type.indexType), t => getSimplifiedType(t, writing)); } } return type[cache] = type; @@ -60442,6 +56251,7 @@ ${lanes.join("\n")} function isIntersectionEmpty(type1, type2) { return !!(getUnionType([intersectTypes(type1, type2), neverType]).flags & 131072 /* Never */); } + function substituteIndexedMappedType(objectType, index) { const mapper = createTypeMapper([getTypeParameterFromMappedType(objectType)], [index]); const templateMapper = combineTypeMappers(objectType.mapper, mapper); @@ -60451,7 +56261,7 @@ ${lanes.join("\n")} return getIndexedAccessTypeOrUndefined(objectType, indexType, accessFlags, accessNode, aliasSymbol, aliasTypeArguments) || (accessNode ? errorType : unknownType); } function indexTypeLessThan(indexType, limit) { - return everyType(indexType, (t) => { + return everyType(indexType, t => { if (t.flags & 384 /* StringOrNumberLiteral */) { const propName = getPropertyNameFromType(t); if (isNumericLiteralName(propName)) { @@ -60470,8 +56280,7 @@ ${lanes.join("\n")} 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; @@ -60505,6 +56314,7 @@ ${lanes.join("\n")} } return getPropertyTypeForIndexType(objectType, apparentObjectType, indexType, indexType, accessNode, accessFlags | 8 /* CacheSymbol */ | 64 /* ReportDeprecated */); } + function getTypeFromIndexedAccessTypeNode(node) { const links = getNodeLinks(node); if (!links.resolvedType) { @@ -60541,7 +56351,7 @@ ${lanes.join("\n")} return constraint && (isGenericObjectType(constraint) || isGenericIndexType(constraint)) ? cloneTypeParameter(p) : p; } function isSimpleTupleType(node) { - return isTupleTypeNode(node) && length(node.elements) > 0 && !some(node.elements, (e) => isOptionalTypeNode(e) || isRestTypeNode(e) || isNamedTupleMember(e) && !!(e.questionToken || e.dotDotDotToken)); + return isTupleTypeNode(node) && length(node.elements) > 0 && !some(node.elements, e => isOptionalTypeNode(e) || isRestTypeNode(e) || isNamedTupleMember(e) && !!(e.questionToken || e.dotDotDotToken)); } function isDeferredType(type, checkTuples) { return isGenericType(type) || checkTuples && isTupleType(type) && some(getElementTypes(type), isGenericType); @@ -60569,12 +56379,9 @@ ${lanes.join("\n")} if (root.inferTypeParameters) { const freshParams = sameMap(root.inferTypeParameters, maybeCloneTypeParameter); const freshMapper = freshParams !== root.inferTypeParameters ? createTypeMapper(root.inferTypeParameters, freshParams) : void 0; - const context = createInferenceContext( - freshParams, - /*signature*/ - void 0, - 0 /* None */ - ); + const context = createInferenceContext(freshParams, /*signature*/ + void 0, 0 /* None */); + if (freshMapper) { const freshCombinedMapper = combineTypeMappers(mapper, freshMapper); for (let i = 0; i < freshParams.length; i++) { @@ -60586,6 +56393,7 @@ ${lanes.join("\n")} if (!checkTypeDeferred) { inferTypes(context.inferences, checkType, instantiateType(extendsType, freshMapper), 512 /* NoConstraints */ | 1024 /* AlwaysStrict */); } + const innerMapper = combineTypeMappers(freshMapper, context.mapper); combinedMapper = mapper ? combineTypeMappers(innerMapper, mapper) : innerMapper; } @@ -60635,7 +56443,7 @@ ${lanes.join("\n")} const newRoot = newType.root; if (newRoot.outerTypeParameters) { const typeParamMapper = combineTypeMappers(newType.mapper, newMapper); - const typeArguments = map(newRoot.outerTypeParameters, (t) => getMappedType(t, typeParamMapper)); + const typeArguments = map(newRoot.outerTypeParameters, t => getMappedType(t, typeParamMapper)); const newRootMapper = createTypeMapper(newRoot.outerTypeParameters, typeArguments); const newCheckType = newRoot.isDistributive ? getMappedType(newRoot.checkType, newRootMapper) : void 0; if (!newCheckType || newCheckType === newRoot.checkType || !(newCheckType.flags & (1048576 /* Union */ | 131072 /* Never */))) { @@ -60665,7 +56473,7 @@ ${lanes.join("\n")} function getInferTypeParameters(node) { let result; if (node.locals) { - node.locals.forEach((symbol) => { + node.locals.forEach(symbol => { if (symbol.flags & 262144 /* TypeParameter */) { result = append(result, getDeclaredTypeOfSymbol(symbol)); } @@ -60682,12 +56490,9 @@ ${lanes.join("\n")} const checkType = getTypeFromTypeNode(node.checkType); const aliasSymbol = getAliasSymbolForTypeNode(node); const aliasTypeArguments = getTypeArgumentsForAliasSymbol(aliasSymbol); - const allOuterTypeParameters = getOuterTypeParameters( - node, - /*includeThisTypes*/ - true - ); - const outerTypeParameters = aliasTypeArguments ? allOuterTypeParameters : filter(allOuterTypeParameters, (tp) => isTypeParameterPossiblyReferenced(tp, node)); + const allOuterTypeParameters = getOuterTypeParameters(node, /*includeThisTypes*/ + true); + const outerTypeParameters = aliasTypeArguments ? allOuterTypeParameters : filter(allOuterTypeParameters, tp => isTypeParameterPossiblyReferenced(tp, node)); const root = { node, checkType, @@ -60699,13 +56504,10 @@ ${lanes.join("\n")} aliasSymbol, aliasTypeArguments }; - links.resolvedType = getConditionalType( - root, - /*mapper*/ - void 0 - ); + links.resolvedType = getConditionalType(root, /*mapper*/ + void 0); if (outerTypeParameters) { - root.instantiations = /* @__PURE__ */ new Map(); + root.instantiations = /* @__PURE__ */new Map(); root.instantiations.set(getTypeListId(outerTypeParameters), links.resolvedType); } } @@ -60741,11 +56543,8 @@ ${lanes.join("\n")} return links.resolvedType = errorType; } const isExportEquals = !!((_a = innerModuleSymbol.exports) == null ? void 0 : _a.get("export=" /* ExportEquals */)); - const moduleSymbol = resolveExternalModuleSymbol( - innerModuleSymbol, - /*dontResolveAlias*/ - false - ); + const moduleSymbol = resolveExternalModuleSymbol(innerModuleSymbol, /*dontResolveAlias*/ + false); if (!nodeIsMissing(node.qualifier)) { const nameStack = getIdentifierChain(node.qualifier); let currentNamespace = moduleSymbol; @@ -60753,16 +56552,11 @@ ${lanes.join("\n")} while (current = nameStack.shift()) { const meaning = nameStack.length ? 1920 /* Namespace */ : targetMeaning; const mergedResolvedSymbol = getMergedSymbol(resolveSymbol(currentNamespace)); - const symbolFromVariable = node.isTypeOf || isInJSFile(node) && isExportEquals ? getPropertyOfType( - getTypeOfSymbol(mergedResolvedSymbol), - current.escapedText, - /*skipObjectFunctionPropertyAugment*/ - false, - /*includeTypeOnlyMembers*/ - true - ) : void 0; + const symbolFromVariable = node.isTypeOf || isInJSFile(node) && isExportEquals ? getPropertyOfType(getTypeOfSymbol(mergedResolvedSymbol), current.escapedText, /*skipObjectFunctionPropertyAugment*/ + false, /*includeTypeOnlyMembers*/ + true) : void 0; const symbolFromModule = node.isTypeOf ? void 0 : getSymbol2(getExportsOfSymbol(mergedResolvedSymbol), current.escapedText, meaning); - const next = symbolFromModule ?? symbolFromVariable; + const next = symbolFromModule !== null && symbolFromModule !== void 0 ? symbolFromModule : symbolFromVariable; if (!next) { error2(current, Diagnostics.Namespace_0_has_no_exported_member_1, getFullyQualifiedName(currentNamespace), declarationNameToString(current)); return links.resolvedType = errorType; @@ -60828,6 +56622,7 @@ ${lanes.join("\n")} function isEmptyObjectTypeOrSpreadsIntoEmptyObject(type) { return isEmptyObjectType(type) || !!(type.flags & (65536 /* Null */ | 32768 /* Undefined */ | 528 /* BooleanLike */ | 296 /* NumberLike */ | 2112 /* BigIntLike */ | 402653316 /* StringLike */ | 1056 /* EnumLike */ | 67108864 /* NonPrimitive */ | 4194304 /* Index */)); } + function tryMergeUnionOfObjectTypeAndEmptyObject(type, readonly) { if (!(type.flags & 1048576 /* Union */)) { return type; @@ -60835,11 +56630,11 @@ ${lanes.join("\n")} if (every(type.types, isEmptyObjectTypeOrSpreadsIntoEmptyObject)) { return find(type.types, isEmptyObjectType) || emptyObjectType; } - const firstType = find(type.types, (t) => !isEmptyObjectTypeOrSpreadsIntoEmptyObject(t)); + const firstType = find(type.types, t => !isEmptyObjectTypeOrSpreadsIntoEmptyObject(t)); if (!firstType) { return type; } - const secondType = find(type.types, (t) => t !== firstType && !isEmptyObjectTypeOrSpreadsIntoEmptyObject(t)); + const secondType = find(type.types, t => t !== firstType && !isEmptyObjectTypeOrSpreadsIntoEmptyObject(t)); if (secondType) { return type; } @@ -60847,16 +56642,12 @@ ${lanes.join("\n")} function getAnonymousPartialType(type2) { const members = createSymbolTable(); for (const prop of getPropertiesOfType(type2)) { - if (getDeclarationModifierFlagsFromSymbol(prop) & (2 /* Private */ | 4 /* Protected */)) { - } else if (isSpreadableProperty(prop)) { + if (getDeclarationModifierFlagsFromSymbol(prop) & (2 /* Private */ | 4 /* Protected */)) {} else if (isSpreadableProperty(prop)) { const isSetonlyAccessor = prop.flags & 65536 /* SetAccessor */ && !(prop.flags & 32768 /* GetAccessor */); const flags = 4 /* Property */ | 16777216 /* Optional */; const result = createSymbol(flags, prop.escapedName, getIsLateCheckFlag(prop) | (readonly ? 8 /* Readonly */ : 0)); - result.links.type = isSetonlyAccessor ? undefinedType : addOptionality( - getTypeOfSymbol(prop), - /*isProperty*/ - true - ); + result.links.type = isSetonlyAccessor ? undefinedType : addOptionality(getTypeOfSymbol(prop), /*isProperty*/ + true); result.declarations = prop.declarations; result.links.nameType = getSymbolLinks(prop).nameType; result.links.syntheticOrigin = prop; @@ -60883,11 +56674,11 @@ ${lanes.join("\n")} } left = tryMergeUnionOfObjectTypeAndEmptyObject(left, readonly); if (left.flags & 1048576 /* Union */) { - return checkCrossProductUnion([left, right]) ? mapType(left, (t) => getSpreadType(t, right, symbol, objectFlags, readonly)) : errorType; + return checkCrossProductUnion([left, right]) ? mapType(left, t => getSpreadType(t, right, symbol, objectFlags, readonly)) : errorType; } right = tryMergeUnionOfObjectTypeAndEmptyObject(right, readonly); if (right.flags & 1048576 /* Union */) { - return checkCrossProductUnion([left, right]) ? mapType(right, (t) => getSpreadType(left, t, symbol, objectFlags, readonly)) : errorType; + return checkCrossProductUnion([left, right]) ? mapType(right, t => getSpreadType(left, t, symbol, objectFlags, readonly)) : errorType; } if (right.flags & (528 /* BooleanLike */ | 296 /* NumberLike */ | 2112 /* BigIntLike */ | 402653316 /* StringLike */ | 1056 /* EnumLike */ | 67108864 /* NonPrimitive */ | 4194304 /* Index */)) { return left; @@ -60906,7 +56697,7 @@ ${lanes.join("\n")} return getIntersectionType([left, right]); } const members = createSymbolTable(); - const skippedPrivateMembers = /* @__PURE__ */ new Set(); + const skippedPrivateMembers = /* @__PURE__ */new Set(); const indexInfos = left === emptyObjectType ? getIndexInfosOfType(right) : getUnionIndexInfos([left, right]); for (const rightProp of getPropertiesOfType(right)) { if (getDeclarationModifierFlagsFromSymbol(rightProp) & (2 /* Private */ | 4 /* Protected */)) { @@ -60940,13 +56731,13 @@ ${lanes.join("\n")} members.set(leftProp.escapedName, getSpreadSymbol(leftProp, readonly)); } } - const spread = createAnonymousType(symbol, members, emptyArray, emptyArray, sameMap(indexInfos, (info) => getIndexInfoWithReadonly(info, readonly))); + const spread = createAnonymousType(symbol, members, emptyArray, emptyArray, sameMap(indexInfos, info => getIndexInfoWithReadonly(info, readonly))); spread.objectFlags |= 128 /* ObjectLiteral */ | 131072 /* ContainsObjectOrArrayLiteral */ | 2097152 /* ContainsSpread */ | objectFlags; return spread; } function isSpreadableProperty(prop) { var _a; - return !some(prop.declarations, isPrivateIdentifierClassElementDeclaration) && (!(prop.flags & (8192 /* Method */ | 32768 /* GetAccessor */ | 65536 /* SetAccessor */)) || !((_a = prop.declarations) == null ? void 0 : _a.some((decl) => isClassLike(decl.parent)))); + return !some(prop.declarations, isPrivateIdentifierClassElementDeclaration) && (!(prop.flags & (8192 /* Method */ | 32768 /* GetAccessor */ | 65536 /* SetAccessor */)) || !((_a = prop.declarations) == null ? void 0 : _a.some(decl => isClassLike(decl.parent)))); } function getSpreadSymbol(prop, readonly) { const isSetonlyAccessor = prop.flags & 65536 /* SetAccessor */ && !(prop.flags & 32768 /* GetAccessor */); @@ -61032,13 +56823,9 @@ ${lanes.join("\n")} return esSymbolType; } function getThisType(node) { - const container = getThisContainer( - node, - /*includeArrowFunctions*/ - false, - /*includeClassComputedPropertyName*/ - false - ); + const container = getThisContainer(node, /*includeArrowFunctions*/ + false, /*includeClassComputedPropertyName*/ + false); const parent2 = container && container.parent; if (parent2 && (isClassLike(parent2) || parent2.kind === 264 /* InterfaceDeclaration */)) { if (!isStatic(container) && (!isConstructorDeclaration(container) || isNodeDescendantOf(node, container.body))) { @@ -61087,12 +56874,8 @@ ${lanes.join("\n")} } function getTypeFromNamedTupleTypeNode(node) { const links = getNodeLinks(node); - return links.resolvedType || (links.resolvedType = node.dotDotDotToken ? getTypeFromRestTypeNode(node) : addOptionality( - getTypeFromTypeNode(node.type), - /*isProperty*/ - true, - !!node.questionToken - )); + return links.resolvedType || (links.resolvedType = node.dotDotDotToken ? getTypeFromRestTypeNode(node) : addOptionality(getTypeFromTypeNode(node.type), /*isProperty*/ + true, !!node.questionToken)); } function getTypeFromTypeNode(node) { return getConditionalFlowTypeOfType(getTypeFromTypeNodeWorker(node), node); @@ -61226,26 +57009,28 @@ ${lanes.join("\n")} switch (mapper.kind) { case 0 /* Simple */: return type === mapper.source ? mapper.target : type; - case 1 /* Array */: { - const sources = mapper.sources; - const targets = mapper.targets; - for (let i = 0; i < sources.length; i++) { - if (type === sources[i]) { - return targets ? targets[i] : anyType; + case 1 /* Array */: + { + const sources = mapper.sources; + const targets = mapper.targets; + for (let i = 0; i < sources.length; i++) { + if (type === sources[i]) { + return targets ? targets[i] : anyType; + } } + return type; } - return type; - } - case 2 /* Deferred */: { - const sources = mapper.sources; - const targets = mapper.targets; - for (let i = 0; i < sources.length; i++) { - if (type === sources[i]) { - return targets[i](); + case 2 /* Deferred */: + { + const sources = mapper.sources; + const targets = mapper.targets; + for (let i = 0; i < sources.length; i++) { + if (type === sources[i]) { + return targets[i](); + } } + return type; } - return type; - } case 3 /* Function */: return mapper.func(type); case 4 /* Composite */: @@ -61255,30 +57040,47 @@ ${lanes.join("\n")} } } function makeUnaryTypeMapper(source, target) { - return Debug.attachDebugPrototypeIfDebug({ kind: 0 /* Simple */, source, target }); + return Debug.attachDebugPrototypeIfDebug({ + kind: 0 /* Simple */, + source, + target + }); } function makeArrayTypeMapper(sources, targets) { - return Debug.attachDebugPrototypeIfDebug({ kind: 1 /* Array */, sources, targets }); + return Debug.attachDebugPrototypeIfDebug({ + kind: 1 /* Array */, + sources, + targets + }); } function makeFunctionTypeMapper(func, debugInfo) { - return Debug.attachDebugPrototypeIfDebug({ kind: 3 /* Function */, func, debugInfo: Debug.isDebugging ? debugInfo : void 0 }); + return Debug.attachDebugPrototypeIfDebug({ + kind: 3 /* Function */, + func, + debugInfo: Debug.isDebugging ? debugInfo : void 0 + }); } function makeDeferredTypeMapper(sources, targets) { - return Debug.attachDebugPrototypeIfDebug({ kind: 2 /* Deferred */, sources, targets }); + return Debug.attachDebugPrototypeIfDebug({ + kind: 2 /* Deferred */, + sources, + targets + }); } function makeCompositeTypeMapper(kind, mapper1, mapper2) { - return Debug.attachDebugPrototypeIfDebug({ kind, mapper1, mapper2 }); + return Debug.attachDebugPrototypeIfDebug({ + kind, + mapper1, + mapper2 + }); } function createTypeEraser(sources) { - return createTypeMapper( - sources, - /*targets*/ - void 0 - ); + return createTypeMapper(sources, /*targets*/ + void 0); } function createBackreferenceMapper(context, index) { const forwardInferences = context.inferences.slice(index); - return createTypeMapper(map(forwardInferences, (i) => i.typeParameter), map(forwardInferences, () => unknownType)); + return createTypeMapper(map(forwardInferences, i => i.typeParameter), map(forwardInferences, () => unknownType)); } function combineTypeMappers(mapper1, mapper2) { return mapper1 ? makeCompositeTypeMapper(4 /* Composite */, mapper1, mapper2) : mapper2; @@ -61312,18 +57114,10 @@ ${lanes.join("\n")} tp.mapper = mapper; } } - const result = createSignature( - signature.declaration, - freshTypeParameters, - signature.thisParameter && instantiateSymbol(signature.thisParameter, mapper), - instantiateList(signature.parameters, mapper, instantiateSymbol), - /*resolvedReturnType*/ - void 0, - /*resolvedTypePredicate*/ - void 0, - signature.minArgumentCount, - signature.flags & 167 /* PropagatingFlags */ - ); + const result = createSignature(signature.declaration, freshTypeParameters, signature.thisParameter && instantiateSymbol(signature.thisParameter, mapper), instantiateList(signature.parameters, mapper, instantiateSymbol), /*resolvedReturnType*/ + void 0, /*resolvedTypePredicate*/ + void 0, signature.minArgumentCount, signature.flags & 167 /* PropagatingFlags */); + result.target = signature; result.mapper = mapper; return result; @@ -61361,28 +57155,25 @@ ${lanes.join("\n")} const target = type.objectFlags & 4 /* Reference */ ? links.resolvedType : type.objectFlags & 64 /* Instantiated */ ? type.target : type; let typeParameters = links.outerTypeParameters; if (!typeParameters) { - let outerTypeParameters = getOuterTypeParameters( - declaration, - /*includeThisTypes*/ - true - ); + let outerTypeParameters = getOuterTypeParameters(declaration, /*includeThisTypes*/ + true); if (isJSConstructor(declaration)) { const templateTagParameters = getTypeParametersFromDeclaration(declaration); outerTypeParameters = addRange(outerTypeParameters, templateTagParameters); } typeParameters = outerTypeParameters || emptyArray; const allDeclarations = type.objectFlags & (4 /* Reference */ | 8388608 /* InstantiationExpressionType */) ? [declaration] : type.symbol.declarations; - typeParameters = (target.objectFlags & (4 /* Reference */ | 8388608 /* InstantiationExpressionType */) || target.symbol.flags & 8192 /* Method */ || target.symbol.flags & 2048 /* TypeLiteral */) && !target.aliasTypeArguments ? filter(typeParameters, (tp) => some(allDeclarations, (d) => isTypeParameterPossiblyReferenced(tp, d))) : typeParameters; + typeParameters = (target.objectFlags & (4 /* Reference */ | 8388608 /* InstantiationExpressionType */) || target.symbol.flags & 8192 /* Method */ || target.symbol.flags & 2048 /* TypeLiteral */) && !target.aliasTypeArguments ? filter(typeParameters, tp => some(allDeclarations, d => isTypeParameterPossiblyReferenced(tp, d))) : typeParameters; links.outerTypeParameters = typeParameters; } if (typeParameters.length) { const combinedMapper = combineTypeMappers(type.mapper, mapper); - const typeArguments = map(typeParameters, (t) => getMappedType(t, combinedMapper)); + const typeArguments = map(typeParameters, t => getMappedType(t, combinedMapper)); const newAliasSymbol = aliasSymbol || type.aliasSymbol; const newAliasTypeArguments = aliasSymbol ? aliasTypeArguments : instantiateTypes(type.aliasTypeArguments, mapper); const id = getTypeListId(typeArguments) + getAliasId(newAliasSymbol, newAliasTypeArguments); if (!target.instantiations) { - target.instantiations = /* @__PURE__ */ new Map(); + target.instantiations = /* @__PURE__ */new Map(); target.instantiations.set(getTypeListId(typeParameters) + getAliasId(target.aliasSymbol, target.aliasTypeArguments), target); } let result = target.instantiations.get(id); @@ -61432,15 +57223,13 @@ ${lanes.join("\n")} if (!isThisIdentifier(firstIdentifier)) { const firstIdentifierSymbol = getResolvedSymbol(firstIdentifier); const tpDeclaration = tp.symbol.declarations[0]; - const tpScope = tpDeclaration.kind === 168 /* TypeParameter */ ? tpDeclaration.parent : ( - // Type parameter is a regular type parameter, e.g. foo - tp.isThisType ? tpDeclaration : ( - // Type parameter is the this type, and its declaration is the class declaration. - void 0 - ) - ); + const tpScope = tpDeclaration.kind === 168 /* TypeParameter */ ? tpDeclaration.parent : + // Type parameter is a regular type parameter, e.g. foo + tp.isThisType ? tpDeclaration : + // Type parameter is the this type, and its declaration is the class declaration. + void 0; if (firstIdentifierSymbol.declarations && tpScope) { - return some(firstIdentifierSymbol.declarations, (idDecl) => isNodeDescendantOf(idDecl, tpScope)) || some(node2.typeArguments, containsReference); + return some(firstIdentifierSymbol.declarations, idDecl => isNodeDescendantOf(idDecl, tpScope)) || some(node2.typeArguments, containsReference); } } return true; @@ -61466,29 +57255,24 @@ ${lanes.join("\n")} if (typeVariable) { const mappedTypeVariable = instantiateType(typeVariable, mapper); if (typeVariable !== mappedTypeVariable) { - return mapTypeWithAlias( - getReducedType(mappedTypeVariable), - (t) => { - if (t.flags & (3 /* AnyOrUnknown */ | 58982400 /* InstantiableNonPrimitive */ | 524288 /* Object */ | 2097152 /* Intersection */) && t !== wildcardType && !isErrorType(t)) { - if (!type.declaration.nameType) { - let constraint; - if (isArrayType(t) || t.flags & 1 /* Any */ && findResolutionCycleStartIndex(typeVariable, 4 /* ImmediateBaseConstraint */) < 0 && (constraint = getConstraintOfTypeParameter(typeVariable)) && everyType(constraint, isArrayOrTupleType)) { - return instantiateMappedArrayType(t, type, prependTypeMapping(typeVariable, t, mapper)); - } - if (isGenericTupleType(t)) { - return instantiateMappedGenericTupleType(t, type, typeVariable, mapper); - } - if (isTupleType(t)) { - return instantiateMappedTupleType(t, type, prependTypeMapping(typeVariable, t, mapper)); - } + return mapTypeWithAlias(getReducedType(mappedTypeVariable), t => { + if (t.flags & (3 /* AnyOrUnknown */ | 58982400 /* InstantiableNonPrimitive */ | 524288 /* Object */ | 2097152 /* Intersection */) && t !== wildcardType && !isErrorType(t)) { + if (!type.declaration.nameType) { + let constraint; + if (isArrayType(t) || t.flags & 1 /* Any */ && findResolutionCycleStartIndex(typeVariable, 4 /* ImmediateBaseConstraint */) < 0 && (constraint = getConstraintOfTypeParameter(typeVariable)) && everyType(constraint, isArrayOrTupleType)) { + return instantiateMappedArrayType(t, type, prependTypeMapping(typeVariable, t, mapper)); + } + if (isGenericTupleType(t)) { + return instantiateMappedGenericTupleType(t, type, typeVariable, mapper); + } + if (isTupleType(t)) { + return instantiateMappedTupleType(t, type, prependTypeMapping(typeVariable, t, mapper)); } - return instantiateAnonymousType(type, prependTypeMapping(typeVariable, t, mapper)); } - return t; - }, - aliasSymbol, - aliasTypeArguments - ); + return instantiateAnonymousType(type, prependTypeMapping(typeVariable, t, mapper)); + } + return t; + }, aliasSymbol, aliasTypeArguments); } } return instantiateType(getConstraintTypeFromMappedType(type), mapper) === wildcardType ? wildcardType : instantiateAnonymousType(type, mapper, aliasSymbol, aliasTypeArguments); @@ -61506,23 +57290,18 @@ ${lanes.join("\n")} return instantiateMappedType(mappedType, prependTypeMapping(typeVariable, singleton, mapper)); }); const newReadonly = getModifiedReadonlyState(tupleType.target.readonly, getMappedTypeModifiers(mappedType)); - return createTupleType(elementTypes, map(elementTypes, (_) => 8 /* Variadic */), newReadonly); + return createTupleType(elementTypes, map(elementTypes, _ => 8 /* Variadic */), newReadonly); } function instantiateMappedArrayType(arrayType, mappedType, mapper) { - const elementType = instantiateMappedTypeTemplate( - mappedType, - numberType, - /*isOptional*/ - true, - mapper - ); + const elementType = instantiateMappedTypeTemplate(mappedType, numberType, /*isOptional*/ + true, mapper); return isErrorType(elementType) ? errorType : createArrayType(elementType, getModifiedReadonlyState(isReadonlyArrayType(arrayType), getMappedTypeModifiers(mappedType))); } function instantiateMappedTupleType(tupleType, mappedType, mapper) { const elementFlags = tupleType.target.elementFlags; const elementTypes = map(getElementTypes(tupleType), (_, i) => instantiateMappedTypeTemplate(mappedType, getStringLiteralType("" + i), !!(elementFlags[i] & 2 /* Optional */), mapper)); const modifiers = getMappedTypeModifiers(mappedType); - const newTupleModifiers = modifiers & 4 /* IncludeOptional */ ? map(elementFlags, (f) => f & 1 /* Required */ ? 2 /* Optional */ : f) : modifiers & 8 /* ExcludeOptional */ ? map(elementFlags, (f) => f & 2 /* Optional */ ? 1 /* Required */ : f) : elementFlags; + const newTupleModifiers = modifiers & 4 /* IncludeOptional */ ? map(elementFlags, f => f & 1 /* Required */ ? 2 /* Optional */ : f) : modifiers & 8 /* ExcludeOptional */ ? map(elementFlags, f => f & 2 /* Optional */ ? 1 /* Required */ : f) : elementFlags; const newReadonly = getModifiedReadonlyState(tupleType.target.readonly, modifiers); return contains(elementTypes, errorType) ? errorType : createTupleType(elementTypes, newTupleModifiers, newReadonly, tupleType.target.labeledElementDeclarations); } @@ -61530,11 +57309,8 @@ ${lanes.join("\n")} const templateMapper = appendTypeMapping(mapper, getTypeParameterFromMappedType(type), key); const propType = instantiateType(getTemplateTypeFromMappedType(type.target || type), templateMapper); const modifiers = getMappedTypeModifiers(type); - return strictNullChecks && modifiers & 4 /* IncludeOptional */ && !maybeTypeOfKind(propType, 32768 /* Undefined */ | 16384 /* Void */) ? getOptionalType( - propType, - /*isProperty*/ - true - ) : strictNullChecks && modifiers & 8 /* ExcludeOptional */ && isOptional ? getTypeWithFacts(propType, 524288 /* NEUndefined */) : propType; + return strictNullChecks && modifiers & 4 /* IncludeOptional */ && !maybeTypeOfKind(propType, 32768 /* Undefined */ | 16384 /* Void */) ? getOptionalType(propType, /*isProperty*/ + true) : strictNullChecks && modifiers & 8 /* ExcludeOptional */ && isOptional ? getTypeWithFacts(propType, 524288 /* NEUndefined */) : propType; } function instantiateAnonymousType(type, mapper, aliasSymbol, aliasTypeArguments) { const result = createObjectType(type.objectFlags & ~(524288 /* CouldContainTypeVariablesComputed */ | 1048576 /* CouldContainTypeVariables */) | 64 /* Instantiated */, type.symbol); @@ -61559,14 +57335,14 @@ ${lanes.join("\n")} function getConditionalTypeInstantiation(type, mapper, aliasSymbol, aliasTypeArguments) { const root = type.root; if (root.outerTypeParameters) { - const typeArguments = map(root.outerTypeParameters, (t) => getMappedType(t, mapper)); + const typeArguments = map(root.outerTypeParameters, t => getMappedType(t, mapper)); const id = getTypeListId(typeArguments) + getAliasId(aliasSymbol, aliasTypeArguments); let result = root.instantiations.get(id); if (!result) { const newMapper = createTypeMapper(root.outerTypeParameters, typeArguments); const checkType = root.checkType; const distributionType = root.isDistributive ? getMappedType(checkType, newMapper) : void 0; - result = distributionType && checkType !== distributionType && distributionType.flags & (1048576 /* Union */ | 131072 /* Never */) ? mapTypeWithAlias(getReducedType(distributionType), (t) => getConditionalType(root, prependTypeMapping(checkType, t, newMapper)), aliasSymbol, aliasTypeArguments) : getConditionalType(root, newMapper, aliasSymbol, aliasTypeArguments); + result = distributionType && checkType !== distributionType && distributionType.flags & (1048576 /* Union */ | 131072 /* Never */) ? mapTypeWithAlias(getReducedType(distributionType), t => getConditionalType(root, prependTypeMapping(checkType, t, newMapper)), aliasSymbol, aliasTypeArguments) : getConditionalType(root, newMapper, aliasSymbol, aliasTypeArguments); root.instantiations.set(id, result); } return result; @@ -61574,14 +57350,9 @@ ${lanes.join("\n")} return type; } function instantiateType(type, mapper) { - return type && mapper ? instantiateTypeWithAlias( - type, - mapper, - /*aliasSymbol*/ - void 0, - /*aliasTypeArguments*/ - void 0 - ) : type; + return type && mapper ? instantiateTypeWithAlias(type, mapper, /*aliasSymbol*/ + void 0, /*aliasTypeArguments*/ + void 0) : type; } function instantiateTypeWithAlias(type, mapper, aliasSymbol, aliasTypeArguments) { var _a; @@ -61589,7 +57360,11 @@ ${lanes.join("\n")} return type; } if (instantiationDepth === 100 || instantiationCount >= 5e6) { - (_a = tracing) == null ? void 0 : _a.instant(tracing.Phase.CheckTypes, "instantiateType_DepthLimit", { typeId: type.id, instantiationDepth, instantiationCount }); + (_a = tracing) == null ? void 0 : _a.instant(tracing.Phase.CheckTypes, "instantiateType_DepthLimit", { + typeId: type.id, + instantiationDepth, + instantiationCount + }); error2(currentNode, Diagnostics.Type_instantiation_is_excessively_deep_and_possibly_infinite); return errorType; } @@ -61643,15 +57418,8 @@ ${lanes.join("\n")} if (flags & 8388608 /* IndexedAccess */) { const newAliasSymbol = aliasSymbol || type.aliasSymbol; const newAliasTypeArguments = aliasSymbol ? aliasTypeArguments : instantiateTypes(type.aliasTypeArguments, mapper); - return getIndexedAccessType( - instantiateType(type.objectType, mapper), - instantiateType(type.indexType, mapper), - type.accessFlags, - /*accessNode*/ - void 0, - newAliasSymbol, - newAliasTypeArguments - ); + return getIndexedAccessType(instantiateType(type.objectType, mapper), instantiateType(type.indexType, mapper), type.accessFlags, /*accessNode*/ + void 0, newAliasSymbol, newAliasTypeArguments); } if (flags & 16777216 /* Conditional */) { return getConditionalTypeInstantiation(type, combineTypeMappers(type.mapper, mapper), aliasSymbol, aliasTypeArguments); @@ -61678,11 +57446,7 @@ ${lanes.join("\n")} if (!(innerIndexType.flags & 4194304 /* Index */)) { return type; } - const instantiated = inferTypeForHomomorphicMappedType( - instantiateType(type.source, mapper), - innerMappedType, - innerIndexType - ); + const instantiated = inferTypeForHomomorphicMappedType(instantiateType(type.source, mapper), innerMappedType, innerIndexType); if (instantiated) { return instantiated; } @@ -61727,14 +57491,20 @@ ${lanes.join("\n")} return isContextSensitive(node.expression); case 292 /* JsxAttributes */: return some(node.properties, isContextSensitive) || isJsxOpeningElement(node.parent) && some(node.parent.parent.children, isContextSensitive); - case 291 /* JsxAttribute */: { - const { initializer } = node; - return !!initializer && isContextSensitive(initializer); - } - case 294 /* JsxExpression */: { - const { expression } = node; - return !!expression && isContextSensitive(expression); - } + case 291 /* JsxAttribute */: + { + const { + initializer + } = node; + return !!initializer && isContextSensitive(initializer); + } + case 294 /* JsxExpression */: + { + const { + expression + } = node; + return !!expression && isContextSensitive(expression); + } } return false; } @@ -61748,7 +57518,7 @@ ${lanes.join("\n")} if (node.body.kind !== 241 /* Block */) { return isContextSensitive(node.body); } - return !!forEachReturnStatement(node.body, (statement) => !!statement.expression && isContextSensitive(statement.expression)); + return !!forEachReturnStatement(node.body, statement => !!statement.expression && isContextSensitive(statement.expression)); } function isContextSensitiveFunctionOrObjectLiteralMethod(func) { return (isFunctionExpressionOrArrowFunction(func) || isObjectLiteralMethod(func)) && isContextSensitiveFunctionLikeDeclaration(func); @@ -61776,12 +57546,15 @@ ${lanes.join("\n")} function compareTypesIdentical(source, target) { return isTypeRelatedTo(source, target, identityRelation) ? -1 /* True */ : 0 /* False */; } + function compareTypesAssignable(source, target) { return isTypeRelatedTo(source, target, assignableRelation) ? -1 /* True */ : 0 /* False */; } + function compareTypesSubtypeOf(source, target) { return isTypeRelatedTo(source, target, subtypeRelation) ? -1 /* True */ : 0 /* False */; } + function isTypeSubtypeOf(source, target) { return isTypeRelatedTo(source, target, subtypeRelation); } @@ -61792,7 +57565,7 @@ ${lanes.join("\n")} return isTypeRelatedTo(source, target, assignableRelation); } function isTypeDerivedFrom(source, target) { - return source.flags & 1048576 /* Union */ ? every(source.types, (t) => isTypeDerivedFrom(t, target)) : target.flags & 1048576 /* Union */ ? some(target.types, (t) => isTypeDerivedFrom(source, t)) : source.flags & 2097152 /* Intersection */ ? some(source.types, (t) => isTypeDerivedFrom(t, target)) : source.flags & 58982400 /* InstantiableNonPrimitive */ ? isTypeDerivedFrom(getBaseConstraintOfType(source) || unknownType, target) : isEmptyAnonymousObjectType(target) ? !!(source.flags & (524288 /* Object */ | 67108864 /* NonPrimitive */)) : target === globalObjectType ? !!(source.flags & (524288 /* Object */ | 67108864 /* NonPrimitive */)) && !isEmptyAnonymousObjectType(source) : target === globalFunctionType ? !!(source.flags & 524288 /* Object */) && isFunctionObjectType(source) : hasBaseType(source, getTargetType(target)) || isArrayType(target) && !isReadonlyArrayType(target) && isTypeDerivedFrom(source, globalReadonlyArrayType); + return source.flags & 1048576 /* Union */ ? every(source.types, t => isTypeDerivedFrom(t, target)) : target.flags & 1048576 /* Union */ ? some(target.types, t => isTypeDerivedFrom(source, t)) : source.flags & 2097152 /* Intersection */ ? some(source.types, t => isTypeDerivedFrom(t, target)) : source.flags & 58982400 /* InstantiableNonPrimitive */ ? isTypeDerivedFrom(getBaseConstraintOfType(source) || unknownType, target) : isEmptyAnonymousObjectType(target) ? !!(source.flags & (524288 /* Object */ | 67108864 /* NonPrimitive */)) : target === globalObjectType ? !!(source.flags & (524288 /* Object */ | 67108864 /* NonPrimitive */)) && !isEmptyAnonymousObjectType(source) : target === globalFunctionType ? !!(source.flags & 524288 /* Object */) && isFunctionObjectType(source) : hasBaseType(source, getTargetType(target)) || isArrayType(target) && !isReadonlyArrayType(target) && isTypeDerivedFrom(source, globalReadonlyArrayType); } function isTypeComparableTo(source, target) { return isTypeRelatedTo(source, target, comparableRelation); @@ -61804,21 +57577,11 @@ ${lanes.join("\n")} return checkTypeRelatedTo(source, target, assignableRelation, errorNode, headMessage, containingMessageChain, errorOutputObject); } function checkTypeAssignableToAndOptionallyElaborate(source, target, errorNode, expr, headMessage, containingMessageChain) { - return checkTypeRelatedToAndOptionallyElaborate( - source, - target, - assignableRelation, - errorNode, - expr, - headMessage, - containingMessageChain, - /*errorOutputContainer*/ - void 0 - ); + return checkTypeRelatedToAndOptionallyElaborate(source, target, assignableRelation, errorNode, expr, headMessage, containingMessageChain, /*errorOutputContainer*/ + void 0); } 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); } @@ -61828,15 +57591,9 @@ ${lanes.join("\n")} 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 (!checkTypeRelatedTo( - source, - target, - relation, - /*errorNode*/ - void 0 - ) && elaborateDidYouMeanToCallOrConstruct(node, source, target, relation, headMessage, containingMessageChain, errorOutputContainer)) { + if (!node || isOrHasGenericConditional(target)) return false; + if (!checkTypeRelatedTo(source, target, relation, /*errorNode*/ + void 0) && elaborateDidYouMeanToCallOrConstruct(node, source, target, relation, headMessage, containingMessageChain, errorOutputContainer)) { return true; } switch (node.kind) { @@ -61869,26 +57626,15 @@ ${lanes.join("\n")} const callSignatures = getSignaturesOfType(source, 0 /* Call */); const constructSignatures = getSignaturesOfType(source, 1 /* Construct */); for (const signatures of [constructSignatures, callSignatures]) { - if (some(signatures, (s) => { + if (some(signatures, s => { const returnType = getReturnTypeOfSignature(s); - return !(returnType.flags & (1 /* Any */ | 131072 /* Never */)) && checkTypeRelatedTo( - returnType, - target, - relation, - /*errorNode*/ - void 0 - ); + return !(returnType.flags & (1 /* Any */ | 131072 /* Never */)) && checkTypeRelatedTo(returnType, target, relation, /*errorNode*/ + void 0); })) { const resultObj = errorOutputContainer || {}; checkTypeAssignableTo(source, target, node, headMessage, containingMessageChain, resultObj); const diagnostic = resultObj.errors[resultObj.errors.length - 1]; - addRelatedInfo( - diagnostic, - createDiagnosticForNode( - node, - signatures === constructSignatures ? Diagnostics.Did_you_mean_to_use_new_with_this_expression : Diagnostics.Did_you_mean_to_call_this_expression - ) - ); + addRelatedInfo(diagnostic, createDiagnosticForNode(node, signatures === constructSignatures ? Diagnostics.Did_you_mean_to_use_new_with_this_expression : Diagnostics.Did_you_mean_to_call_this_expression)); return true; } } @@ -61912,61 +57658,23 @@ ${lanes.join("\n")} const returnExpression = node.body; const sourceReturn = getReturnTypeOfSignature(sourceSig); const targetReturn = getUnionType(map(targetSignatures, getReturnTypeOfSignature)); - if (!checkTypeRelatedTo( - sourceReturn, - targetReturn, - relation, - /*errorNode*/ - void 0 - )) { - const elaborated = returnExpression && elaborateError( - returnExpression, - sourceReturn, - targetReturn, - relation, - /*headMessage*/ - void 0, - containingMessageChain, - errorOutputContainer - ); + if (!checkTypeRelatedTo(sourceReturn, targetReturn, relation, /*errorNode*/ + void 0)) { + const elaborated = returnExpression && elaborateError(returnExpression, sourceReturn, targetReturn, relation, /*headMessage*/ + void 0, containingMessageChain, errorOutputContainer); if (elaborated) { return elaborated; } const resultObj = errorOutputContainer || {}; - checkTypeRelatedTo( - sourceReturn, - targetReturn, - relation, - returnExpression, - /*headMessage*/ - void 0, - containingMessageChain, - resultObj - ); + checkTypeRelatedTo(sourceReturn, targetReturn, relation, returnExpression, /*headMessage*/ + void 0, containingMessageChain, resultObj); if (resultObj.errors) { if (target.symbol && length(target.symbol.declarations)) { - addRelatedInfo( - resultObj.errors[resultObj.errors.length - 1], - createDiagnosticForNode( - target.symbol.declarations[0], - Diagnostics.The_expected_type_comes_from_the_return_type_of_this_signature - ) - ); + addRelatedInfo(resultObj.errors[resultObj.errors.length - 1], createDiagnosticForNode(target.symbol.declarations[0], Diagnostics.The_expected_type_comes_from_the_return_type_of_this_signature)); } - if ((getFunctionFlags(node) & 2 /* Async */) === 0 && !getTypeOfPropertyOfType(sourceReturn, "then") && checkTypeRelatedTo( - createPromiseType(sourceReturn), - targetReturn, - relation, - /*errorNode*/ - void 0 - )) { - addRelatedInfo( - resultObj.errors[resultObj.errors.length - 1], - createDiagnosticForNode( - node, - Diagnostics.Did_you_mean_to_mark_this_function_as_async - ) - ); + if ((getFunctionFlags(node) & 2 /* Async */) === 0 && !getTypeOfPropertyOfType(sourceReturn, "then") && checkTypeRelatedTo(createPromiseType(sourceReturn), targetReturn, relation, /*errorNode*/ + void 0)) { + addRelatedInfo(resultObj.errors[resultObj.errors.length - 1], createDiagnosticForNode(node, Diagnostics.Did_you_mean_to_mark_this_function_as_async)); } return true; } @@ -61986,12 +57694,8 @@ ${lanes.join("\n")} } } function checkExpressionForMutableLocationWithContextualType(next, sourcePropType) { - pushContextualType( - next, - sourcePropType, - /*isCache*/ - false - ); + pushContextualType(next, sourcePropType, /*isCache*/ + false); const result = checkExpressionForMutableLocation(next, 1 /* Contextual */); popContextualType(); return result; @@ -61999,35 +57703,22 @@ ${lanes.join("\n")} function elaborateElementwise(iterator, source, target, relation, containingMessageChain, errorOutputContainer) { let reportedError = false; 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; - let sourcePropType = getIndexedAccessTypeOrUndefined(source, nameType); - if (!sourcePropType) - continue; - const propName = getPropertyNameFromIndex( + const { + errorNode: prop, + innerExpression: next, nameType, - /*accessNode*/ - void 0 - ); - if (!checkTypeRelatedTo( - sourcePropType, - targetPropType, - relation, - /*errorNode*/ - void 0 - )) { - const elaborated = next && elaborateError( - next, - sourcePropType, - targetPropType, - relation, - /*headMessage*/ - void 0, - containingMessageChain, - errorOutputContainer - ); + errorMessage + } = value; + let targetPropType = getBestMatchIndexedAccessTypeOrUndefined(source, target, nameType); + if (!targetPropType || targetPropType.flags & 8388608 /* IndexedAccess */) continue; + let sourcePropType = getIndexedAccessTypeOrUndefined(source, nameType); + if (!sourcePropType) continue; + const propName = getPropertyNameFromIndex(nameType, /*accessNode*/ + void 0); + if (!checkTypeRelatedTo(sourcePropType, targetPropType, relation, /*errorNode*/ + void 0)) { + const elaborated = next && elaborateError(next, sourcePropType, targetPropType, relation, /*headMessage*/ + void 0, containingMessageChain, errorOutputContainer); reportedError = true; if (!elaborated) { const resultObj = errorOutputContainer || {}; @@ -62061,15 +57752,7 @@ ${lanes.join("\n")} if (!issuedElaboration && (targetProp && length(targetProp.declarations) || target.symbol && length(target.symbol.declarations))) { const targetNode = targetProp && length(targetProp.declarations) ? targetProp.declarations[0] : target.symbol.declarations[0]; if (!getSourceFileOfNode(targetNode).hasNoDefaultLib) { - addRelatedInfo( - reportedDiag, - createDiagnosticForNode( - targetNode, - Diagnostics.The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1, - propertyName && !(nameType.flags & 8192 /* UniqueESSymbol */) ? unescapeLeadingUnderscores(propertyName) : typeToString(nameType), - typeToString(target) - ) - ); + addRelatedInfo(reportedDiag, createDiagnosticForNode(targetNode, Diagnostics.The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1, propertyName && !(nameType.flags & 8192 /* UniqueESSymbol */) ? unescapeLeadingUnderscores(propertyName) : typeToString(nameType), typeToString(target))); } } } @@ -62080,49 +57763,31 @@ ${lanes.join("\n")} } function elaborateIterableOrArrayLikeTargetElementwise(iterator, source, target, relation, containingMessageChain, errorOutputContainer) { const tupleOrArrayLikeTargetParts = filterType(target, isArrayOrTupleLikeType); - const nonTupleOrArrayLikeTargetParts = filterType(target, (t) => !isArrayOrTupleLikeType(t)); - const iterationType = nonTupleOrArrayLikeTargetParts !== neverType ? getIterationTypeOfIterable( - 13 /* ForOf */, - 0 /* Yield */, - nonTupleOrArrayLikeTargetParts, - /*errorNode*/ - void 0 - ) : void 0; + const nonTupleOrArrayLikeTargetParts = filterType(target, t => !isArrayOrTupleLikeType(t)); + const iterationType = nonTupleOrArrayLikeTargetParts !== neverType ? getIterationTypeOfIterable(13 /* ForOf */, 0 /* Yield */, nonTupleOrArrayLikeTargetParts, /*errorNode*/ + void 0) : void 0; let reportedError = false; for (let status = iterator.next(); !status.done; status = iterator.next()) { - const { errorNode: prop, innerExpression: next, nameType, errorMessage } = status.value; + const { + errorNode: prop, + innerExpression: next, + nameType, + errorMessage + } = status.value; let targetPropType = iterationType; const targetIndexedPropType = tupleOrArrayLikeTargetParts !== neverType ? getBestMatchIndexedAccessTypeOrUndefined(source, tupleOrArrayLikeTargetParts, nameType) : void 0; if (targetIndexedPropType && !(targetIndexedPropType.flags & 8388608 /* IndexedAccess */)) { targetPropType = iterationType ? getUnionType([iterationType, targetIndexedPropType]) : targetIndexedPropType; } - if (!targetPropType) - continue; + if (!targetPropType) continue; let sourcePropType = getIndexedAccessTypeOrUndefined(source, nameType); - if (!sourcePropType) - continue; - const propName = getPropertyNameFromIndex( - nameType, - /*accessNode*/ - void 0 - ); - if (!checkTypeRelatedTo( - sourcePropType, - targetPropType, - relation, - /*errorNode*/ - void 0 - )) { - const elaborated = next && elaborateError( - next, - sourcePropType, - targetPropType, - relation, - /*headMessage*/ - void 0, - containingMessageChain, - errorOutputContainer - ); + if (!sourcePropType) continue; + const propName = getPropertyNameFromIndex(nameType, /*accessNode*/ + void 0); + if (!checkTypeRelatedTo(sourcePropType, targetPropType, relation, /*errorNode*/ + void 0)) { + const elaborated = next && elaborateError(next, sourcePropType, targetPropType, relation, /*headMessage*/ + void 0, containingMessageChain, errorOutputContainer); reportedError = true; if (!elaborated) { const resultObj = errorOutputContainer || {}; @@ -62147,17 +57812,18 @@ ${lanes.join("\n")} 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; - yield { errorNode: prop.name, innerExpression: prop.initializer, nameType: getStringLiteralType(getTextOfJsxAttributeName(prop.name)) }; + 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]; @@ -62173,16 +57839,29 @@ ${lanes.join("\n")} function getElaborationElementForJsxChild(child, nameType, getInvalidTextDiagnostic) { switch (child.kind) { case 294 /* JsxExpression */: - return { errorNode: child, innerExpression: child.expression, nameType }; + return { + errorNode: child, + innerExpression: child.expression, + nameType + }; case 12 /* JsxText */: if (child.containsOnlyTriviaWhiteSpaces) { break; } - return { errorNode: child, innerExpression: void 0, nameType, errorMessage: getInvalidTextDiagnostic() }; + return { + errorNode: child, + innerExpression: void 0, + nameType, + errorMessage: getInvalidTextDiagnostic() + }; case 284 /* JsxElement */: case 285 /* JsxSelfClosingElement */: case 288 /* JsxFragment */: - return { errorNode: child, innerExpression: child, nameType }; + return { + errorNode: child, + innerExpression: child, + nameType + }; default: return Debug.assertNever(child, "Found invalid jsx child"); } @@ -62203,17 +57882,15 @@ ${lanes.join("\n")} const moreThanOneRealChildren = length(validChildren) > 1; let arrayLikeTargetParts; let nonArrayLikeTargetParts; - const iterableType = getGlobalIterableType( - /*reportErrors*/ - false - ); + const iterableType = getGlobalIterableType( /*reportErrors*/ + false); if (iterableType !== emptyGenericType) { const anyIterable = createIterableType(anyType); - arrayLikeTargetParts = filterType(childrenTargetType, (t) => isTypeAssignableTo(t, anyIterable)); - nonArrayLikeTargetParts = filterType(childrenTargetType, (t) => !isTypeAssignableTo(t, anyIterable)); + arrayLikeTargetParts = filterType(childrenTargetType, t => isTypeAssignableTo(t, anyIterable)); + nonArrayLikeTargetParts = filterType(childrenTargetType, t => !isTypeAssignableTo(t, anyIterable)); } else { arrayLikeTargetParts = filterType(childrenTargetType, isArrayOrTupleLikeType); - nonArrayLikeTargetParts = filterType(childrenTargetType, (t) => !isArrayOrTupleLikeType(t)); + nonArrayLikeTargetParts = filterType(childrenTargetType, t => !isArrayOrTupleLikeType(t)); } if (moreThanOneRealChildren) { if (arrayLikeTargetParts !== neverType) { @@ -62222,12 +57899,7 @@ ${lanes.join("\n")} result = elaborateIterableOrArrayLikeTargetElementwise(children, realSource, arrayLikeTargetParts, relation, containingMessageChain, errorOutputContainer) || result; } else if (!isTypeRelatedTo(getIndexedAccessType(source, childrenNameType), childrenTargetType, relation)) { result = true; - const diag2 = error2( - containingElement.openingElement.tagName, - Diagnostics.This_JSX_tag_s_0_prop_expects_a_single_child_of_type_1_but_multiple_children_were_provided, - childrenPropName, - typeToString(childrenTargetType) - ); + const diag2 = error2(containingElement.openingElement.tagName, Diagnostics.This_JSX_tag_s_0_prop_expects_a_single_child_of_type_1_but_multiple_children_were_provided, childrenPropName, typeToString(childrenTargetType)); if (errorOutputContainer && errorOutputContainer.skipLogging) { (errorOutputContainer.errors || (errorOutputContainer.errors = [])).push(diag2); } @@ -62237,25 +57909,13 @@ ${lanes.join("\n")} const child = validChildren[0]; const elem = getElaborationElementForJsxChild(child, childrenNameType, getInvalidTextualChildDiagnostic); if (elem) { - result = elaborateElementwise( - function* () { - yield elem; - }(), - source, - target, - relation, - containingMessageChain, - errorOutputContainer - ) || result; + result = elaborateElementwise(function* () { + yield elem; + }(), source, target, relation, containingMessageChain, errorOutputContainer) || result; } } else if (!isTypeRelatedTo(getIndexedAccessType(source, childrenNameType), childrenTargetType, relation)) { result = true; - const diag2 = error2( - containingElement.openingElement.tagName, - Diagnostics.This_JSX_tag_s_0_prop_expects_type_1_which_requires_multiple_children_but_only_a_single_child_was_provided, - childrenPropName, - typeToString(childrenTargetType) - ); + const diag2 = error2(containingElement.openingElement.tagName, Diagnostics.This_JSX_tag_s_0_prop_expects_type_1_which_requires_multiple_children_but_only_a_single_child_was_provided, childrenPropName, typeToString(childrenTargetType)); if (errorOutputContainer && errorOutputContainer.skipLogging) { (errorOutputContainer.errors || (errorOutputContainer.errors = [])).push(diag2); } @@ -62270,43 +57930,39 @@ ${lanes.join("\n")} const childrenPropName = childPropName === void 0 ? "children" : unescapeLeadingUnderscores(childPropName); const childrenTargetType = getIndexedAccessType(target, getStringLiteralType(childrenPropName)); const diagnostic = Diagnostics._0_components_don_t_accept_text_as_child_elements_Text_in_JSX_has_the_type_string_but_the_expected_type_of_1_is_2; - invalidTextDiagnostic = { ...diagnostic, key: "!!ALREADY FORMATTED!!", message: formatMessage(diagnostic, tagNameText, childrenPropName, typeToString(childrenTargetType)) }; + invalidTextDiagnostic = { + ...diagnostic, + key: "!!ALREADY FORMATTED!!", + message: formatMessage(diagnostic, tagNameText, childrenPropName, typeToString(childrenTargetType)) + }; } return invalidTextDiagnostic; } } 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); - yield { errorNode: elem, innerExpression: elem, nameType }; + yield { + errorNode: elem, + innerExpression: elem, + 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); } - pushContextualType( - node, - target, - /*isCache*/ - false - ); - const tupleizedType = checkArrayLiteral( - node, - 1 /* Contextual */, - /*forceTuple*/ - true - ); + pushContextualType(node, target, /*isCache*/ + false); + const tupleizedType = checkArrayLiteral(node, 1 /* Contextual */, /*forceTuple*/ + true); popContextualType(); if (isTupleLikeType(tupleizedType)) { return elaborateElementwise(generateLimitedTupleElements(node, target), tupleizedType, target, relation, containingMessageChain, errorOutputContainer); @@ -62314,11 +57970,9 @@ ${lanes.join("\n")} 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; @@ -62328,10 +57982,19 @@ ${lanes.join("\n")} case 177 /* GetAccessor */: case 174 /* MethodDeclaration */: case 304 /* ShorthandPropertyAssignment */: - yield { errorNode: prop.name, innerExpression: void 0, nameType: type }; + yield { + errorNode: prop.name, + innerExpression: void 0, + nameType: type + }; break; case 303 /* PropertyAssignment */: - yield { errorNode: prop.name, innerExpression: prop.initializer, nameType: type, errorMessage: isComputedNonLiteralName(prop.name) ? Diagnostics.Type_of_computed_property_s_value_is_0_which_is_not_assignable_to_type_1 : void 0 }; + yield { + errorNode: prop.name, + innerExpression: prop.initializer, + nameType: type, + errorMessage: isComputedNonLiteralName(prop.name) ? Diagnostics.Type_of_computed_property_s_value_is_0_which_is_not_assignable_to_type_1 : void 0 + }; break; default: Debug.assertNever(prop); @@ -62339,47 +58002,42 @@ ${lanes.join("\n")} } } 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) { return checkTypeRelatedTo(source, target, comparableRelation, errorNode, headMessage, containingMessageChain); } function isSignatureAssignableTo(source, target, ignoreReturnTypes) { - return compareSignaturesRelated( - source, - target, - ignoreReturnTypes ? 4 /* IgnoreReturnTypes */ : 0 /* None */, - /*reportErrors*/ - false, - /*errorReporter*/ - void 0, - /*incompatibleErrorReporter*/ - void 0, - compareTypesAssignable, - /*reportUnreliableMarkers*/ - void 0 - ) !== 0 /* False */; + return compareSignaturesRelated(source, target, ignoreReturnTypes ? 4 /* IgnoreReturnTypes */ : 0 /* None */, /*reportErrors*/ + false, /*errorReporter*/ + void 0, /*incompatibleErrorReporter*/ + void 0, compareTypesAssignable, /*reportUnreliableMarkers*/ + void 0) !== 0 /* False */; } + function isTopSignature(s) { if (!s.typeParameters && (!s.thisParameter || isTypeAny(getTypeOfParameter(s.thisParameter))) && s.parameters.length === 1 && signatureHasRestParameter(s)) { const paramType = getTypeOfParameter(s.parameters[0]); const restType = isArrayType(paramType) ? getTypeArguments(paramType)[0] : paramType; return !!(restType.flags & (1 /* Any */ | 131072 /* Never */) && getReturnTypeOfSignature(s).flags & 3 /* AnyOrUnknown */); } + return false; } function compareSignaturesRelated(source, target, checkMode, reportErrors2, errorReporter, incompatibleErrorReporter, compareTypes, reportUnreliableMarkers) { if (source === target) { return -1 /* True */; } + if (!(checkMode & 16 /* StrictTopSignature */ && isTopSignature(source)) && isTopSignature(target)) { return -1 /* True */; } + if (checkMode & 16 /* StrictTopSignature */ && isTopSignature(source) && !isTopSignature(target)) { return 0 /* False */; } + const targetCount = getParameterCount(target); const sourceHasMoreParameters = !hasEffectiveRestParameter(target) && (checkMode & 8 /* StrictArity */ ? hasEffectiveRestParameter(source) || getParameterCount(source) > targetCount : getMinArgumentCount(source) > targetCount); if (sourceHasMoreParameters) { @@ -62388,15 +58046,11 @@ ${lanes.join("\n")} } return 0 /* False */; } + if (source.typeParameters && source.typeParameters !== target.typeParameters) { target = getCanonicalSignature(target); - source = instantiateSignatureInContextOf( - source, - target, - /*inferenceContext*/ - void 0, - compareTypes - ); + source = instantiateSignatureInContextOf(source, target, /*inferenceContext*/ + void 0, compareTypes); } const sourceCount = getParameterCount(source); const sourceRestType = getNonArrayRestType(source); @@ -62411,18 +58065,15 @@ ${lanes.join("\n")} if (sourceThisType && sourceThisType !== voidType) { const targetThisType = getThisTypeOfSignature(target); if (targetThisType) { - const related = !strictVariance && compareTypes( - sourceThisType, - targetThisType, - /*reportErrors*/ - false - ) || compareTypes(targetThisType, sourceThisType, reportErrors2); + const related = !strictVariance && compareTypes(sourceThisType, targetThisType, /*reportErrors*/ + false) || compareTypes(targetThisType, sourceThisType, reportErrors2); if (!related) { if (reportErrors2) { errorReporter(Diagnostics.The_this_types_of_each_signature_are_incompatible); } return 0 /* False */; } + result &= related; } } @@ -62435,26 +58086,20 @@ ${lanes.join("\n")} const sourceSig = checkMode & 3 /* Callback */ ? void 0 : getSingleCallSignature(getNonNullableType(sourceType)); const targetSig = checkMode & 3 /* Callback */ ? void 0 : getSingleCallSignature(getNonNullableType(targetType)); const callbacks = sourceSig && targetSig && !getTypePredicateOfSignature(sourceSig) && !getTypePredicateOfSignature(targetSig) && getTypeFacts(sourceType, 50331648 /* IsUndefinedOrNull */) === getTypeFacts(targetType, 50331648 /* IsUndefinedOrNull */); - let related = callbacks ? compareSignaturesRelated(targetSig, sourceSig, checkMode & 8 /* StrictArity */ | (strictVariance ? 2 /* StrictCallback */ : 1 /* BivariantCallback */), reportErrors2, errorReporter, incompatibleErrorReporter, compareTypes, reportUnreliableMarkers) : !(checkMode & 3 /* Callback */) && !strictVariance && compareTypes( - sourceType, - targetType, - /*reportErrors*/ - false - ) || compareTypes(targetType, sourceType, reportErrors2); - if (related && checkMode & 8 /* StrictArity */ && i >= getMinArgumentCount(source) && i < getMinArgumentCount(target) && compareTypes( - sourceType, - targetType, - /*reportErrors*/ - false - )) { + let related = callbacks ? compareSignaturesRelated(targetSig, sourceSig, checkMode & 8 /* StrictArity */ | (strictVariance ? 2 /* StrictCallback */ : 1 /* BivariantCallback */), reportErrors2, errorReporter, incompatibleErrorReporter, compareTypes, reportUnreliableMarkers) : !(checkMode & 3 /* Callback */) && !strictVariance && compareTypes(sourceType, targetType, /*reportErrors*/ + false) || compareTypes(targetType, sourceType, reportErrors2); + if (related && checkMode & 8 /* StrictArity */ && i >= getMinArgumentCount(source) && i < getMinArgumentCount(target) && compareTypes(sourceType, targetType, /*reportErrors*/ + false)) { related = 0 /* False */; } + if (!related) { if (reportErrors2) { errorReporter(Diagnostics.Types_of_parameters_0_and_1_are_incompatible, unescapeLeadingUnderscores(getParameterNameAtPosition(source, i)), unescapeLeadingUnderscores(getParameterNameAtPosition(target, i))); } return 0 /* False */; } + result &= related; } } @@ -62476,12 +58121,8 @@ ${lanes.join("\n")} return 0 /* False */; } } else { - result &= checkMode & 1 /* BivariantCallback */ && compareTypes( - targetReturnType, - sourceReturnType, - /*reportErrors*/ - false - ) || compareTypes(sourceReturnType, targetReturnType, reportErrors2); + result &= checkMode & 1 /* BivariantCallback */ && compareTypes(targetReturnType, sourceReturnType, /*reportErrors*/ + false) || compareTypes(sourceReturnType, targetReturnType, reportErrors2); if (!result && reportErrors2 && incompatibleErrorReporter) { incompatibleErrorReporter(sourceReturnType, targetReturnType); } @@ -62497,6 +58138,7 @@ ${lanes.join("\n")} } return 0 /* False */; } + if (source.kind === 1 /* Identifier */ || source.kind === 3 /* AssertsIdentifier */) { if (source.parameterIndex !== target.parameterIndex) { if (reportErrors2) { @@ -62506,6 +58148,7 @@ ${lanes.join("\n")} return 0 /* False */; } } + const related = source.type === target.type ? -1 /* True */ : source.type && target.type ? compareTypes(source.type, target.type, reportErrors2) : 0 /* False */; if (related === 0 /* False */ && reportErrors2) { errorReporter(Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target)); @@ -62518,12 +58161,8 @@ ${lanes.join("\n")} const sourceReturnType = getReturnTypeOfSignature(erasedSource); const targetReturnType = getReturnTypeOfSignature(erasedTarget); if (targetReturnType === voidType || isTypeRelatedTo(targetReturnType, sourceReturnType, assignableRelation) || isTypeRelatedTo(sourceReturnType, targetReturnType, assignableRelation)) { - return isSignatureAssignableTo( - erasedSource, - erasedTarget, - /*ignoreReturnTypes*/ - true - ); + return isSignatureAssignableTo(erasedSource, erasedTarget, /*ignoreReturnTypes*/ + true); } return false; } @@ -62544,11 +58183,13 @@ ${lanes.join("\n")} } return !!(type.objectFlags & 67108864 /* IsUnknownLikeUnion */); } + return false; } function containsUndefinedType(type) { return !!((type.flags & 1048576 /* Union */ ? type.types[0] : type).flags & 32768 /* Undefined */); } + function isStringIndexSignatureOnlyType(type) { return type.flags & 524288 /* Object */ && !isGenericMappedType(type) && getPropertiesOfType(type).length === 0 && getIndexInfosOfType(type).length === 1 && !!getIndexInfoOfType(type, stringType) || type.flags & 3145728 /* UnionOrIntersection */ && every(type.types, isStringIndexSignatureOnlyType) || false; } @@ -62566,22 +58207,21 @@ ${lanes.join("\n")} if (entry !== void 0 && !(!(entry & 4 /* Reported */) && entry & 2 /* Failed */ && errorReporter)) { return !!(entry & 1 /* Succeeded */); } + const targetEnumType = getTypeOfSymbol(targetSymbol); for (const property of getPropertiesOfType(getTypeOfSymbol(sourceSymbol))) { if (property.flags & 8 /* EnumMember */) { const targetProperty = getPropertyOfType(targetEnumType, property.escapedName); if (!targetProperty || !(targetProperty.flags & 8 /* EnumMember */)) { if (errorReporter) { - errorReporter(Diagnostics.Property_0_is_missing_in_type_1, symbolName(property), typeToString( - getDeclaredTypeOfSymbol(targetSymbol), - /*enclosingDeclaration*/ - void 0, - 64 /* UseFullyQualifiedType */ - )); + errorReporter(Diagnostics.Property_0_is_missing_in_type_1, symbolName(property), typeToString(getDeclaredTypeOfSymbol(targetSymbol), /*enclosingDeclaration*/ + void 0, 64 /* UseFullyQualifiedType */)); + enumRelation.set(id, 2 /* Failed */ | 4 /* Reported */); } else { enumRelation.set(id, 2 /* Failed */); } + return false; } } @@ -62592,49 +58232,29 @@ ${lanes.join("\n")} 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; } @@ -62653,32 +58273,20 @@ ${lanes.join("\n")} 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( - source, - target, - 0 /* None */, - relation, - /*ignoreConstraints*/ - false - )); + const related = relation.get(getRelationKey(source, target, 0 /* None */, relation, /*ignoreConstraints*/ + false)); if (related !== void 0) { return !!(related & 1 /* Succeeded */); } } + if (source.flags & 469499904 /* StructuredOrInstantiable */ || target.flags & 469499904 /* StructuredOrInstantiable */) { - return checkTypeRelatedTo( - source, - target, - relation, - /*errorNode*/ - void 0 - ); + return checkTypeRelatedTo(source, target, relation, /*errorNode*/ + void 0); } return false; } @@ -62688,8 +58296,7 @@ ${lanes.join("\n")} 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; } } @@ -62699,7 +58306,7 @@ ${lanes.join("\n")} return reduced; } if (type.flags & 2097152 /* Intersection */ && some(type.types, isEmptyAnonymousObjectType)) { - const normalizedTypes = sameMap(type.types, (t) => getNormalizedType(t, writing)); + const normalizedTypes = sameMap(type.types, t => getNormalizedType(t, writing)); if (normalizedTypes !== type.types) { return getIntersectionType(normalizedTypes); } @@ -62708,7 +58315,7 @@ ${lanes.join("\n")} } function getNormalizedTupleType(type, writing) { const elements = getElementTypes(type); - const normalizedElements = sameMap(elements, (t) => t.flags & 25165824 /* Simplifiable */ ? getSimplifiedType(t, writing) : t); + const normalizedElements = sameMap(elements, t => t.flags & 25165824 /* Simplifiable */ ? getSimplifiedType(t, writing) : t); return elements !== normalizedElements ? createNormalizedTupleType(type.target, normalizedElements) : type; } function checkTypeRelatedTo(source, target, relation, errorNode, headMessage, containingMessageChain, errorOutputContainer) { @@ -62730,29 +58337,22 @@ ${lanes.join("\n")} let incompatibleStack; let relationCount = 16e6 - relation.size >> 3; Debug.assert(relation !== identityRelation || !errorNode, "no error reporting in identity checking"); - const result = isRelatedTo( - source, - target, - 3 /* Both */, - /*reportErrors*/ - !!errorNode, - headMessage - ); + const result = isRelatedTo(source, target, 3 /* Both */, /*reportErrors*/ + !!errorNode, headMessage); if (incompatibleStack) { reportIncompatibleStack(); } if (overflow) { - const id = getRelationKey( - source, - target, - /*intersectionState*/ - 0 /* None */, - relation, - /*ignoreConstraints*/ - false - ); + const id = getRelationKey(source, target, /*intersectionState*/ + 0 /* None */, relation, /*ignoreConstraints*/ + false); relation.set(id, 4 /* Reported */ | 2 /* Failed */); - (_a = tracing) == null ? void 0 : _a.instant(tracing.Phase.CheckTypes, "checkTypeRelatedTo_DepthLimit", { sourceId: source.id, targetId: target.id, depth: sourceDepth, targetDepth }); + (_a = tracing) == null ? void 0 : _a.instant(tracing.Phase.CheckTypes, "checkTypeRelatedTo_DepthLimit", { + sourceId: source.id, + targetId: target.id, + depth: sourceDepth, + targetDepth + }); const message = relationCount <= 0 ? Diagnostics.Excessive_complexity_comparing_types_0_and_1 : Diagnostics.Excessive_stack_depth_comparing_types_0_and_1; const diag2 = error2(errorNode || currentNode, message, typeToString(source), typeToString(target)); if (errorOutputContainer) { @@ -62770,13 +58370,8 @@ ${lanes.join("\n")} if (headMessage && errorNode && !result && source.symbol) { const links = getSymbolLinks(source.symbol); if (links.originatingImport && !isImportCall(links.originatingImport)) { - const helpfulRetry = checkTypeRelatedTo( - getTypeOfSymbol(links.target), - target, - relation, - /*errorNode*/ - void 0 - ); + const helpfulRetry = checkTypeRelatedTo(getTypeOfSymbol(links.target), target, relation, /*errorNode*/ + void 0); if (helpfulRetry) { const diag3 = createDiagnosticForNode(links.originatingImport, 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); relatedInformation = append(relatedInformation, diag3); @@ -62829,11 +58424,8 @@ ${lanes.join("\n")} if (stack.length === 1) { reportError(...stack[0]); if (info) { - reportRelationError( - /*message*/ - void 0, - ...info - ); + reportRelationError( /*message*/ + void 0, ...info); } return; } @@ -62842,58 +58434,59 @@ ${lanes.join("\n")} while (stack.length) { const [msg, ...args] = stack.pop(); switch (msg.code) { - case Diagnostics.Types_of_property_0_are_incompatible.code: { - if (path.indexOf("new ") === 0) { - path = `(${path})`; + case Diagnostics.Types_of_property_0_are_incompatible.code: + { + if (path.indexOf("new ") === 0) { + path = `(${path})`; + } + const str = "" + args[0]; + if (path.length === 0) { + path = `${str}`; + } else if (isIdentifierText(str, getEmitScriptTarget(compilerOptions))) { + path = `${path}.${str}`; + } else if (str[0] === "[" && str[str.length - 1] === "]") { + path = `${path}${str}`; + } else { + path = `${path}[${str}]`; + } + break; } - const str = "" + args[0]; - if (path.length === 0) { - path = `${str}`; - } else if (isIdentifierText(str, getEmitScriptTarget(compilerOptions))) { - path = `${path}.${str}`; - } else if (str[0] === "[" && str[str.length - 1] === "]") { - path = `${path}${str}`; - } else { - path = `${path}[${str}]`; - } - break; - } case Diagnostics.Call_signature_return_types_0_and_1_are_incompatible.code: case Diagnostics.Construct_signature_return_types_0_and_1_are_incompatible.code: case Diagnostics.Call_signatures_with_no_arguments_have_incompatible_return_types_0_and_1.code: - case Diagnostics.Construct_signatures_with_no_arguments_have_incompatible_return_types_0_and_1.code: { - if (path.length === 0) { - let mappedMsg = msg; - if (msg.code === Diagnostics.Call_signatures_with_no_arguments_have_incompatible_return_types_0_and_1.code) { - mappedMsg = Diagnostics.Call_signature_return_types_0_and_1_are_incompatible; - } else if (msg.code === Diagnostics.Construct_signatures_with_no_arguments_have_incompatible_return_types_0_and_1.code) { - mappedMsg = Diagnostics.Construct_signature_return_types_0_and_1_are_incompatible; + case Diagnostics.Construct_signatures_with_no_arguments_have_incompatible_return_types_0_and_1.code: + { + if (path.length === 0) { + let mappedMsg = msg; + if (msg.code === Diagnostics.Call_signatures_with_no_arguments_have_incompatible_return_types_0_and_1.code) { + mappedMsg = Diagnostics.Call_signature_return_types_0_and_1_are_incompatible; + } else if (msg.code === Diagnostics.Construct_signatures_with_no_arguments_have_incompatible_return_types_0_and_1.code) { + mappedMsg = Diagnostics.Construct_signature_return_types_0_and_1_are_incompatible; + } + secondaryRootErrors.unshift([mappedMsg, args[0], args[1]]); + } else { + const prefix = msg.code === Diagnostics.Construct_signature_return_types_0_and_1_are_incompatible.code || msg.code === Diagnostics.Construct_signatures_with_no_arguments_have_incompatible_return_types_0_and_1.code ? "new " : ""; + const params = msg.code === Diagnostics.Call_signatures_with_no_arguments_have_incompatible_return_types_0_and_1.code || msg.code === Diagnostics.Construct_signatures_with_no_arguments_have_incompatible_return_types_0_and_1.code ? "" : "..."; + path = `${prefix}${path}(${params})`; } - secondaryRootErrors.unshift([mappedMsg, args[0], args[1]]); - } else { - const prefix = msg.code === Diagnostics.Construct_signature_return_types_0_and_1_are_incompatible.code || msg.code === Diagnostics.Construct_signatures_with_no_arguments_have_incompatible_return_types_0_and_1.code ? "new " : ""; - const params = msg.code === Diagnostics.Call_signatures_with_no_arguments_have_incompatible_return_types_0_and_1.code || msg.code === Diagnostics.Construct_signatures_with_no_arguments_have_incompatible_return_types_0_and_1.code ? "" : "..."; - path = `${prefix}${path}(${params})`; + break; + } + case Diagnostics.Type_at_position_0_in_source_is_not_compatible_with_type_at_position_1_in_target.code: + { + secondaryRootErrors.unshift([Diagnostics.Type_at_position_0_in_source_is_not_compatible_with_type_at_position_1_in_target, args[0], args[1]]); + break; + } + case Diagnostics.Type_at_positions_0_through_1_in_source_is_not_compatible_with_type_at_position_2_in_target.code: + { + secondaryRootErrors.unshift([Diagnostics.Type_at_positions_0_through_1_in_source_is_not_compatible_with_type_at_position_2_in_target, args[0], args[1], args[2]]); + break; } - break; - } - case Diagnostics.Type_at_position_0_in_source_is_not_compatible_with_type_at_position_1_in_target.code: { - secondaryRootErrors.unshift([Diagnostics.Type_at_position_0_in_source_is_not_compatible_with_type_at_position_1_in_target, args[0], args[1]]); - break; - } - case Diagnostics.Type_at_positions_0_through_1_in_source_is_not_compatible_with_type_at_position_2_in_target.code: { - secondaryRootErrors.unshift([Diagnostics.Type_at_positions_0_through_1_in_source_is_not_compatible_with_type_at_position_2_in_target, args[0], args[1], args[2]]); - break; - } default: return Debug.fail(`Unhandled Diagnostic: ${msg.code}`); } } if (path) { - reportError( - path[path.length - 1] === ")" ? Diagnostics.The_types_returned_by_0_are_incompatible_between_these_types : Diagnostics.The_types_of_0_are_incompatible_between_these_types, - path - ); + reportError(path[path.length - 1] === ")" ? Diagnostics.The_types_returned_by_0_are_incompatible_between_these_types : Diagnostics.The_types_of_0_are_incompatible_between_these_types, path); } else { secondaryRootErrors.shift(); } @@ -62904,19 +58497,14 @@ ${lanes.join("\n")} msg.elidedInCompatabilityPyramid = originalValue; } if (info) { - reportRelationError( - /*message*/ - void 0, - ...info - ); + reportRelationError( /*message*/ + void 0, ...info); } } 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 { @@ -62936,8 +58524,7 @@ ${lanes.join("\n")} } } function reportRelationError(message, source2, target2) { - if (incompatibleStack) - reportIncompatibleStack(); + if (incompatibleStack) reportIncompatibleStack(); const [sourceType, targetType] = getTypeNamesForErrorDisplay(source2, target2); let generalizedSource = source2; let generalizedSourceType = sourceType; @@ -62951,19 +58538,10 @@ ${lanes.join("\n")} const constraint = getBaseConstraintOfType(target2); let needsOriginalSource; if (constraint && (isTypeAssignableTo(generalizedSource, constraint) || (needsOriginalSource = isTypeAssignableTo(source2, constraint)))) { - reportError( - Diagnostics._0_is_assignable_to_the_constraint_of_type_1_but_1_could_be_instantiated_with_a_different_subtype_of_constraint_2, - needsOriginalSource ? sourceType : generalizedSourceType, - targetType, - typeToString(constraint) - ); + reportError(Diagnostics._0_is_assignable_to_the_constraint_of_type_1_but_1_could_be_instantiated_with_a_different_subtype_of_constraint_2, needsOriginalSource ? sourceType : generalizedSourceType, targetType, typeToString(constraint)); } else { errorInfo = void 0; - reportError( - Diagnostics._0_could_be_instantiated_with_an_arbitrary_type_which_could_be_unrelated_to_1, - targetType, - generalizedSourceType - ); + reportError(Diagnostics._0_could_be_instantiated_with_an_arbitrary_type_which_could_be_unrelated_to_1, targetType, generalizedSourceType); } } if (!message) { @@ -63020,64 +58598,47 @@ ${lanes.join("\n")} return isRelatedTo(source2, target2, 3 /* Both */, reportErrors2); } function isRelatedTo(originalSource, originalTarget, recursionFlags = 3 /* Both */, reportErrors2 = false, headMessage2, intersectionState = 0 /* None */) { - if (originalSource === 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 */; } + if (reportErrors2) { reportErrorResults(originalSource, originalTarget, originalSource, originalTarget, headMessage2); } return 0 /* False */; } - const source2 = getNormalizedType( - originalSource, - /*writing*/ - false - ); - let target2 = getNormalizedType( - originalTarget, - /*writing*/ - true - ); - if (source2 === target2) - return -1 /* True */; + + const source2 = getNormalizedType(originalSource, /*writing*/ + false); + let target2 = getNormalizedType(originalTarget, /*writing*/ + 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, - target2, - /*reportErrors*/ - false, - 0 /* None */, - recursionFlags - ); + return recursiveTypeRelatedTo(source2, target2, /*reportErrors*/ + false, 0 /* None */, recursionFlags); } if (source2.flags & 262144 /* TypeParameter */ && getConstraintOfType(source2) === target2) { return -1 /* True */; } + if (source2.flags & 470302716 /* DefinitelyNonNullable */ && target2.flags & 1048576 /* Union */) { const types = target2.types; const candidate = types.length === 2 && types[0].flags & 98304 /* Nullable */ ? types[1] : types.length === 3 && types[0].flags & 98304 /* Nullable */ && types[1].flags & 98304 /* Nullable */ ? types[2] : void 0; if (candidate && !(candidate.flags & 98304 /* Nullable */)) { - target2 = getNormalizedType( - candidate, - /*writing*/ - true - ); - if (source2 === target2) - return -1 /* True */; + target2 = getNormalizedType(candidate, /*writing*/ + 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 */); + const isPerformingExcessPropertyChecks = !(intersectionState & 2 /* Target */) && isObjectLiteralType2(source2) && getObjectFlags(source2) & 8192 /* FreshLiteral */; if (isPerformingExcessPropertyChecks) { if (hasExcessProperties(source2, target2, reportErrors2)) { if (reportErrors2) { @@ -63086,6 +58647,7 @@ ${lanes.join("\n")} return 0 /* False */; } } + const isPerformingCommonPropertyChecks = (relation !== comparableRelation || isUnitType(source2)) && !(intersectionState & 2 /* Target */) && source2.flags & (402784252 /* Primitive */ | 524288 /* Object */ | 2097152 /* Intersection */) && source2 !== globalObjectType && target2.flags & (524288 /* Object */ | 2097152 /* Intersection */) && isWeakType(target2) && (getPropertiesOfType(source2).length > 0 || typeHasCallOrConstructSignatures(source2)); const isComparingJsxAttributes = !!(getObjectFlags(source2) & 2048 /* JsxAttributes */); if (isPerformingCommonPropertyChecks && !hasCommonProperties(source2, target2, isComparingJsxAttributes)) { @@ -63094,19 +58656,9 @@ ${lanes.join("\n")} const targetString = typeToString(originalTarget.aliasSymbol ? originalTarget : target2); const calls = getSignaturesOfType(source2, 0 /* Call */); const constructs = getSignaturesOfType(source2, 1 /* Construct */); - if (calls.length > 0 && isRelatedTo( - getReturnTypeOfSignature(calls[0]), - target2, - 1 /* Source */, - /*reportErrors*/ - false - ) || constructs.length > 0 && isRelatedTo( - getReturnTypeOfSignature(constructs[0]), - target2, - 1 /* Source */, - /*reportErrors*/ - false - )) { + if (calls.length > 0 && isRelatedTo(getReturnTypeOfSignature(calls[0]), target2, 1 /* Source */, /*reportErrors*/ + false) || constructs.length > 0 && isRelatedTo(getReturnTypeOfSignature(constructs[0]), target2, 1 /* Source */, /*reportErrors*/ + false)) { reportError(Diagnostics.Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it, sourceString, targetString); } else { reportError(Diagnostics.Type_0_has_no_properties_in_common_with_type_1, sourceString, targetString); @@ -63114,6 +58666,7 @@ ${lanes.join("\n")} } return 0 /* False */; } + traceUnionsOrIntersectionsTooLarge(source2, target2); const skipCaching = source2.flags & 1048576 /* Union */ && source2.types.length < 4 && !(target2.flags & 1048576 /* Union */) || target2.flags & 1048576 /* Union */ && target2.types.length < 4 && !(source2.flags & 469499904 /* StructuredOrInstantiable */); const result2 = skipCaching ? unionOrIntersectionRelatedTo(source2, target2, reportErrors2, intersectionState) : recursiveTypeRelatedTo(source2, target2, reportErrors2, intersectionState, recursionFlags); @@ -63126,6 +58679,7 @@ ${lanes.join("\n")} } return 0 /* False */; } + function reportErrorResults(originalSource, originalTarget, source2, target2, headMessage2) { var _a2, _b; const sourceHasBase = !!getSingleBaseForNonAugmentingSubtype(originalSource); @@ -63138,12 +58692,8 @@ ${lanes.join("\n")} } if (source2.flags & 524288 /* Object */ && target2.flags & 524288 /* Object */) { const currentError = errorInfo; - tryElaborateArrayLikeErrors( - source2, - target2, - /*reportErrors*/ - true - ); + tryElaborateArrayLikeErrors(source2, target2, /*reportErrors*/ + true); if (errorInfo !== currentError) { maybeSuppress = !!errorInfo; } @@ -63208,12 +58758,8 @@ ${lanes.join("\n")} const propType = prop && getTypeOfSymbol(prop) || ((_a2 = getApplicableIndexInfoForName(type, name)) == null ? void 0 : _a2.type) || undefinedType; return append(propTypes, propType); }; - return getUnionType(reduceLeft( - types, - appendPropType, - /*initial*/ - void 0 - ) || emptyArray); + return getUnionType(reduceLeft(types, appendPropType, /*initial*/ + void 0) || emptyArray); } function hasExcessProperties(source2, target2, reportErrors2) { var _a2; @@ -63235,8 +58781,7 @@ ${lanes.join("\n")} 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; @@ -63252,7 +58797,7 @@ ${lanes.join("\n")} } else { const objectLiteralDeclaration = ((_a2 = source2.symbol) == null ? void 0 : _a2.declarations) && firstOrUndefined(source2.symbol.declarations); let suggestion; - if (prop.valueDeclaration && findAncestor(prop.valueDeclaration, (d) => d === objectLiteralDeclaration) && getSourceFileOfNode(objectLiteralDeclaration) === getSourceFileOfNode(errorNode)) { + if (prop.valueDeclaration && findAncestor(prop.valueDeclaration, d => d === objectLiteralDeclaration) && getSourceFileOfNode(objectLiteralDeclaration) === getSourceFileOfNode(errorNode)) { const propDeclaration = prop.valueDeclaration; Debug.assertNode(propDeclaration, isObjectLiteralElementLike); const name = propDeclaration.name; @@ -63290,64 +58835,52 @@ ${lanes.join("\n")} if (sourceOrigin && sourceOrigin.flags & 2097152 /* Intersection */ && target2.aliasSymbol && contains(sourceOrigin.types, target2)) { return -1 /* True */; } + const targetOrigin = target2.origin; if (targetOrigin && targetOrigin.flags & 1048576 /* Union */ && source2.aliasSymbol && contains(targetOrigin.types, source2)) { return -1 /* True */; } } + return relation === comparableRelation ? someTypeRelatedToType(source2, target2, reportErrors2 && !(source2.flags & 402784252 /* Primitive */), intersectionState) : eachTypeRelatedToType(source2, target2, reportErrors2 && !(source2.flags & 402784252 /* Primitive */), intersectionState); } if (target2.flags & 1048576 /* Union */) { return typeRelatedToSomeType(getRegularTypeOfObjectLiteral(source2), target2, reportErrors2 && !(source2.flags & 402784252 /* Primitive */) && !(target2.flags & 402784252 /* Primitive */)); } + if (target2.flags & 2097152 /* Intersection */) { return typeRelatedToEachType(source2, target2, reportErrors2, 2 /* Target */); } + if (relation === comparableRelation && target2.flags & 402784252 /* Primitive */) { - const constraints = sameMap(source2.types, (t) => t.flags & 465829888 /* Instantiable */ ? getBaseConstraintOfType(t) || unknownType : t); + const constraints = sameMap(source2.types, t => t.flags & 465829888 /* Instantiable */ ? getBaseConstraintOfType(t) || unknownType : t); if (constraints !== source2.types) { source2 = getIntersectionType(constraints); if (source2.flags & 131072 /* Never */) { return 0 /* False */; } + if (!(source2.flags & 2097152 /* Intersection */)) { - return isRelatedTo( - source2, - target2, - 1 /* Source */, - /*reportErrors*/ - false - ) || isRelatedTo( - target2, - source2, - 1 /* Source */, - /*reportErrors*/ - false - ); + return isRelatedTo(source2, target2, 1 /* Source */, /*reportErrors*/ + false) || isRelatedTo(target2, source2, 1 /* Source */, /*reportErrors*/ + false); } } } - return someTypeRelatedToType( - source2, - target2, - /*reportErrors*/ - false, - 1 /* Source */ - ); + return someTypeRelatedToType(source2, target2, /*reportErrors*/ + false, 1 /* Source */); } + function eachTypeRelatedToSomeType(source2, target2) { let result2 = -1 /* True */; const sourceTypes = source2.types; for (const sourceType of sourceTypes) { - const related = typeRelatedToSomeType( - sourceType, - target2, - /*reportErrors*/ - false - ); + const related = typeRelatedToSomeType(sourceType, target2, /*reportErrors*/ + false); if (!related) { return 0 /* False */; } + result2 &= related; } return result2; @@ -63358,33 +58891,25 @@ ${lanes.join("\n")} if (containsType(targetTypes, source2)) { return -1 /* True */; } + if (relation !== comparableRelation && getObjectFlags(target2) & 32768 /* PrimitiveUnion */ && !(source2.flags & 1024 /* EnumLiteral */) && (source2.flags & (128 /* StringLiteral */ | 512 /* BooleanLiteral */ | 2048 /* BigIntLiteral */) || (relation === subtypeRelation || relation === strictSubtypeRelation) && source2.flags & 256 /* NumberLiteral */)) { const alternateForm = source2 === source2.regularType ? source2.freshType : source2.regularType; const primitive = source2.flags & 128 /* StringLiteral */ ? stringType : source2.flags & 256 /* NumberLiteral */ ? numberType : source2.flags & 2048 /* BigIntLiteral */ ? bigintType : void 0; return primitive && containsType(targetTypes, primitive) || alternateForm && containsType(targetTypes, alternateForm) ? -1 /* True */ : 0 /* False */; } + const match = getMatchingUnionConstituentForType(target2, source2); if (match) { - const related = isRelatedTo( - source2, - match, - 2 /* Target */, - /*reportErrors*/ - false - ); + const related = isRelatedTo(source2, match, 2 /* Target */, /*reportErrors*/ + false); if (related) { return related; } } } for (const type of targetTypes) { - const related = isRelatedTo( - source2, - type, - 2 /* Target */, - /*reportErrors*/ - false - ); + const related = isRelatedTo(source2, type, 2 /* Target */, /*reportErrors*/ + false); if (related) { return related; } @@ -63392,33 +58917,23 @@ ${lanes.join("\n")} if (reportErrors2) { const bestMatchingType = getBestMatchingType(source2, target2, isRelatedTo); if (bestMatchingType) { - isRelatedTo( - source2, - bestMatchingType, - 2 /* Target */, - /*reportErrors*/ - true - ); + isRelatedTo(source2, bestMatchingType, 2 /* Target */, /*reportErrors*/ + true); } } return 0 /* False */; } + function typeRelatedToEachType(source2, target2, reportErrors2, intersectionState) { let result2 = -1 /* True */; const targetTypes = target2.types; for (const targetType of targetTypes) { - const related = isRelatedTo( - source2, - targetType, - 2 /* Target */, - reportErrors2, - /*headMessage*/ - void 0, - intersectionState - ); + const related = isRelatedTo(source2, targetType, 2 /* Target */, reportErrors2, /*headMessage*/ + void 0, intersectionState); if (!related) { return 0 /* False */; } + result2 &= related; } return result2; @@ -63428,27 +58943,23 @@ ${lanes.join("\n")} if (source2.flags & 1048576 /* Union */ && containsType(sourceTypes, target2)) { return -1 /* True */; } + const len = sourceTypes.length; for (let i = 0; i < len; i++) { - const related = isRelatedTo( - sourceTypes[i], - target2, - 1 /* Source */, - reportErrors2 && i === len - 1, - /*headMessage*/ - void 0, - intersectionState - ); + const related = isRelatedTo(sourceTypes[i], target2, 1 /* Source */, reportErrors2 && i === len - 1, /*headMessage*/ + void 0, intersectionState); if (related) { return related; } } return 0 /* False */; } + function getUndefinedStrippedTargetIfNeeded(source2, target2) { if (source2.flags & 1048576 /* Union */ && target2.flags & 1048576 /* Union */ && !(source2.types[0].flags & 32768 /* Undefined */) && target2.types[0].flags & 32768 /* Undefined */) { return extractTypesOfKind(target2, ~32768 /* Undefined */); } + return target2; } function eachTypeRelatedToType(source2, target2, reportErrors2, intersectionState) { @@ -63458,33 +58969,20 @@ ${lanes.join("\n")} for (let i = 0; i < sourceTypes.length; i++) { const sourceType = sourceTypes[i]; if (undefinedStrippedTarget.flags & 1048576 /* Union */ && sourceTypes.length >= undefinedStrippedTarget.types.length && sourceTypes.length % undefinedStrippedTarget.types.length === 0) { - const related2 = isRelatedTo( - sourceType, - undefinedStrippedTarget.types[i % undefinedStrippedTarget.types.length], - 3 /* Both */, - /*reportErrors*/ - false, - /*headMessage*/ - void 0, - intersectionState - ); + const related2 = isRelatedTo(sourceType, undefinedStrippedTarget.types[i % undefinedStrippedTarget.types.length], 3 /* Both */, /*reportErrors*/ + false, /*headMessage*/ + void 0, intersectionState); if (related2) { result2 &= related2; continue; } } - const related = isRelatedTo( - sourceType, - target2, - 1 /* Source */, - reportErrors2, - /*headMessage*/ - void 0, - intersectionState - ); + const related = isRelatedTo(sourceType, target2, 1 /* Source */, reportErrors2, /*headMessage*/ + void 0, intersectionState); if (!related) { return 0 /* False */; } + result2 &= related; } return result2; @@ -63493,6 +58991,7 @@ ${lanes.join("\n")} if (sources.length !== targets.length && relation === identityRelation) { return 0 /* False */; } + const length2 = sources.length <= targets.length ? sources.length : targets.length; let result2 = -1 /* True */; for (let i = 0; i < length2; i++) { @@ -63503,77 +59002,33 @@ ${lanes.join("\n")} const t = targets[i]; let related = -1 /* True */; if (varianceFlags & 8 /* Unmeasurable */) { - related = relation === identityRelation ? isRelatedTo( - s, - t, - 3 /* Both */, - /*reportErrors*/ - false - ) : compareTypesIdentical(s, t); + related = relation === identityRelation ? isRelatedTo(s, t, 3 /* Both */, /*reportErrors*/ + false) : compareTypesIdentical(s, t); } else if (variance === 1 /* Covariant */) { - related = isRelatedTo( - s, - t, - 3 /* Both */, - reportErrors2, - /*headMessage*/ - void 0, - intersectionState - ); + related = isRelatedTo(s, t, 3 /* Both */, reportErrors2, /*headMessage*/ + void 0, intersectionState); } else if (variance === 2 /* Contravariant */) { - related = isRelatedTo( - t, - s, - 3 /* Both */, - reportErrors2, - /*headMessage*/ - void 0, - intersectionState - ); + related = isRelatedTo(t, s, 3 /* Both */, reportErrors2, /*headMessage*/ + void 0, intersectionState); } else if (variance === 3 /* Bivariant */) { - related = isRelatedTo( - t, - s, - 3 /* Both */, - /*reportErrors*/ - false - ); + related = isRelatedTo(t, s, 3 /* Both */, /*reportErrors*/ + false); if (!related) { - related = isRelatedTo( - s, - t, - 3 /* Both */, - reportErrors2, - /*headMessage*/ - void 0, - intersectionState - ); + related = isRelatedTo(s, t, 3 /* Both */, reportErrors2, /*headMessage*/ + void 0, intersectionState); } } else { - related = isRelatedTo( - s, - t, - 3 /* Both */, - reportErrors2, - /*headMessage*/ - void 0, - intersectionState - ); + related = isRelatedTo(s, t, 3 /* Both */, reportErrors2, /*headMessage*/ + void 0, intersectionState); if (related) { - related &= isRelatedTo( - t, - s, - 3 /* Both */, - reportErrors2, - /*headMessage*/ - void 0, - intersectionState - ); + related &= isRelatedTo(t, s, 3 /* Both */, reportErrors2, /*headMessage*/ + void 0, intersectionState); } } if (!related) { return 0 /* False */; } + result2 &= related; } } @@ -63584,18 +59039,12 @@ ${lanes.join("\n")} if (overflow) { return 0 /* False */; } - const id = getRelationKey( - source2, - target2, - intersectionState, - relation, - /*ignoreConstraints*/ - false - ); + + const id = getRelationKey(source2, target2, intersectionState, relation, /*ignoreConstraints*/ + false); const entry = relation.get(id); if (entry !== void 0) { - if (reportErrors2 && entry & 2 /* Failed */ && !(entry & 4 /* Reported */)) { - } else { + if (reportErrors2 && entry & 2 /* Failed */ && !(entry & 4 /* Reported */)) {} else { if (outofbandVarianceMarkerHandler) { const saved = entry & 24 /* ReportsMask */; if (saved & 8 /* ReportsUnmeasurable */) { @@ -63608,35 +59057,34 @@ ${lanes.join("\n")} return entry & 1 /* Succeeded */ ? -1 /* True */ : 0 /* False */; } } + if (relationCount <= 0) { overflow = true; return 0 /* False */; } + if (!maybeKeys) { maybeKeys = []; - maybeKeysSet = /* @__PURE__ */ new Set(); + maybeKeysSet = /* @__PURE__ */new Set(); sourceStack = []; targetStack = []; } else { if (maybeKeysSet.has(id)) { return 3 /* Maybe */; } - const broadestEquivalentId = id.startsWith("*") ? getRelationKey( - source2, - target2, - intersectionState, - relation, - /*ignoreConstraints*/ - true - ) : void 0; + + const broadestEquivalentId = id.startsWith("*") ? getRelationKey(source2, target2, intersectionState, relation, /*ignoreConstraints*/ + true) : void 0; if (broadestEquivalentId && maybeKeysSet.has(broadestEquivalentId)) { return 3 /* Maybe */; } + if (sourceDepth === 100 || targetDepth === 100) { overflow = true; return 0 /* False */; } } + const maybeStart = maybeCount; maybeKeys[maybeCount] = id; maybeKeysSet.add(id); @@ -63645,20 +59093,20 @@ ${lanes.join("\n")} 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; if (outofbandVarianceMarkerHandler) { originalHandler = outofbandVarianceMarkerHandler; - outofbandVarianceMarkerHandler = (onlyUnreliable) => { + outofbandVarianceMarkerHandler = onlyUnreliable => { propagatingVarianceFlags |= onlyUnreliable ? 16 /* ReportsUnreliable */ : 8 /* ReportsUnmeasurable */; return originalHandler(onlyUnreliable); }; @@ -63667,15 +59115,18 @@ ${lanes.join("\n")} if (expandingFlags === 3 /* Both */) { (_a2 = tracing) == null ? void 0 : _a2.instant(tracing.Phase.CheckTypes, "recursiveTypeRelatedTo_DepthLimit", { sourceId: source2.id, - sourceIdStack: sourceStack.map((t) => t.id), + sourceIdStack: sourceStack.map(t => t.id), targetId: target2.id, - targetIdStack: targetStack.map((t) => t.id), + targetIdStack: targetStack.map(t => t.id), depth: sourceDepth, targetDepth }); result2 = 3 /* Maybe */; } else { - (_b = tracing) == null ? void 0 : _b.push(tracing.Phase.CheckTypes, "structuredTypeRelatedTo", { sourceId: source2.id, targetId: target2.id }); + (_b = tracing) == null ? void 0 : _b.push(tracing.Phase.CheckTypes, "structuredTypeRelatedTo", { + sourceId: source2.id, + targetId: target2.id + }); result2 = structuredTypeRelatedTo(source2, target2, reportErrors2, intersectionState); (_c = tracing) == null ? void 0 : _c.pop(); } @@ -63692,24 +59143,18 @@ ${lanes.join("\n")} if (result2) { if (result2 === -1 /* True */ || sourceDepth === 0 && targetDepth === 0) { if (result2 === -1 /* True */ || result2 === 3 /* Maybe */) { - resetMaybeStack( - /*markAllAsSucceeded*/ - true - ); + resetMaybeStack( /*markAllAsSucceeded*/ + true); } else { - resetMaybeStack( - /*markAllAsSucceeded*/ - false - ); + resetMaybeStack( /*markAllAsSucceeded*/ + false); } } } else { relation.set(id, (reportErrors2 ? 4 /* Reported */ : 0) | 2 /* Failed */ | propagatingVarianceFlags); relationCount--; - resetMaybeStack( - /*markAllAsSucceeded*/ - false - ); + resetMaybeStack( /*markAllAsSucceeded*/ + false); } return result2; function resetMaybeStack(markAllAsSucceeded) { @@ -63729,51 +59174,25 @@ ${lanes.join("\n")} if (relation !== identityRelation) { if (!result2 && (source2.flags & 2097152 /* Intersection */ || source2.flags & 262144 /* TypeParameter */ && target2.flags & 1048576 /* Union */)) { const constraint = getEffectiveConstraintOfIntersection(source2.flags & 2097152 /* Intersection */ ? source2.types : [source2], !!(target2.flags & 1048576 /* Union */)); - if (constraint && everyType(constraint, (c) => c !== source2)) { - result2 = isRelatedTo( - constraint, - target2, - 1 /* Source */, - /*reportErrors*/ - false, - /*headMessage*/ - void 0, - intersectionState - ); + if (constraint && everyType(constraint, c => c !== source2)) { + result2 = isRelatedTo(constraint, target2, 1 /* Source */, /*reportErrors*/ + false, /*headMessage*/ + void 0, intersectionState); } } if (result2 && !(intersectionState & 2 /* Target */) && target2.flags & 2097152 /* Intersection */ && !isGenericObjectType(target2) && source2.flags & (524288 /* Object */ | 2097152 /* Intersection */)) { - result2 &= propertiesRelatedTo( - source2, - target2, - reportErrors2, - /*excludedProperties*/ - void 0, - /*optionalsOnly*/ - false, - 0 /* None */ - ); + result2 &= propertiesRelatedTo(source2, target2, reportErrors2, /*excludedProperties*/ + void 0, /*optionalsOnly*/ + false, 0 /* None */); + if (result2 && isObjectLiteralType2(source2) && getObjectFlags(source2) & 8192 /* FreshLiteral */) { - result2 &= indexSignaturesRelatedTo( - source2, - target2, - /*sourceIsPrimitive*/ - false, - reportErrors2, - 0 /* None */ - ); + result2 &= indexSignaturesRelatedTo(source2, target2, /*sourceIsPrimitive*/ + false, reportErrors2, 0 /* None */); } - } else if (result2 && isNonGenericObjectType(target2) && !isArrayOrTupleType(target2) && source2.flags & 2097152 /* Intersection */ && getApparentType(source2).flags & 3670016 /* StructuredType */ && !some(source2.types, (t) => t === target2 || !!(getObjectFlags(t) & 262144 /* NonInferrableType */))) { - result2 &= propertiesRelatedTo( - source2, - target2, - reportErrors2, - /*excludedProperties*/ - void 0, - /*optionalsOnly*/ - true, - intersectionState - ); + } else if (result2 && isNonGenericObjectType(target2) && !isArrayOrTupleType(target2) && source2.flags & 2097152 /* Intersection */ && getApparentType(source2).flags & 3670016 /* StructuredType */ && !some(source2.types, t => t === target2 || !!(getObjectFlags(t) & 262144 /* NonInferrableType */))) { + result2 &= propertiesRelatedTo(source2, target2, reportErrors2, /*excludedProperties*/ + void 0, /*optionalsOnly*/ + true, intersectionState); } } if (result2) { @@ -63796,63 +59215,28 @@ ${lanes.join("\n")} return result3; } if (sourceFlags & 4194304 /* Index */) { - return isRelatedTo( - source2.type, - target2.type, - 3 /* Both */, - /*reportErrors*/ - false - ); + return isRelatedTo(source2.type, target2.type, 3 /* Both */, /*reportErrors*/ + false); } if (sourceFlags & 8388608 /* IndexedAccess */) { - if (result2 = isRelatedTo( - source2.objectType, - target2.objectType, - 3 /* Both */, - /*reportErrors*/ - false - )) { - if (result2 &= isRelatedTo( - source2.indexType, - target2.indexType, - 3 /* Both */, - /*reportErrors*/ - false - )) { + if (result2 = isRelatedTo(source2.objectType, target2.objectType, 3 /* Both */, /*reportErrors*/ + false)) { + if (result2 &= isRelatedTo(source2.indexType, target2.indexType, 3 /* Both */, /*reportErrors*/ + false)) { return result2; } } } if (sourceFlags & 16777216 /* Conditional */) { if (source2.root.isDistributive === target2.root.isDistributive) { - if (result2 = isRelatedTo( - source2.checkType, - target2.checkType, - 3 /* Both */, - /*reportErrors*/ - false - )) { - if (result2 &= isRelatedTo( - source2.extendsType, - target2.extendsType, - 3 /* Both */, - /*reportErrors*/ - false - )) { - if (result2 &= isRelatedTo( - getTrueTypeFromConditionalType(source2), - getTrueTypeFromConditionalType(target2), - 3 /* Both */, - /*reportErrors*/ - false - )) { - if (result2 &= isRelatedTo( - getFalseTypeFromConditionalType(source2), - getFalseTypeFromConditionalType(target2), - 3 /* Both */, - /*reportErrors*/ - false - )) { + if (result2 = isRelatedTo(source2.checkType, target2.checkType, 3 /* Both */, /*reportErrors*/ + false)) { + if (result2 &= isRelatedTo(source2.extendsType, target2.extendsType, 3 /* Both */, /*reportErrors*/ + false)) { + if (result2 &= isRelatedTo(getTrueTypeFromConditionalType(source2), getTrueTypeFromConditionalType(target2), 3 /* Both */, /*reportErrors*/ + false)) { + if (result2 &= isRelatedTo(getFalseTypeFromConditionalType(source2), getFalseTypeFromConditionalType(target2), 3 /* Both */, /*reportErrors*/ + false)) { return result2; } } @@ -63861,20 +59245,10 @@ ${lanes.join("\n")} } } if (sourceFlags & 33554432 /* Substitution */) { - if (result2 = isRelatedTo( - source2.baseType, - target2.baseType, - 3 /* Both */, - /*reportErrors*/ - false - )) { - if (result2 &= isRelatedTo( - source2.constraint, - target2.constraint, - 3 /* Both */, - /*reportErrors*/ - false - )) { + if (result2 = isRelatedTo(source2.baseType, target2.baseType, 3 /* Both */, /*reportErrors*/ + false)) { + if (result2 &= isRelatedTo(source2.constraint, target2.constraint, 3 /* Both */, /*reportErrors*/ + false)) { return result2; } } @@ -63890,11 +59264,13 @@ ${lanes.join("\n")} return 0 /* False */; } } + if (sourceFlags & (524288 /* Object */ | 16777216 /* Conditional */) && source2.aliasSymbol && source2.aliasTypeArguments && source2.aliasSymbol === target2.aliasSymbol && !(isMarkerType(source2) || isMarkerType(target2))) { const variances = getAliasVariances(source2.aliasSymbol); if (variances === emptyArray) { return 1 /* Unknown */; } + const params = getSymbolLinks(source2.aliasSymbol).typeParameters; const minParams = getMinTypeArgumentCount(params); const sourceTypes = fillMissingTypeArguments(source2.aliasTypeArguments, params, minParams, isInJSFile(source2.aliasSymbol.valueDeclaration)); @@ -63920,14 +59296,9 @@ ${lanes.join("\n")} if (relation === comparableRelation && sourceFlags & 262144 /* TypeParameter */) { let constraint = getConstraintOfTypeParameter(source2); if (constraint && hasNonCircularBaseConstraint(source2)) { - while (constraint && someType(constraint, (c) => !!(c.flags & 262144 /* TypeParameter */))) { - if (result2 = isRelatedTo( - constraint, - target2, - 1 /* Source */, - /*reportErrors*/ - false - )) { + while (constraint && someType(constraint, c => !!(c.flags & 262144 /* TypeParameter */))) { + if (result2 = isRelatedTo(constraint, target2, 1 /* Source */, /*reportErrors*/ + false)) { return result2; } constraint = getConstraintOfTypeParameter(constraint); @@ -63938,13 +59309,8 @@ ${lanes.join("\n")} } else if (targetFlags & 4194304 /* Index */) { const targetType = target2.type; if (sourceFlags & 4194304 /* Index */) { - if (result2 = isRelatedTo( - targetType, - source2.type, - 3 /* Both */, - /*reportErrors*/ - false - )) { + if (result2 = isRelatedTo(targetType, source2.type, 3 /* Both */, /*reportErrors*/ + false)) { return result2; } } @@ -63965,13 +59331,8 @@ ${lanes.join("\n")} if (nameType && isMappedTypeWithKeyofConstraintDeclaration(targetType)) { const modifiersType = getApparentType(getModifiersTypeFromMappedType(targetType)); const mappedKeys = []; - forEachMappedTypePropertyKeyTypeAndIndexSignatureKeyType( - modifiersType, - 8576 /* StringOrNumberLiteralOrUnique */, - /*stringsOnly*/ - false, - (t) => void mappedKeys.push(instantiateType(nameType, appendTypeMapping(targetType.mapper, getTypeParameterFromMappedType(targetType), t))) - ); + forEachMappedTypePropertyKeyTypeAndIndexSignatureKeyType(modifiersType, 8576 /* StringOrNumberLiteralOrUnique */, /*stringsOnly*/ + false, t => void mappedKeys.push(instantiateType(nameType, appendTypeMapping(targetType.mapper, getTypeParameterFromMappedType(targetType), t)))); targetKeys = getUnionType([...mappedKeys, nameType]); } else { targetKeys = nameType || constraintType; @@ -64005,15 +59366,8 @@ ${lanes.join("\n")} if (reportErrors2 && originalErrorInfo) { resetErrorInfo(saveErrorInfo); } - if (result2 = isRelatedTo( - source2, - constraint, - 2 /* Target */, - reportErrors2, - /*headMessage*/ - void 0, - intersectionState - )) { + if (result2 = isRelatedTo(source2, constraint, 2 /* Target */, reportErrors2, /*headMessage*/ + void 0, intersectionState)) { return result2; } if (reportErrors2 && originalErrorInfo && errorInfo) { @@ -64033,6 +59387,7 @@ ${lanes.join("\n")} if (!keysRemapped && templateType.flags & 8388608 /* IndexedAccess */ && templateType.objectType === source2 && templateType.indexType === getTypeParameterFromMappedType(target2)) { return -1 /* True */; } + if (!isGenericMappedType(source2)) { const targetKeys = keysRemapped ? getNameTypeFromMappedType(target2) : getConstraintTypeFromMappedType(target2); const sourceKeys = getIndexType(source2, 2 /* NoIndexSignatures */); @@ -64062,30 +59417,17 @@ ${lanes.join("\n")} if (isDeeplyNestedType(target2, targetStack, targetDepth, 10)) { return 3 /* Maybe */; } + const c = target2; if (!c.root.inferTypeParameters && !isDistributionDependent(c.root) && !(source2.flags & 16777216 /* Conditional */ && source2.root === c.root)) { const skipTrue = !isTypeAssignableTo(getPermissiveInstantiation(c.checkType), getPermissiveInstantiation(c.extendsType)); const skipFalse = !skipTrue && isTypeAssignableTo(getRestrictiveInstantiation(c.checkType), getRestrictiveInstantiation(c.extendsType)); - if (result2 = skipTrue ? -1 /* True */ : isRelatedTo( - source2, - getTrueTypeFromConditionalType(c), - 2 /* Target */, - /*reportErrors*/ - false, - /*headMessage*/ - void 0, - intersectionState - )) { - result2 &= skipFalse ? -1 /* True */ : isRelatedTo( - source2, - getFalseTypeFromConditionalType(c), - 2 /* Target */, - /*reportErrors*/ - false, - /*headMessage*/ - void 0, - intersectionState - ); + if (result2 = skipTrue ? -1 /* True */ : isRelatedTo(source2, getTrueTypeFromConditionalType(c), 2 /* Target */, /*reportErrors*/ + false, /*headMessage*/ + void 0, intersectionState)) { + result2 &= skipFalse ? -1 /* True */ : isRelatedTo(source2, getFalseTypeFromConditionalType(c), 2 /* Target */, /*reportErrors*/ + false, /*headMessage*/ + void 0, intersectionState); if (result2) { return result2; } @@ -64096,6 +59438,7 @@ ${lanes.join("\n")} if (relation === comparableRelation) { return templateLiteralTypesDefinitelyUnrelated(source2, target2) ? 0 /* False */ : -1 /* True */; } + instantiateType(source2, reportUnreliableMapper); } if (isTypeMatchedByTemplateLiteralType(source2, target2)) { @@ -64108,29 +59451,16 @@ ${lanes.join("\n")} } } } + if (sourceFlags & 8650752 /* TypeVariable */) { if (!(sourceFlags & 8388608 /* IndexedAccess */ && targetFlags & 8388608 /* IndexedAccess */)) { const constraint = getConstraintOfType(source2) || unknownType; - if (result2 = isRelatedTo( - constraint, - target2, - 1 /* Source */, - /*reportErrors*/ - false, - /*headMessage*/ - void 0, - intersectionState - )) { + if (result2 = isRelatedTo(constraint, target2, 1 /* Source */, /*reportErrors*/ + false, /*headMessage*/ + void 0, intersectionState)) { return result2; - } else if (result2 = isRelatedTo( - getTypeWithThisArgument(constraint, source2), - target2, - 1 /* Source */, - reportErrors2 && constraint !== unknownType && !(targetFlags & sourceFlags & 262144 /* TypeParameter */), - /*headMessage*/ - void 0, - intersectionState - )) { + } else if (result2 = isRelatedTo(getTypeWithThisArgument(constraint, source2), target2, 1 /* Source */, reportErrors2 && constraint !== unknownType && !(targetFlags & sourceFlags & 262144 /* TypeParameter */), /*headMessage*/ + void 0, intersectionState)) { return result2; } if (isMappedTypeGenericIndexedAccess(source2)) { @@ -64158,6 +59488,7 @@ ${lanes.join("\n")} if (source2.symbol !== target2.symbol) { return 0 /* False */; } + if (result2 = isRelatedTo(source2.type, target2.type, 3 /* Both */, reportErrors2)) { return result2; } @@ -64171,18 +59502,14 @@ ${lanes.join("\n")} if (isDeeplyNestedType(source2, sourceStack, sourceDepth, 10)) { return 3 /* Maybe */; } + if (targetFlags & 16777216 /* Conditional */) { const sourceParams = source2.root.inferTypeParameters; let sourceExtends = source2.extendsType; let mapper; if (sourceParams) { - const ctx = createInferenceContext( - sourceParams, - /*signature*/ - void 0, - 0 /* None */, - isRelatedToWorker - ); + const ctx = createInferenceContext(sourceParams, /*signature*/ + void 0, 0 /* None */, isRelatedToWorker); inferTypes(ctx.inferences, target2.extendsType, sourceExtends, 512 /* NoConstraints */ | 1024 /* AlwaysStrict */); sourceExtends = instantiateType(sourceExtends, ctx.mapper); mapper = ctx.mapper; @@ -64213,6 +59540,7 @@ ${lanes.join("\n")} if (relation !== subtypeRelation && relation !== strictSubtypeRelation && isPartialMappedType(target2) && isEmptyObjectType(source2)) { return -1 /* True */; } + if (isGenericMappedType(target2)) { if (isGenericMappedType(source2)) { if (result2 = mappedTypeRelatedTo(source2, target2, reportErrors2)) { @@ -64221,6 +59549,7 @@ ${lanes.join("\n")} } return 0 /* False */; } + const sourceIsPrimitive = !!(sourceFlags & 402784252 /* Primitive */); if (relation !== identityRelation) { source2 = getApparentType(source2); @@ -64228,19 +59557,22 @@ ${lanes.join("\n")} } else if (isGenericMappedType(source2)) { return 0 /* False */; } + if (getObjectFlags(source2) & 4 /* Reference */ && getObjectFlags(target2) & 4 /* Reference */ && source2.target === target2.target && !isTupleType(source2) && !(isMarkerType(source2) || isMarkerType(target2))) { if (isEmptyArrayLiteralType(source2)) { return -1 /* True */; } + const variances = getVariances(source2.target); if (variances === emptyArray) { return 1 /* Unknown */; } + const varianceResult = relateVariances(getTypeArguments(source2), getTypeArguments(target2), variances, intersectionState); if (varianceResult !== void 0) { return varianceResult; } - } else if (isReadonlyArrayType(target2) ? everyType(source2, isArrayOrTupleType) : isArrayType(target2) && everyType(source2, (t) => isTupleType(t) && !t.target.readonly)) { + } else if (isReadonlyArrayType(target2) ? everyType(source2, isArrayOrTupleType) : isArrayType(target2) && everyType(source2, t => isTupleType(t) && !t.target.readonly)) { if (relation !== identityRelation) { return isRelatedTo(getIndexTypeOfType(source2, numberType) || anyType, getIndexTypeOfType(target2, numberType) || anyType, 3 /* Both */, reportErrors2); } else { @@ -64254,18 +59586,12 @@ ${lanes.join("\n")} } else if ((relation === subtypeRelation || relation === strictSubtypeRelation) && isEmptyObjectType(target2) && getObjectFlags(target2) & 8192 /* FreshLiteral */ && !isEmptyObjectType(source2)) { return 0 /* False */; } + if (sourceFlags & (524288 /* Object */ | 2097152 /* Intersection */) && targetFlags & 524288 /* Object */) { const reportStructuralErrors = reportErrors2 && errorInfo === saveErrorInfo.errorInfo && !sourceIsPrimitive; - result2 = propertiesRelatedTo( - source2, - target2, - reportStructuralErrors, - /*excludedProperties*/ - void 0, - /*optionalsOnly*/ - false, - intersectionState - ); + result2 = propertiesRelatedTo(source2, target2, reportStructuralErrors, /*excludedProperties*/ + void 0, /*optionalsOnly*/ + false, intersectionState); if (result2) { result2 &= signaturesRelatedTo(source2, target2, 0 /* Call */, reportStructuralErrors, intersectionState); if (result2) { @@ -64293,15 +59619,14 @@ ${lanes.join("\n")} } 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) { if (result2 = typeArgumentsRelatedTo(sourceTypeArguments, targetTypeArguments, variances, reportErrors2, intersectionState2)) { return result2; } - if (some(variances, (v) => !!(v & 24 /* AllowsStructuralFallback */))) { + if (some(variances, v => !!(v & 24 /* AllowsStructuralFallback */))) { originalErrorInfo = void 0; resetErrorInfo(saveErrorInfo); return void 0; @@ -64309,9 +59634,10 @@ ${lanes.join("\n")} const allowStructuralFallback = targetTypeArguments && hasCovariantVoidArgument(targetTypeArguments, variances); varianceCheckFailed = !allowStructuralFallback; if (variances !== emptyArray && !allowStructuralFallback) { - if (varianceCheckFailed && !(reportErrors2 && some(variances, (v) => (v & 7 /* VarianceMask */) === 0 /* Invariant */))) { + if (varianceCheckFailed && !(reportErrors2 && some(variances, v => (v & 7 /* VarianceMask */) === 0 /* Invariant */))) { return 0 /* False */; } + originalErrorInfo = errorInfo; resetErrorInfo(saveErrorInfo); } @@ -64332,22 +59658,27 @@ ${lanes.join("\n")} } return 0 /* False */; } + function typeRelatedToDiscriminatedType(source2, target2) { 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)); if (numCombinations > 25) { - (_a2 = tracing) == null ? void 0 : _a2.instant(tracing.Phase.CheckTypes, "typeRelatedToDiscriminatedType_DepthLimit", { sourceId: source2.id, targetId: target2.id, numCombinations }); + (_a2 = tracing) == null ? void 0 : _a2.instant(tracing.Phase.CheckTypes, "typeRelatedToDiscriminatedType_DepthLimit", { + sourceId: source2.id, + targetId: target2.id, + numCombinations + }); return 0 /* False */; } } + const sourceDiscriminantTypes = new Array(sourcePropertiesFiltered.length); - const excludedProperties = /* @__PURE__ */ new Set(); + const excludedProperties = /* @__PURE__ */new Set(); for (let i = 0; i < sourcePropertiesFiltered.length; i++) { const sourceProperty = sourcePropertiesFiltered[i]; const sourcePropertyType = getNonMissingTypeOfSymbol(sourceProperty); @@ -64358,81 +59689,49 @@ ${lanes.join("\n")} const matchingTypes = []; for (const combination of discriminantCombinations) { let hasMatch = false; - outer: - for (const type of target2.types) { - 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; - const related = propertyRelatedTo( - source2, - target2, - sourceProperty, - targetProperty, - (_) => combination[i], - /*reportErrors*/ - false, - 0 /* None */, - /*skipOptional*/ - strictNullChecks || relation === comparableRelation - ); - if (!related) { - continue outer; - } + outer: for (const type of target2.types) { + 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; + const related = propertyRelatedTo(source2, target2, sourceProperty, targetProperty, _ => combination[i], /*reportErrors*/ + false, 0 /* None */, /*skipOptional*/ + strictNullChecks || relation === comparableRelation); + if (!related) { + continue outer; } - pushIfUnique(matchingTypes, type, equateValues); - hasMatch = true; } + pushIfUnique(matchingTypes, type, equateValues); + hasMatch = true; + } if (!hasMatch) { return 0 /* False */; } } + let result2 = -1 /* True */; for (const type of matchingTypes) { - result2 &= propertiesRelatedTo( - source2, - type, - /*reportErrors*/ - false, - excludedProperties, - /*optionalsOnly*/ - false, - 0 /* None */ - ); + result2 &= propertiesRelatedTo(source2, type, /*reportErrors*/ + false, excludedProperties, /*optionalsOnly*/ + false, 0 /* None */); + if (result2) { - result2 &= signaturesRelatedTo( - source2, - type, - 0 /* Call */, - /*reportErrors*/ - false, - 0 /* None */ - ); + result2 &= signaturesRelatedTo(source2, type, 0 /* Call */, /*reportErrors*/ + false, 0 /* None */); + if (result2) { - result2 &= signaturesRelatedTo( - source2, - type, - 1 /* Construct */, - /*reportErrors*/ - false, - 0 /* None */ - ); + result2 &= signaturesRelatedTo(source2, type, 1 /* Construct */, /*reportErrors*/ + false, 0 /* None */); + if (result2 && !(isTupleType(source2) && isTupleType(type))) { - result2 &= indexSignaturesRelatedTo( - source2, - type, - /*sourceIsPrimitive*/ - false, - /*reportErrors*/ - false, - 0 /* None */ - ); + result2 &= indexSignaturesRelatedTo(source2, type, /*sourceIsPrimitive*/ + false, /*reportErrors*/ + false, 0 /* None */); } } } + if (!result2) { return result2; } @@ -64440,8 +59739,7 @@ ${lanes.join("\n")} 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)) { @@ -64456,22 +59754,11 @@ ${lanes.join("\n")} } function isPropertySymbolTypeRelated(sourceProp, targetProp, getTypeOfSourceProperty, reportErrors2, intersectionState) { const targetIsOptional = strictNullChecks && !!(getCheckFlags(targetProp) & 48 /* Partial */); - const effectiveTarget = addOptionality( - getNonMissingTypeOfSymbol(targetProp), - /*isProperty*/ - false, - targetIsOptional - ); + const effectiveTarget = addOptionality(getNonMissingTypeOfSymbol(targetProp), /*isProperty*/ + false, targetIsOptional); const effectiveSource = getTypeOfSourceProperty(sourceProp); - return isRelatedTo( - effectiveSource, - effectiveTarget, - 3 /* Both */, - reportErrors2, - /*headMessage*/ - void 0, - intersectionState - ); + return isRelatedTo(effectiveSource, effectiveTarget, 3 /* Both */, reportErrors2, /*headMessage*/ + void 0, intersectionState); } function propertyRelatedTo(source2, target2, sourceProp, targetProp, getTypeOfSourceProperty, reportErrors2, intersectionState, skipOptional) { const sourcePropFlags = getDeclarationModifierFlagsFromSymbol(sourceProp); @@ -64500,9 +59787,11 @@ ${lanes.join("\n")} } return 0 /* False */; } + if (relation === strictSubtypeRelation && isReadonlySymbol(sourceProp) && !isReadonlySymbol(targetProp)) { return 0 /* False */; } + const related = isPropertySymbolTypeRelated(sourceProp, targetProp, getTypeOfSourceProperty, reportErrors2, intersectionState); if (!related) { if (reportErrors2) { @@ -64510,12 +59799,14 @@ ${lanes.join("\n")} } return 0 /* False */; } + if (!skipOptional && sourceProp.flags & 16777216 /* Optional */ && targetProp.flags & 106500 /* ClassMember */ && !(targetProp.flags & 16777216 /* Optional */)) { if (reportErrors2) { reportError(Diagnostics.Property_0_is_optional_in_type_1_but_required_in_type_2, symbolToString(targetProp), typeToString(source2), typeToString(target2)); } return 0 /* False */; } + return related; } function reportUnmatchedProperty(source2, target2, unmatchedProperty, requireOptionalProperties) { @@ -64526,33 +59817,19 @@ ${lanes.join("\n")} if (symbolTableKey && getPropertyOfType(source2, symbolTableKey)) { const sourceName = factory.getDeclarationName(source2.symbol.valueDeclaration); const targetName = factory.getDeclarationName(target2.symbol.valueDeclaration); - reportError( - Diagnostics.Property_0_in_type_1_refers_to_a_different_member_that_cannot_be_accessed_from_within_type_2, - diagnosticName(privateIdentifierDescription), - diagnosticName(sourceName.escapedText === "" ? anon : sourceName), - diagnosticName(targetName.escapedText === "" ? anon : targetName) - ); + reportError(Diagnostics.Property_0_in_type_1_refers_to_a_different_member_that_cannot_be_accessed_from_within_type_2, diagnosticName(privateIdentifierDescription), diagnosticName(sourceName.escapedText === "" ? anon : sourceName), diagnosticName(targetName.escapedText === "" ? anon : targetName)); return; } } - const props = arrayFrom(getUnmatchedProperties( - source2, - target2, - requireOptionalProperties, - /*matchDiscriminantProperties*/ - false - )); + const props = arrayFrom(getUnmatchedProperties(source2, target2, requireOptionalProperties, /*matchDiscriminantProperties*/ + false)); if (!headMessage || headMessage.code !== Diagnostics.Class_0_incorrectly_implements_interface_1.code && headMessage.code !== Diagnostics.Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclass.code) { shouldSkipElaboration = true; } if (props.length === 1) { - const propName = symbolToString( - unmatchedProperty, - /*enclosingDeclaration*/ - void 0, - 0 /* None */, - 4 /* AllowAnyNodeKind */ | 16 /* WriteComputedProps */ - ); + const propName = symbolToString(unmatchedProperty, /*enclosingDeclaration*/ + void 0, 0 /* None */, 4 /* AllowAnyNodeKind */ | 16 /* WriteComputedProps */); + reportError(Diagnostics.Property_0_is_missing_in_type_1_but_required_in_type_2, propName, ...getTypeNamesForErrorDisplay(source2, target2)); if (length(unmatchedProperty.declarations)) { associateRelatedInfo(createDiagnosticForNode(unmatchedProperty.declarations[0], Diagnostics._0_is_declared_here, propName)); @@ -64560,16 +59837,12 @@ ${lanes.join("\n")} if (shouldSkipElaboration && errorInfo) { overrideNextErrorInfo++; } - } else if (tryElaborateArrayLikeErrors( - source2, - target2, - /*reportErrors*/ - false - )) { + } else if (tryElaborateArrayLikeErrors(source2, target2, /*reportErrors*/ + false)) { if (props.length > 5) { - reportError(Diagnostics.Type_0_is_missing_the_following_properties_from_type_1_Colon_2_and_3_more, typeToString(source2), typeToString(target2), map(props.slice(0, 4), (p) => symbolToString(p)).join(", "), props.length - 4); + reportError(Diagnostics.Type_0_is_missing_the_following_properties_from_type_1_Colon_2_and_3_more, typeToString(source2), typeToString(target2), map(props.slice(0, 4), p => symbolToString(p)).join(", "), props.length - 4); } else { - reportError(Diagnostics.Type_0_is_missing_the_following_properties_from_type_1_Colon_2, typeToString(source2), typeToString(target2), map(props, (p) => symbolToString(p)).join(", ")); + reportError(Diagnostics.Type_0_is_missing_the_following_properties_from_type_1_Colon_2, typeToString(source2), typeToString(target2), map(props, p => symbolToString(p)).join(", ")); } if (shouldSkipElaboration && errorInfo) { overrideNextErrorInfo++; @@ -64586,6 +59859,7 @@ ${lanes.join("\n")} if (!target2.target.readonly && (isReadonlyArrayType(source2) || isTupleType(source2) && source2.target.readonly)) { return 0 /* False */; } + const sourceArity = getTypeReferenceArity(source2); const targetArity = getTypeReferenceArity(target2); const sourceRestFlag = isTupleType(source2) ? source2.target.combinedFlags & 4 /* Rest */ : 4 /* Rest */; @@ -64598,12 +59872,14 @@ ${lanes.join("\n")} } return 0 /* False */; } + if (!targetRestFlag && targetArity < sourceMinLength) { if (reportErrors2) { reportError(Diagnostics.Source_has_0_element_s_but_target_allows_only_1, sourceMinLength, targetArity); } return 0 /* False */; } + if (!targetRestFlag && (sourceRestFlag || targetArity < sourceArity)) { if (reportErrors2) { if (sourceMinLength < targetMinLength) { @@ -64614,6 +59890,7 @@ ${lanes.join("\n")} } return 0 /* False */; } + const sourceTypeArguments = getTypeArguments(source2); const targetTypeArguments = getTypeArguments(target2); const targetStartCount = getStartElementCount(target2.target, 11 /* NonRest */); @@ -64631,18 +59908,21 @@ ${lanes.join("\n")} } return 0 /* False */; } + if (sourceFlags & 8 /* Variadic */ && !(targetFlags & 12 /* Variable */)) { if (reportErrors2) { reportError(Diagnostics.Variadic_element_at_position_0_in_source_does_not_match_element_at_position_1_in_target, sourcePosition, targetPosition); } return 0 /* False */; } + if (targetFlags & 1 /* Required */ && !(sourceFlags & 1 /* Required */)) { if (reportErrors2) { reportError(Diagnostics.Source_provides_no_match_for_required_element_at_position_0_in_target, targetPosition); } return 0 /* False */; } + if (canExcludeDiscriminants) { if (sourceFlags & 12 /* Variable */ || targetFlags & 12 /* Variable */) { canExcludeDiscriminants = false; @@ -64654,15 +59934,8 @@ ${lanes.join("\n")} const sourceType = removeMissingType(sourceTypeArguments[sourcePosition], !!(sourceFlags & targetFlags & 2 /* Optional */)); const targetType = targetTypeArguments[targetPosition]; const targetCheckType = sourceFlags & 8 /* Variadic */ && targetFlags & 4 /* Rest */ ? createArrayType(targetType) : removeMissingType(targetType, !!(targetFlags & 2 /* Optional */)); - const related = isRelatedTo( - sourceType, - targetCheckType, - 3 /* Both */, - reportErrors2, - /*headMessage*/ - void 0, - intersectionState - ); + const related = isRelatedTo(sourceType, targetCheckType, 3 /* Both */, reportErrors2, /*headMessage*/ + void 0, intersectionState); if (!related) { if (reportErrors2 && (targetArity > 1 || sourceArity > 1)) { if (targetHasRestElement && sourcePosition >= targetStartCount && sourcePositionFromEnd >= targetEndCount && targetStartCount !== sourceArity - targetEndCount - 1) { @@ -64673,6 +59946,7 @@ ${lanes.join("\n")} } return 0 /* False */; } + result2 &= related; } return result2; @@ -64681,20 +59955,17 @@ ${lanes.join("\n")} return 0 /* False */; } } + const requireOptionalProperties = (relation === subtypeRelation || relation === strictSubtypeRelation) && !isObjectLiteralType2(source2) && !isEmptyArrayLiteralType(source2) && !isTupleType(source2); - const unmatchedProperty = getUnmatchedProperty( - source2, - target2, - requireOptionalProperties, - /*matchDiscriminantProperties*/ - false - ); + const unmatchedProperty = getUnmatchedProperty(source2, target2, requireOptionalProperties, /*matchDiscriminantProperties*/ + false); if (unmatchedProperty) { if (reportErrors2 && shouldReportUnmatchedPropertyError(source2, target2)) { reportUnmatchedProperty(source2, target2, unmatchedProperty, requireOptionalProperties); } return 0 /* False */; } + if (isObjectLiteralType2(target2)) { for (const sourceProp of excludeProperties(getPropertiesOfType(source2), excludedProperties)) { if (!getPropertyOfObjectType(target2, sourceProp.escapedName)) { @@ -64708,6 +59979,7 @@ ${lanes.join("\n")} } } } + const properties = getPropertiesOfType(target2); const numericNamesOnly = isTupleType(source2) && isTupleType(target2); for (const targetProp of excludeProperties(properties, excludedProperties)) { @@ -64719,6 +59991,7 @@ ${lanes.join("\n")} if (!related) { return 0 /* False */; } + result2 &= related; } } @@ -64729,21 +60002,25 @@ ${lanes.join("\n")} if (!(source2.flags & 524288 /* Object */ && target2.flags & 524288 /* Object */)) { return 0 /* False */; } + const sourceProperties = excludeProperties(getPropertiesOfObjectType(source2), excludedProperties); const targetProperties = excludeProperties(getPropertiesOfObjectType(target2), excludedProperties); if (sourceProperties.length !== targetProperties.length) { return 0 /* False */; } + let result2 = -1 /* True */; for (const sourceProp of sourceProperties) { const targetProp = getPropertyOfObjectType(target2, sourceProp.escapedName); if (!targetProp) { return 0 /* False */; } + const related = compareProperties2(sourceProp, targetProp, isRelatedTo); if (!related) { return 0 /* False */; } + result2 &= related; } return result2; @@ -64756,16 +60033,11 @@ ${lanes.join("\n")} if (target2 === anyFunctionType || source2 === anyFunctionType) { return -1 /* True */; } + const sourceIsJSConstructor = source2.symbol && isJSConstructor(source2.symbol.valueDeclaration); const targetIsJSConstructor = target2.symbol && isJSConstructor(target2.symbol.valueDeclaration); - const sourceSignatures = getSignaturesOfType( - source2, - sourceIsJSConstructor && kind === 1 /* Construct */ ? 0 /* Call */ : kind - ); - const targetSignatures = getSignaturesOfType( - target2, - targetIsJSConstructor && kind === 1 /* Construct */ ? 0 /* Call */ : kind - ); + const sourceSignatures = getSignaturesOfType(source2, sourceIsJSConstructor && kind === 1 /* Construct */ ? 0 /* Call */ : kind); + const targetSignatures = getSignaturesOfType(target2, targetIsJSConstructor && kind === 1 /* Construct */ ? 0 /* Call */ : kind); if (kind === 1 /* Construct */ && sourceSignatures.length && targetSignatures.length) { const sourceIsAbstract = !!(sourceSignatures[0].flags & 4 /* Abstract */); const targetIsAbstract = !!(targetSignatures[0].flags & 4 /* Abstract */); @@ -64775,28 +60047,24 @@ ${lanes.join("\n")} } return 0 /* False */; } + if (!constructorVisibilitiesAreCompatible(sourceSignatures[0], targetSignatures[0], reportErrors2)) { return 0 /* False */; } } + let result2 = -1 /* True */; const incompatibleReporter = kind === 1 /* Construct */ ? reportIncompatibleConstructSignatureReturn : reportIncompatibleCallSignatureReturn; const sourceObjectFlags = getObjectFlags(source2); const targetObjectFlags = getObjectFlags(target2); if (sourceObjectFlags & 64 /* Instantiated */ && targetObjectFlags & 64 /* Instantiated */ && source2.symbol === target2.symbol || sourceObjectFlags & 4 /* Reference */ && targetObjectFlags & 4 /* Reference */ && source2.target === target2.target) { for (let i = 0; i < targetSignatures.length; i++) { - const related = signatureRelatedTo( - sourceSignatures[i], - targetSignatures[i], - /*erase*/ - true, - reportErrors2, - intersectionState, - incompatibleReporter(sourceSignatures[i], targetSignatures[i]) - ); + const related = signatureRelatedTo(sourceSignatures[i], targetSignatures[i], /*erase*/ + true, reportErrors2, intersectionState, incompatibleReporter(sourceSignatures[i], targetSignatures[i])); if (!related) { return 0 /* False */; } + result2 &= related; } } else if (sourceSignatures.length === 1 && targetSignatures.length === 1) { @@ -64805,52 +60073,35 @@ ${lanes.join("\n")} const targetSignature = first(targetSignatures); result2 = signatureRelatedTo(sourceSignature, targetSignature, eraseGenerics, reportErrors2, intersectionState, incompatibleReporter(sourceSignature, targetSignature)); if (!result2 && reportErrors2 && kind === 1 /* Construct */ && sourceObjectFlags & targetObjectFlags && (((_a2 = targetSignature.declaration) == null ? void 0 : _a2.kind) === 176 /* Constructor */ || ((_b = sourceSignature.declaration) == null ? void 0 : _b.kind) === 176 /* Constructor */)) { - const constructSignatureToString = (signature) => signatureToString( - signature, - /*enclosingDeclaration*/ - void 0, - 262144 /* WriteArrowStyleSignature */, - kind - ); + const constructSignatureToString = signature => signatureToString(signature, /*enclosingDeclaration*/ + void 0, 262144 /* WriteArrowStyleSignature */, kind); reportError(Diagnostics.Type_0_is_not_assignable_to_type_1, constructSignatureToString(sourceSignature), constructSignatureToString(targetSignature)); reportError(Diagnostics.Types_of_construct_signatures_are_incompatible); return result2; } } else { - outer: - for (const t of targetSignatures) { - const saveErrorInfo = captureErrorCalculationState(); - let shouldElaborateErrors = reportErrors2; - for (const s of sourceSignatures) { - const related = signatureRelatedTo( - s, - t, - /*erase*/ - true, - shouldElaborateErrors, - intersectionState, - incompatibleReporter(s, t) - ); - if (related) { - result2 &= related; - resetErrorInfo(saveErrorInfo); - continue outer; - } - shouldElaborateErrors = false; + outer: for (const t of targetSignatures) { + const saveErrorInfo = captureErrorCalculationState(); + let shouldElaborateErrors = reportErrors2; + for (const s of sourceSignatures) { + const related = signatureRelatedTo(s, t, /*erase*/ + true, shouldElaborateErrors, intersectionState, incompatibleReporter(s, t)); + if (related) { + result2 &= related; + resetErrorInfo(saveErrorInfo); + continue outer; } - if (shouldElaborateErrors) { - reportError(Diagnostics.Type_0_provides_no_match_for_the_signature_1, typeToString(source2), signatureToString( - t, - /*enclosingDeclaration*/ - void 0, - /*flags*/ - void 0, - kind - )); - } - return 0 /* False */; + shouldElaborateErrors = false; } + if (shouldElaborateErrors) { + reportError(Diagnostics.Type_0_provides_no_match_for_the_signature_1, typeToString(source2), signatureToString(t, /*enclosingDeclaration*/ + void 0, /*flags*/ + void 0, kind)); + } + return 0 /* False */; + } } + return result2; } function shouldReportUnmatchedPropertyError(source2, target2) { @@ -64881,15 +60132,8 @@ ${lanes.join("\n")} const checkMode = relation === subtypeRelation ? 16 /* StrictTopSignature */ : relation === strictSubtypeRelation ? 16 /* StrictTopSignature */ | 8 /* StrictArity */ : 0 /* None */; return compareSignaturesRelated(erase ? getErasedSignature(source2) : source2, erase ? getErasedSignature(target2) : target2, checkMode, reportErrors2, reportError, incompatibleReporter, isRelatedToWorker2, reportUnreliableMapper); function isRelatedToWorker2(source3, target3, reportErrors3) { - return isRelatedTo( - source3, - target3, - 3 /* Both */, - reportErrors3, - /*headMessage*/ - void 0, - intersectionState - ); + return isRelatedTo(source3, target3, 3 /* Both */, reportErrors3, /*headMessage*/ + void 0, intersectionState); } } function signaturesIdenticalTo(source2, target2, kind) { @@ -64898,22 +60142,17 @@ ${lanes.join("\n")} if (sourceSignatures.length !== targetSignatures.length) { return 0 /* False */; } + let result2 = -1 /* True */; for (let i = 0; i < sourceSignatures.length; i++) { - const related = compareSignaturesIdentical( - sourceSignatures[i], - targetSignatures[i], - /*partialMatch*/ - false, - /*ignoreThisTypes*/ - false, - /*ignoreReturnTypes*/ - false, - isRelatedTo - ); + const related = compareSignaturesIdentical(sourceSignatures[i], targetSignatures[i], /*partialMatch*/ + false, /*ignoreThisTypes*/ + false, /*ignoreReturnTypes*/ + false, isRelatedTo); if (!related) { return 0 /* False */; } + result2 &= related; } return result2; @@ -64929,21 +60168,15 @@ ${lanes.join("\n")} if (isApplicableIndexType(getLiteralTypeFromProperty(prop, 8576 /* StringOrNumberLiteralOrUnique */), keyType)) { const propType = getNonMissingTypeOfSymbol(prop); const type = exactOptionalPropertyTypes || propType.flags & 32768 /* Undefined */ || keyType === numberType || !(prop.flags & 16777216 /* Optional */) ? propType : getTypeWithFacts(propType, 524288 /* NEUndefined */); - const related = isRelatedTo( - type, - targetInfo.type, - 3 /* Both */, - reportErrors2, - /*headMessage*/ - void 0, - intersectionState - ); + const related = isRelatedTo(type, targetInfo.type, 3 /* Both */, reportErrors2, /*headMessage*/ + void 0, intersectionState); if (!related) { if (reportErrors2) { reportError(Diagnostics.Property_0_is_incompatible_with_index_signature, symbolToString(prop)); } return 0 /* False */; } + result2 &= related; } } @@ -64953,21 +60186,15 @@ ${lanes.join("\n")} if (!related) { return 0 /* False */; } + result2 &= related; } } return result2; } function indexInfoRelatedTo(sourceInfo, targetInfo, reportErrors2, intersectionState) { - const related = isRelatedTo( - sourceInfo.type, - targetInfo.type, - 3 /* Both */, - reportErrors2, - /*headMessage*/ - void 0, - intersectionState - ); + const related = isRelatedTo(sourceInfo.type, targetInfo.type, 3 /* Both */, reportErrors2, /*headMessage*/ + void 0, intersectionState); if (!related && reportErrors2) { if (sourceInfo.keyType === targetInfo.keyType) { reportError(Diagnostics._0_index_signatures_are_incompatible, typeToString(sourceInfo.keyType)); @@ -64982,13 +60209,14 @@ ${lanes.join("\n")} return indexSignaturesIdenticalTo(source2, target2); } const indexInfos = getIndexInfosOfType(target2); - const targetHasStringIndex = some(indexInfos, (info) => info.keyType === stringType); + const targetHasStringIndex = some(indexInfos, info => info.keyType === stringType); let result2 = -1 /* True */; for (const targetInfo of indexInfos) { const related = relation !== strictSubtypeRelation && !sourceIsPrimitive && targetHasStringIndex && targetInfo.type.flags & 1 /* Any */ ? -1 /* True */ : isGenericMappedType(source2) && targetHasStringIndex ? isRelatedTo(getTemplateTypeFromMappedType(source2), targetInfo.type, 3 /* Both */, reportErrors2) : typeRelatedToIndexInfo(source2, targetInfo, reportErrors2, intersectionState); if (!related) { return 0 /* False */; } + result2 &= related; } return result2; @@ -65006,20 +60234,24 @@ ${lanes.join("\n")} } return 0 /* False */; } + function indexSignaturesIdenticalTo(source2, target2) { const sourceInfos = getIndexInfosOfType(source2); const targetInfos = getIndexInfosOfType(target2); if (sourceInfos.length !== targetInfos.length) { return 0 /* False */; } + for (const targetInfo of targetInfos) { const sourceInfo = getIndexInfoOfType(source2, targetInfo.keyType); if (!(sourceInfo && isRelatedTo(sourceInfo.type, targetInfo.type, 3 /* Both */) && sourceInfo.isReadonly === targetInfo.isReadonly)) { return 0 /* False */; } } + return -1 /* True */; } + function constructorVisibilitiesAreCompatible(sourceSignature, targetSignature, reportErrors2) { if (!sourceSignature.declaration || !targetSignature.declaration) { return true; @@ -65056,23 +60288,23 @@ ${lanes.join("\n")} } return isUnitType(type) || !!(type.flags & 134217728 /* TemplateLiteral */) || !!(type.flags & 268435456 /* StringMapping */); } + function getExactOptionalUnassignableProperties(source, target) { - if (isTupleType(source) && isTupleType(target)) - return emptyArray; - return getPropertiesOfType(target).filter((targetProp) => isExactOptionalPropertyMismatch(getTypeOfPropertyOfType(source, targetProp.escapedName), getTypeOfSymbol(targetProp))); + if (isTupleType(source) && isTupleType(target)) return emptyArray; + return getPropertiesOfType(target).filter(targetProp => isExactOptionalPropertyMismatch(getTypeOfPropertyOfType(source, targetProp.escapedName), getTypeOfSymbol(targetProp))); } function isExactOptionalPropertyMismatch(source, target) { return !!source && !!target && maybeTypeOfKind(source, 32768 /* Undefined */) && !!containsMissingType(target); } function getExactOptionalProperties(type) { - return getPropertiesOfType(type).filter((targetProp) => containsMissingType(getTypeOfSymbol(targetProp))); + return getPropertiesOfType(type).filter(targetProp => containsMissingType(getTypeOfSymbol(targetProp))); } function getBestMatchingType(source, target, isRelatedTo = compareTypesAssignable) { return findMatchingDiscriminantType(source, target, isRelatedTo) || findMatchingTypeReferenceOrTypeAliasReference(source, target) || findBestTypeForObjectLiteral(source, target) || findBestTypeForInvokable(source, target) || findMostOverlappyType(source, target); } function discriminateTypeByDiscriminableItems(target, discriminators, related) { const types = target.types; - const include = types.map((t) => t.flags & 402784252 /* Primitive */ ? 0 /* False */ : -1 /* True */); + const include = types.map(t => t.flags & 402784252 /* Primitive */ ? 0 /* False */ : -1 /* True */); for (const [getDiscriminatingType, propertyName] of discriminators) { let matched = false; for (let i = 0; i < types.length; i++) { @@ -65085,20 +60317,23 @@ ${lanes.join("\n")} } } } + for (let i = 0; i < types.length; i++) { if (include[i] === 3 /* Maybe */) { include[i] = matched ? 0 /* False */ : -1 /* True */; } } } + const filtered = contains(include, 0 /* False */) ? getUnionType(types.filter((_, i) => include[i]), 0 /* None */) : target; return filtered.flags & 131072 /* Never */ ? target : filtered; } function isWeakType(type) { if (type.flags & 524288 /* Object */) { const resolved = resolveStructuredTypeMembers(type); - return resolved.callSignatures.length === 0 && resolved.constructSignatures.length === 0 && resolved.indexInfos.length === 0 && resolved.properties.length > 0 && every(resolved.properties, (p) => !!(p.flags & 16777216 /* Optional */)); + return resolved.callSignatures.length === 0 && resolved.constructSignatures.length === 0 && resolved.indexInfos.length === 0 && resolved.properties.length > 0 && every(resolved.properties, p => !!(p.flags & 16777216 /* Optional */)); } + if (type.flags & 2097152 /* Intersection */) { return every(type.types, isWeakType); } @@ -65122,7 +60357,10 @@ ${lanes.join("\n")} var _a, _b; const links = getSymbolLinks(symbol); if (!links.variances) { - (_a = tracing) == null ? void 0 : _a.push(tracing.Phase.CheckTypes, "getVariancesWorker", { arity: typeParameters.length, id: getTypeId(getDeclaredTypeOfSymbol(symbol)) }); + (_a = tracing) == null ? void 0 : _a.push(tracing.Phase.CheckTypes, "getVariancesWorker", { + arity: typeParameters.length, + id: getTypeId(getDeclaredTypeOfSymbol(symbol)) + }); const oldVarianceComputation = inVarianceComputation; if (!inVarianceComputation) { inVarianceComputation = true; @@ -65137,23 +60375,26 @@ ${lanes.join("\n")} let unmeasurable = false; let unreliable = false; const oldHandler = outofbandVarianceMarkerHandler; - outofbandVarianceMarkerHandler = (onlyUnreliable) => onlyUnreliable ? unreliable = true : unmeasurable = true; + outofbandVarianceMarkerHandler = onlyUnreliable => onlyUnreliable ? unreliable = true : unmeasurable = true; const typeWithSuper = createMarkerType(symbol, tp, markerSuperType); const typeWithSub = createMarkerType(symbol, tp, markerSubType); variance = (isTypeAssignableTo(typeWithSub, typeWithSuper) ? 1 /* Covariant */ : 0) | (isTypeAssignableTo(typeWithSuper, typeWithSub) ? 2 /* Contravariant */ : 0); if (variance === 3 /* Bivariant */ && isTypeAssignableTo(createMarkerType(symbol, tp, markerOtherType), typeWithSuper)) { variance = 4 /* Independent */; } + outofbandVarianceMarkerHandler = oldHandler; if (unmeasurable || unreliable) { if (unmeasurable) { variance |= 8 /* Unmeasurable */; } + if (unreliable) { variance |= 16 /* Unreliable */; } } } + variances.push(variance); } if (!oldVarianceComputation) { @@ -65161,7 +60402,9 @@ ${lanes.join("\n")} resolutionStart = 0; } links.variances = variances; - (_b = tracing) == null ? void 0 : _b.pop({ variances: variances.map(Debug.formatVariance) }); + (_b = tracing) == null ? void 0 : _b.pop({ + variances: variances.map(Debug.formatVariance) + }); } return links.variances; } @@ -65182,6 +60425,7 @@ ${lanes.join("\n")} var _a; return reduceLeft((_a = tp.symbol) == null ? void 0 : _a.declarations, (modifiers, d) => modifiers | getEffectiveModifierFlags(d), 0 /* None */) & (8192 /* In */ | 16384 /* Out */ | 4096 /* Const */); } + function hasCovariantVoidArgument(typeArguments, variances) { for (let i = 0; i < variances.length; i++) { if ((variances[i] & 7 /* VarianceMask */) === 1 /* Covariant */ && typeArguments[i].flags & 16384 /* Void */) { @@ -65197,7 +60441,7 @@ ${lanes.join("\n")} return !!(getObjectFlags(type) & 4 /* Reference */) && !type.node; } function isTypeReferenceWithGenericArguments(type) { - return isNonDeferredTypeReference(type) && some(getTypeArguments(type), (t) => !!(t.flags & 262144 /* TypeParameter */) || isTypeReferenceWithGenericArguments(t)); + return isNonDeferredTypeReference(type) && some(getTypeArguments(type), t => !!(t.flags & 262144 /* TypeParameter */) || isTypeReferenceWithGenericArguments(t)); } function getGenericTypeReferenceRelationKey(source, target, postFix, ignoreConstraints) { const typeParameters = []; @@ -65259,16 +60503,16 @@ ${lanes.join("\n")} return baseClassType && getTypeOfPropertyOfType(baseClassType, property.escapedName); } function isPropertyInClassDerivedFrom(prop, baseClass) { - return forEachProperty2(prop, (sp) => { + return forEachProperty2(prop, sp => { const sourceClass = getDeclaringClass(sp); return sourceClass ? hasBaseType(sourceClass, baseClass) : false; }); } function isValidOverrideOf(sourceProp, targetProp) { - return !forEachProperty2(targetProp, (tp) => getDeclarationModifierFlagsFromSymbol(tp) & 4 /* Protected */ ? !isPropertyInClassDerivedFrom(sourceProp, getDeclaringClass(tp)) : false); + return !forEachProperty2(targetProp, tp => getDeclarationModifierFlagsFromSymbol(tp) & 4 /* Protected */ ? !isPropertyInClassDerivedFrom(sourceProp, getDeclaringClass(tp)) : false); } function isClassDerivedFromDeclaringClasses(checkClass, prop, writing) { - return forEachProperty2(prop, (p) => getDeclarationModifierFlagsFromSymbol(p, writing) & 4 /* Protected */ ? !hasBaseType(checkClass, getDeclaringClass(p)) : false) ? void 0 : checkClass; + return forEachProperty2(prop, p => getDeclarationModifierFlagsFromSymbol(p, writing) & 4 /* Protected */ ? !hasBaseType(checkClass, getDeclaringClass(p)) : false) ? void 0 : checkClass; } function isDeeplyNestedType(type, stack, depth, maxDepth = 3) { if (depth >= maxDepth) { @@ -65276,7 +60520,7 @@ ${lanes.join("\n")} type = getMappedTargetWithSymbol(type); } if (type.flags & 2097152 /* Intersection */) { - return some(type.types, (t) => isDeeplyNestedType(t, stack, depth, maxDepth)); + return some(type.types, t => isDeeplyNestedType(t, stack, depth, maxDepth)); } const identity2 = getRecursionIdentity(type); let count = 0; @@ -65298,7 +60542,7 @@ ${lanes.join("\n")} } function getMappedTargetWithSymbol(type) { let target; - while ((getObjectFlags(type) & 96 /* InstantiatedMapped */) === 96 /* InstantiatedMapped */ && (target = getModifiersTypeFromMappedType(type)) && (target.symbol || target.flags & 2097152 /* Intersection */ && some(target.types, (t) => !!t.symbol))) { + while ((getObjectFlags(type) & 96 /* InstantiatedMapped */) === 96 /* InstantiatedMapped */ && (target = getModifiersTypeFromMappedType(type)) && (target.symbol || target.flags & 2097152 /* Intersection */ && some(target.types, t => !!t.symbol))) { type = target; } return type; @@ -65308,7 +60552,7 @@ ${lanes.join("\n")} type = getMappedTargetWithSymbol(type); } if (type.flags & 2097152 /* Intersection */) { - return some(type.types, (t) => hasMatchingRecursionIdentity(t, identity2)); + return some(type.types, t => hasMatchingRecursionIdentity(t, identity2)); } return getRecursionIdentity(type) === identity2; } @@ -65341,15 +60585,18 @@ ${lanes.join("\n")} function isPropertyIdenticalTo(sourceProp, targetProp) { return compareProperties2(sourceProp, targetProp, compareTypesIdentical) !== 0 /* False */; } + function compareProperties2(sourceProp, targetProp, compareTypes) { if (sourceProp === targetProp) { return -1 /* True */; } + const sourcePropAccessibility = getDeclarationModifierFlagsFromSymbol(sourceProp) & 6 /* NonPublicAccessibilityModifier */; const targetPropAccessibility = getDeclarationModifierFlagsFromSymbol(targetProp) & 6 /* NonPublicAccessibilityModifier */; if (sourcePropAccessibility !== targetPropAccessibility) { return 0 /* False */; } + if (sourcePropAccessibility) { if (getTargetSymbol(sourceProp) !== getTargetSymbol(targetProp)) { return 0 /* False */; @@ -65359,9 +60606,11 @@ ${lanes.join("\n")} return 0 /* False */; } } + if (isReadonlySymbol(sourceProp) !== isReadonlySymbol(targetProp)) { return 0 /* False */; } + return compareTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp)); } function isMatchingSignature(source, target, partialMatch) { @@ -65383,12 +60632,15 @@ ${lanes.join("\n")} if (source === target) { return -1 /* True */; } + if (!isMatchingSignature(source, target, partialMatch)) { return 0 /* False */; } + if (length(source.typeParameters) !== length(target.typeParameters)) { return 0 /* False */; } + if (target.typeParameters) { const mapper = createTypeMapper(source.typeParameters, target.typeParameters); for (let i = 0; i < target.typeParameters.length; i++) { @@ -65398,12 +60650,9 @@ ${lanes.join("\n")} return 0 /* False */; } } - source = instantiateSignature( - source, - mapper, - /*eraseTypeParameters*/ - true - ); + + source = instantiateSignature(source, mapper, /*eraseTypeParameters*/ + true); } let result = -1 /* True */; if (!ignoreThisTypes) { @@ -65415,6 +60664,7 @@ ${lanes.join("\n")} if (!related) { return 0 /* False */; } + result &= related; } } @@ -65427,6 +60677,7 @@ ${lanes.join("\n")} if (!related) { return 0 /* False */; } + result &= related; } if (!ignoreReturnTypes) { @@ -65439,12 +60690,14 @@ ${lanes.join("\n")} function compareTypePredicatesIdentical(source, target, compareTypes) { return !(source && target && typePredicateKindsMatch(source, target)) ? 0 /* False */ : source.type === target.type ? -1 /* True */ : source.type && target.type ? compareTypes(source.type, target.type) : 0 /* False */; } + function literalTypesWithSameBaseType(types) { let commonBaseType; for (const t of types) { if (!(t.flags & 131072 /* Never */)) { + var _commonBaseType; const baseType = getBaseTypeOfLiteralType(t); - commonBaseType ?? (commonBaseType = baseType); + (_commonBaseType = commonBaseType) !== null && _commonBaseType !== void 0 ? _commonBaseType : commonBaseType = baseType; if (baseType === t || baseType !== commonBaseType) { return false; } @@ -65459,10 +60712,11 @@ ${lanes.join("\n")} if (types.length === 1) { return types[0]; } - const primaryTypes = strictNullChecks ? sameMap(types, (t) => filterType(t, (u) => !(u.flags & 98304 /* Nullable */))) : types; + const primaryTypes = strictNullChecks ? sameMap(types, t => filterType(t, u => !(u.flags & 98304 /* Nullable */))) : types; const superTypeOrUnion = literalTypesWithSameBaseType(primaryTypes) ? getUnionType(primaryTypes) : reduceLeft(primaryTypes, (s, t) => isTypeSubtypeOf(s, t) ? t : s); return primaryTypes === types ? superTypeOrUnion : getNullableType(superTypeOrUnion, getCombinedTypeFlags(types) & 98304 /* Nullable */); } + function getCommonSubtype(types) { return reduceLeft(types, (s, t) => isTypeSubtypeOf(t, s) ? t : s); } @@ -65525,8 +60779,9 @@ ${lanes.join("\n")} } function isTupleLikeType(type) { let lengthType; - return isTupleType(type) || !!getPropertyOfType(type, "0") || isArrayLikeType(type) && !!(lengthType = getTypeOfPropertyOfType(type, "length")) && everyType(lengthType, (t) => !!(t.flags & 256 /* NumberLiteral */)); + return isTupleType(type) || !!getPropertyOfType(type, "0") || isArrayLikeType(type) && !!(lengthType = getTypeOfPropertyOfType(type, "length")) && everyType(lengthType, t => !!(t.flags & 256 /* NumberLiteral */)); } + function isArrayOrTupleLikeType(type) { return isArrayLikeType(type) || isTupleLikeType(type); } @@ -65543,9 +60798,11 @@ ${lanes.join("\n")} function isNeitherUnitTypeNorNever(type) { return !(type.flags & (109472 /* Unit */ | 131072 /* Never */)); } + function isUnitType(type) { return !!(type.flags & 109472 /* Unit */); } + function isUnitLikeType(type) { const t = getBaseConstraintOrType(type); return t.flags & 2097152 /* Intersection */ ? some(t.types, isUnitType) : isUnitType(t); @@ -65560,8 +60817,9 @@ ${lanes.join("\n")} return type.flags & 1056 /* EnumLike */ ? getBaseTypeOfEnumLikeType(type) : type.flags & (128 /* StringLiteral */ | 134217728 /* TemplateLiteral */ | 268435456 /* StringMapping */) ? stringType : type.flags & 256 /* NumberLiteral */ ? numberType : type.flags & 2048 /* BigIntLiteral */ ? bigintType : type.flags & 512 /* BooleanLiteral */ ? booleanType : type.flags & 1048576 /* Union */ ? getBaseTypeOfLiteralTypeUnion(type) : type; } function getBaseTypeOfLiteralTypeUnion(type) { + var _getCachedType; const key = `B${getTypeId(type)}`; - return getCachedType(key) ?? setCachedType(key, mapType(type, getBaseTypeOfLiteralType)); + return (_getCachedType = getCachedType(key)) !== null && _getCachedType !== void 0 ? _getCachedType : setCachedType(key, mapType(type, getBaseTypeOfLiteralType)); } function getBaseTypeOfLiteralTypeForComparison(type) { return type.flags & (128 /* StringLiteral */ | 134217728 /* TemplateLiteral */ | 268435456 /* StringMapping */) ? stringType : type.flags & (256 /* NumberLiteral */ | 32 /* Enum */) ? numberType : type.flags & 2048 /* BigIntLiteral */ ? bigintType : type.flags & 512 /* BooleanLiteral */ ? booleanType : type.flags & 1048576 /* Union */ ? mapType(type, getBaseTypeOfLiteralTypeForComparison) : type; @@ -65595,9 +60853,11 @@ ${lanes.join("\n")} function isTupleType(type) { return !!(getObjectFlags(type) & 4 /* Reference */ && type.target.objectFlags & 8 /* Tuple */); } + function isGenericTupleType(type) { return isTupleType(type) && !!(type.target.combinedFlags & 8 /* Variadic */); } + function isSingleElementGenericTupleType(type) { return isGenericTupleType(type) && type.target.elementFlags.length === 1; } @@ -65605,7 +60865,7 @@ ${lanes.join("\n")} return getElementTypeOfSliceOfTupleType(type, type.target.fixedLength); } function getTupleElementTypeOutOfStartCount(type, index, undefinedOrMissingType2) { - return mapType(type, (t) => { + return mapType(type, t => { const tupleType = t; const restType = getRestTypeOfTupleType(tupleType); if (!restType) { @@ -65632,17 +60892,22 @@ ${lanes.join("\n")} } return writing ? getIntersectionType(elementTypes) : getUnionType(elementTypes, noReductions ? 0 /* None */ : 1 /* Literal */); } + return void 0; } function isTupleTypeStructureMatching(t1, t2) { return getTypeReferenceArity(t1) === getTypeReferenceArity(t2) && every(t1.target.elementFlags, (f, i) => (f & 12 /* Variable */) === (t2.target.elementFlags[i] & 12 /* Variable */)); } - function isZeroBigInt({ value }) { + + function isZeroBigInt({ + value + }) { return value.base10Value === "0"; } function removeDefinitelyFalsyTypes(type) { - return filterType(type, (t) => hasTypeFacts(t, 4194304 /* Truthy */)); + return filterType(type, t => hasTypeFacts(t, 4194304 /* Truthy */)); } + function extractDefinitelyFalsyTypes(type) { return mapType(type, getDefinitelyFalsyPartOfType); } @@ -65660,12 +60925,8 @@ ${lanes.join("\n")} } function getGlobalNonNullableTypeInstantiation(type) { if (!deferredGlobalNonNullableTypeAlias) { - deferredGlobalNonNullableTypeAlias = getGlobalSymbol( - "NonNullable", - 524288 /* TypeAlias */, - /*diagnostic*/ - void 0 - ) || unknownSymbol; + deferredGlobalNonNullableTypeAlias = getGlobalSymbol("NonNullable", 524288 /* TypeAlias */, /*diagnostic*/ + void 0) || unknownSymbol; } return deferredGlobalNonNullableTypeAlias !== unknownSymbol ? getTypeAliasInstantiation(deferredGlobalNonNullableTypeAlias, [type]) : getIntersectionType([type, emptyObjectType]); } @@ -65693,6 +60954,7 @@ ${lanes.join("\n")} function removeMissingOrUndefinedType(type) { return exactOptionalPropertyTypes ? removeType(type, missingType) : getTypeWithFacts(type, 524288 /* NEUndefined */); } + function isCoercibleUnderDoubleEquals(source, target) { return (source.flags & (8 /* Number */ | 4 /* String */ | 512 /* BooleanLiteral */)) !== 0 && (target.flags & (8 /* Number */ | 4 /* String */ | 16 /* Boolean */)) !== 0; } @@ -65741,7 +61003,12 @@ ${lanes.join("\n")} return regularNew; } function createWideningContext(parent2, propertyName, siblings) { - return { parent: parent2, propertyName, siblings, resolvedProperties: void 0 }; + return { + parent: parent2, + propertyName, + siblings, + resolvedProperties: void 0 + }; } function getSiblingsOfContext(context) { if (!context.siblings) { @@ -65750,7 +61017,7 @@ ${lanes.join("\n")} if (isObjectLiteralType2(type)) { const prop = getPropertyOfObjectType(type, context.propertyName); if (prop) { - forEachType(getTypeOfSymbol(prop), (t) => { + forEachType(getTypeOfSymbol(prop), t => { siblings.push(t); }); } @@ -65762,7 +61029,7 @@ ${lanes.join("\n")} } function getPropertiesOfContext(context) { if (!context.resolvedProperties) { - const names = /* @__PURE__ */ new Map(); + const names = /* @__PURE__ */new Map(); for (const t of getSiblingsOfContext(context)) { if (isObjectLiteralType2(t) && !(getObjectFlags(t) & 2097152 /* ContainsSpread */)) { for (const prop of getPropertiesOfType(t)) { @@ -65779,12 +61046,8 @@ ${lanes.join("\n")} return prop; } const original = getTypeOfSymbol(prop); - const propContext = context && createWideningContext( - context, - prop.escapedName, - /*siblings*/ - void 0 - ); + const propContext = context && createWideningContext(context, prop.escapedName, /*siblings*/ + void 0); const widened = getWidenedTypeWithContext(original, propContext); return widened === original ? prop : createSymbolWithType(prop, widened); } @@ -65810,16 +61073,13 @@ ${lanes.join("\n")} } } } - const result = createAnonymousType(type.symbol, members, emptyArray, emptyArray, sameMap(getIndexInfosOfType(type), (info) => createIndexInfo(info.keyType, getWidenedType(info.type), info.isReadonly))); + const result = createAnonymousType(type.symbol, members, emptyArray, emptyArray, sameMap(getIndexInfosOfType(type), info => createIndexInfo(info.keyType, getWidenedType(info.type), info.isReadonly))); result.objectFlags |= getObjectFlags(type) & (4096 /* JSLiteral */ | 262144 /* NonInferrableType */); return result; } function getWidenedType(type) { - return getWidenedTypeWithContext( - type, - /*context*/ - void 0 - ); + return getWidenedTypeWithContext(type, /*context*/ + void 0); } function getWidenedTypeWithContext(type, context) { if (getObjectFlags(type) & 196608 /* RequiresWidening */) { @@ -65832,14 +61092,10 @@ ${lanes.join("\n")} } else if (isObjectLiteralType2(type)) { result = getWidenedTypeOfObjectLiteral(type, context); } else if (type.flags & 1048576 /* Union */) { - const unionContext = context || createWideningContext( - /*parent*/ - void 0, - /*propertyName*/ - void 0, - type.types - ); - const widenedTypes = sameMap(type.types, (t) => t.flags & 98304 /* Nullable */ ? t : getWidenedTypeWithContext(t, unionContext)); + const unionContext = context || createWideningContext( /*parent*/ + void 0, /*propertyName*/ + void 0, type.types); + const widenedTypes = sameMap(type.types, t => t.flags & 98304 /* Nullable */ ? t : getWidenedTypeWithContext(t, unionContext)); result = getUnionType(widenedTypes, some(widenedTypes, isEmptyObjectType) ? 2 /* Subtype */ : 1 /* Literal */); } else if (type.flags & 2097152 /* Intersection */) { result = getIntersectionType(sameMap(type.types, getWidenedType)); @@ -65904,16 +61160,9 @@ ${lanes.join("\n")} const param = declaration; if (isIdentifier(param.name)) { const originalKeywordKind = identifierToKeywordKind(param.name); - if ((isCallSignatureDeclaration(param.parent) || isMethodSignature(param.parent) || isFunctionTypeNode(param.parent)) && param.parent.parameters.includes(param) && (resolveName( - param, - param.name.escapedText, - 788968 /* Type */, - /*nameNotFoundMessage*/ - void 0, - param.name.escapedText, - /*isUse*/ - true - ) || originalKeywordKind && isTypeNodeKind(originalKeywordKind))) { + if ((isCallSignatureDeclaration(param.parent) || isMethodSignature(param.parent) || isFunctionTypeNode(param.parent)) && param.parent.parameters.includes(param) && (resolveName(param, param.name.escapedText, 788968 /* Type */, /*nameNotFoundMessage*/ + void 0, param.name.escapedText, /*isUse*/ + true) || originalKeywordKind && isTypeNodeKind(originalKeywordKind))) { const newName = "arg" + param.parent.parameters.indexOf(param); const typeName = declarationNameToString(param.name) + (param.dotDotDotToken ? "[]" : ""); errorOrSuggestion(noImplicitAny, declaration, Diagnostics.Parameter_has_a_name_but_no_type_Did_you_mean_0_Colon_1, newName, typeName); @@ -65990,12 +61239,8 @@ ${lanes.join("\n")} callback(getTypeAtPosition(source, i), getTypeAtPosition(target, i)); } if (targetRestType) { - callback(getRestTypeAtPosition( - source, - paramCount, - /*readonly*/ - isConstTypeVariable(targetRestType) && !someType(targetRestType, isMutableArrayLikeType) - ), targetRestType); + callback(getRestTypeAtPosition(source, paramCount, /*readonly*/ + isConstTypeVariable(targetRestType) && !someType(targetRestType, isMutableArrayLikeType)), targetRestType); } } function applyToReturnTypes(source, target, callback) { @@ -66028,25 +61273,19 @@ ${lanes.join("\n")} return context; } function makeFixingMapperForContext(context) { - return makeDeferredTypeMapper( - map(context.inferences, (i) => i.typeParameter), - map(context.inferences, (inference, i) => () => { - if (!inference.isFixed) { - inferFromIntraExpressionSites(context); - clearCachedInferences(context.inferences); - inference.isFixed = true; - } - return getInferredType(context, i); - }) - ); + return makeDeferredTypeMapper(map(context.inferences, i => i.typeParameter), map(context.inferences, (inference, i) => () => { + if (!inference.isFixed) { + inferFromIntraExpressionSites(context); + clearCachedInferences(context.inferences); + inference.isFixed = true; + } + return getInferredType(context, i); + })); } function makeNonFixingMapperForContext(context) { - return makeDeferredTypeMapper( - map(context.inferences, (i) => i.typeParameter), - map(context.inferences, (_, i) => () => { - return getInferredType(context, i); - }) - ); + return makeDeferredTypeMapper(map(context.inferences, i => i.typeParameter), map(context.inferences, (_, i) => () => { + return getInferredType(context, i); + })); } function clearCachedInferences(inferences) { for (const inference of inferences) { @@ -66056,11 +61295,18 @@ ${lanes.join("\n")} } } function addIntraExpressionInferenceSite(context, node, type) { - (context.intraExpressionInferenceSites ?? (context.intraExpressionInferenceSites = [])).push({ node, type }); + var _context$intraExpress; + ((_context$intraExpress = context.intraExpressionInferenceSites) !== null && _context$intraExpress !== void 0 ? _context$intraExpress : context.intraExpressionInferenceSites = []).push({ + node, + type + }); } function inferFromIntraExpressionSites(context) { if (context.intraExpressionInferenceSites) { - for (const { node, type } of context.intraExpressionInferenceSites) { + for (const { + node, + type + } of context.intraExpressionInferenceSites) { const contextualType = node.kind === 174 /* MethodDeclaration */ ? getContextualTypeForObjectLiteralMethod(node, 2 /* NoConstraints */) : getContextualType2(node, 2 /* NoConstraints */); if (contextualType) { inferTypes(context.inferences, type, contextualType); @@ -66105,6 +61351,7 @@ ${lanes.join("\n")} if (objectFlags & 524288 /* CouldContainTypeVariablesComputed */) { return !!(objectFlags & 1048576 /* CouldContainTypeVariables */); } + const result = !!(type.flags & 465829888 /* Instantiable */ || type.flags & 524288 /* Object */ && !isNonGenericTopLevelType(type) && (objectFlags & 4 /* Reference */ && (type.node || some(getTypeArguments(type), couldContainTypeVariables)) || objectFlags & 16 /* Anonymous */ && type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && type.symbol.declarations || objectFlags & (32 /* Mapped */ | 1024 /* ReverseMapped */ | 4194304 /* ObjectRestType */ | 8388608 /* InstantiationExpressionType */)) || type.flags & 3145728 /* UnionOrIntersection */ && !(type.flags & 1024 /* EnumLiteral */) && !isNonGenericTopLevelType(type) && some(type.types, couldContainTypeVariables)); if (type.flags & 3899393 /* ObjectFlagsType */) { type.objectFlags |= 524288 /* CouldContainTypeVariablesComputed */ | (result ? 1048576 /* CouldContainTypeVariables */ : 0); @@ -66114,12 +61361,12 @@ ${lanes.join("\n")} function isNonGenericTopLevelType(type) { if (type.aliasSymbol && !type.aliasTypeArguments) { const declaration = getDeclarationOfKind(type.aliasSymbol, 265 /* TypeAliasDeclaration */); - return !!(declaration && findAncestor(declaration.parent, (n) => n.kind === 312 /* SourceFile */ ? true : n.kind === 267 /* ModuleDeclaration */ ? false : "quit")); + return !!(declaration && findAncestor(declaration.parent, n => n.kind === 312 /* SourceFile */ ? true : n.kind === 267 /* ModuleDeclaration */ ? false : "quit")); } return false; } function isTypeParameterAtTopLevel(type, tp, depth = 0) { - return !!(type === tp || type.flags & 3145728 /* UnionOrIntersection */ && some(type.types, (t) => isTypeParameterAtTopLevel(t, tp, depth)) || depth < 3 && type.flags & 16777216 /* Conditional */ && (isTypeParameterAtTopLevel(getTrueTypeFromConditionalType(type), tp, depth + 1) || isTypeParameterAtTopLevel(getFalseTypeFromConditionalType(type), tp, depth + 1))); + return !!(type === tp || type.flags & 3145728 /* UnionOrIntersection */ && some(type.types, t => isTypeParameterAtTopLevel(t, tp, depth)) || depth < 3 && type.flags & 16777216 /* Conditional */ && (isTypeParameterAtTopLevel(getTrueTypeFromConditionalType(type), tp, depth + 1) || isTypeParameterAtTopLevel(getFalseTypeFromConditionalType(type), tp, depth + 1))); } function isTypeParameterAtTopLevelInReturnType(signature, typeParameter) { const typePredicate = getTypePredicateOfSignature(signature); @@ -66127,7 +61374,7 @@ ${lanes.join("\n")} } function createEmptyObjectTypeFromStringLiteral(type) { const members = createSymbolTable(); - forEachType(type, (t) => { + forEachType(type, t => { if (!(t.flags & 128 /* StringLiteral */)) { return; } @@ -66140,20 +61387,10 @@ ${lanes.join("\n")} } members.set(name, literalProp); }); - const indexInfos = type.flags & 4 /* String */ ? [createIndexInfo( - stringType, - emptyObjectType, - /*isReadonly*/ - false - )] : emptyArray; - return createAnonymousType( - /*symbol*/ - void 0, - members, - emptyArray, - emptyArray, - indexInfos - ); + const indexInfos = type.flags & 4 /* String */ ? [createIndexInfo(stringType, emptyObjectType, /*isReadonly*/ + false)] : emptyArray; + return createAnonymousType( /*symbol*/ + void 0, members, emptyArray, emptyArray, indexInfos); } function inferTypeForHomomorphicMappedType(source, target, constraint) { const cacheKey = source.id + "," + target.id + "," + constraint.id; @@ -66171,7 +61408,7 @@ ${lanes.join("\n")} return type; } function isPartiallyInferableType(type) { - return !(getObjectFlags(type) & 262144 /* NonInferrableType */) || isObjectLiteralType2(type) && some(getPropertiesOfType(type), (prop) => isPartiallyInferableType(getTypeOfSymbol(prop))) || isTupleType(type) && some(getElementTypes(type), isPartiallyInferableType); + return !(getObjectFlags(type) & 262144 /* NonInferrableType */) || isObjectLiteralType2(type) && some(getPropertiesOfType(type), prop => isPartiallyInferableType(getTypeOfSymbol(prop))) || isTupleType(type) && some(getElementTypes(type), isPartiallyInferableType); } function createReverseMappedType(source, target, constraint) { if (!(getIndexInfoOfType(source, stringType) || getPropertiesOfType(source).length !== 0 && isPartiallyInferableType(source))) { @@ -66181,15 +61418,12 @@ ${lanes.join("\n")} return createArrayType(inferReverseMappedType(getTypeArguments(source)[0], target, constraint), isReadonlyArrayType(source)); } if (isTupleType(source)) { - const elementTypes = map(getElementTypes(source), (t) => inferReverseMappedType(t, target, constraint)); - const elementFlags = getMappedTypeModifiers(target) & 4 /* IncludeOptional */ ? sameMap(source.target.elementFlags, (f) => f & 2 /* Optional */ ? 1 /* Required */ : f) : source.target.elementFlags; + const elementTypes = map(getElementTypes(source), t => inferReverseMappedType(t, target, constraint)); + const elementFlags = getMappedTypeModifiers(target) & 4 /* IncludeOptional */ ? sameMap(source.target.elementFlags, f => f & 2 /* Optional */ ? 1 /* Required */ : f) : source.target.elementFlags; return createTupleType(elementTypes, elementFlags, source.target.readonly, source.target.labeledElementDeclarations); } - const reversed = createObjectType( - 1024 /* ReverseMapped */ | 16 /* Anonymous */, - /*symbol*/ - void 0 - ); + const reversed = createObjectType(1024 /* ReverseMapped */ | 16 /* Anonymous */, /*symbol*/ + void 0); reversed.source = source; reversed.mappedType = target; reversed.constraintType = constraint; @@ -66238,21 +61472,11 @@ ${lanes.join("\n")} return !(target.target.combinedFlags & 8 /* Variadic */) && target.target.minLength > source.target.minLength || !target.target.hasRestElement && (source.target.hasRestElement || target.target.fixedLength < source.target.fixedLength); } function typesDefinitelyUnrelated(source, target) { - return isTupleType(source) && isTupleType(target) ? tupleTypesDefinitelyUnrelated(source, target) : !!getUnmatchedProperty( - source, - target, - /*requireOptionalProperties*/ - false, - /*matchDiscriminantProperties*/ - true - ) && !!getUnmatchedProperty( - target, - source, - /*requireOptionalProperties*/ - false, - /*matchDiscriminantProperties*/ - false - ); + return isTupleType(source) && isTupleType(target) ? tupleTypesDefinitelyUnrelated(source, target) : !!getUnmatchedProperty(source, target, /*requireOptionalProperties*/ + false, /*matchDiscriminantProperties*/ + true) && !!getUnmatchedProperty(target, source, /*requireOptionalProperties*/ + false, /*matchDiscriminantProperties*/ + false); } function getTypeFromInference(inference) { return inference.candidates ? getUnionType(inference.candidates, 2 /* Subtype */) : inference.contraCandidates ? getIntersectionType(inference.contraCandidates) : void 0; @@ -66273,8 +61497,7 @@ ${lanes.join("\n")} 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); } @@ -66304,19 +61527,13 @@ ${lanes.join("\n")} return true; } if (target.flags & 2097152 /* Intersection */) { - return every(target.types, (t) => t === emptyTypeLiteralType || isValidTypeForTemplateLiteralPlaceholder(source, t)); + return every(target.types, t => t === emptyTypeLiteralType || isValidTypeForTemplateLiteralPlaceholder(source, t)); } if (source.flags & 128 /* StringLiteral */) { const value = source.value; - return !!(target.flags & 8 /* Number */ && isValidNumberString( - value, - /*roundTripOnly*/ - false - ) || target.flags & 64 /* BigInt */ && isValidBigIntString( - value, - /*roundTripOnly*/ - false - ) || target.flags & (512 /* BooleanLiteral */ | 98304 /* Nullable */) && value === target.intrinsicName || target.flags & 268435456 /* StringMapping */ && isMemberOfStringMapping(getStringLiteralType(value), target) || target.flags & 134217728 /* TemplateLiteral */ && isTypeMatchedByTemplateLiteralType(source, target)); + return !!(target.flags & 8 /* Number */ && isValidNumberString(value, /*roundTripOnly*/ + false) || target.flags & 64 /* BigInt */ && isValidBigIntString(value, /*roundTripOnly*/ + false) || target.flags & (512 /* BooleanLiteral */ | 98304 /* Nullable */) && value === target.intrinsicName || target.flags & 268435456 /* StringMapping */ && isMemberOfStringMapping(getStringLiteralType(value), target) || target.flags & 134217728 /* TemplateLiteral */ && isTypeMatchedByTemplateLiteralType(source, target)); } if (source.flags & 134217728 /* TemplateLiteral */) { const texts = source.texts; @@ -66342,8 +61559,7 @@ ${lanes.join("\n")} 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; @@ -66355,11 +61571,9 @@ ${lanes.join("\n")} 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); @@ -66378,10 +61592,7 @@ ${lanes.join("\n")} return index < lastSourceIndex ? sourceTexts[index] : remainingEndText; } function addMatch(s, p) { - const matchType = s === seg ? getStringLiteralType(getSourceText(s).slice(pos, p)) : getTemplateLiteralType( - [sourceTexts[seg].slice(pos), ...sourceTexts.slice(seg + 1, s), getSourceText(s).slice(0, p)], - sourceTypes.slice(seg, s) - ); + const matchType = s === seg ? getStringLiteralType(getSourceText(s).slice(pos, p)) : getTemplateLiteralType([sourceTexts[seg].slice(pos), ...sourceTexts.slice(seg + 1, s), getSourceText(s).slice(0, p)], sourceTypes.slice(seg, s)); matches.push(matchType); seg = s; pos = p; @@ -66486,30 +61697,17 @@ ${lanes.join("\n")} inferencePriority = Math.min(inferencePriority, priority); return; } - const simplified = getSimplifiedType( - target, - /*writing*/ - false - ); + const simplified = getSimplifiedType(target, /*writing*/ + false); if (simplified !== target) { inferFromTypes(source, simplified); } else if (target.flags & 8388608 /* IndexedAccess */) { - const indexType = getSimplifiedType( - target.indexType, - /*writing*/ - false - ); + const indexType = getSimplifiedType(target.indexType, /*writing*/ + false); if (indexType.flags & 465829888 /* Instantiable */) { - const simplified2 = distributeIndexOverObjectType( - getSimplifiedType( - target.objectType, - /*writing*/ - false - ), - indexType, - /*writing*/ - false - ); + const simplified2 = distributeIndexOverObjectType(getSimplifiedType(target.objectType, /*writing*/ + false), indexType, /*writing*/ + false); if (simplified2 && simplified2 !== target) { inferFromTypes(source, simplified2); } @@ -66577,27 +61775,27 @@ ${lanes.join("\n")} priority = savePriority; } function invokeOnce(source, target, action) { + var _sourceStack, _targetStack; const key = source.id + "," + target.id; const status = visited && visited.get(key); if (status !== void 0) { inferencePriority = Math.min(inferencePriority, status); return; } - (visited || (visited = /* @__PURE__ */ new Map())).set(key, -1 /* Circularity */); + (visited || (visited = /* @__PURE__ */new Map())).set(key, -1 /* Circularity */); const saveInferencePriority = inferencePriority; inferencePriority = 2048 /* MaxValue */; 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 */; + ((_sourceStack = sourceStack) !== null && _sourceStack !== void 0 ? _sourceStack : sourceStack = []).push(source); + ((_targetStack = targetStack) !== null && _targetStack !== void 0 ? _targetStack : targetStack = []).push(target); + if (isDeeplyNestedType(source, sourceStack, sourceStack.length, 2)) expandingFlags |= 1 /* Source */; + if (isDeeplyNestedType(target, targetStack, targetStack.length, 2)) expandingFlags |= 2 /* Target */; if (expandingFlags !== 3 /* Both */) { action(source, target); } else { inferencePriority = -1 /* Circularity */; } + targetStack.pop(); sourceStack.pop(); expandingFlags = saveExpandingFlags; @@ -66616,10 +61814,7 @@ ${lanes.join("\n")} } } } - return [ - matchedSources ? filter(sources, (t) => !contains(matchedSources, t)) : sources, - matchedTargets ? filter(targets, (t) => !contains(matchedTargets, t)) : targets - ]; + return [matchedSources ? filter(sources, t => !contains(matchedSources, t)) : sources, matchedTargets ? filter(targets, t => !contains(matchedTargets, t)) : targets]; } function inferFromTypeArguments(sourceTypes, targetTypes, variances) { const count = sourceTypes.length < targetTypes.length ? sourceTypes.length : targetTypes.length; @@ -66656,7 +61851,7 @@ ${lanes.join("\n")} function getSingleTypeVariableFromIntersectionTypes(types) { let typeVariable; for (const type of types) { - const t = type.flags & 2097152 /* Intersection */ && find(type.types, (t2) => !!getInferenceInfoForType(t2)); + const t = type.flags & 2097152 /* Intersection */ && find(type.types, t2 => !!getInferenceInfoForType(t2)); if (!t || typeVariable && t !== typeVariable) { return void 0; } @@ -66680,8 +61875,7 @@ ${lanes.join("\n")} 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); } @@ -66692,6 +61886,7 @@ ${lanes.join("\n")} if (intersectionTypeVariable) { inferWithPriority(source, intersectionTypeVariable, 1 /* NakedTypeVariable */); } + return; } if (typeVariableCount === 1 && !inferenceCircularity) { @@ -66718,6 +61913,7 @@ ${lanes.join("\n")} } } } + function inferToMappedType(source, target, constraintType) { if (constraintType.flags & 1048576 /* Union */) { let result = false; @@ -66731,27 +61927,21 @@ ${lanes.join("\n")} if (inference && !inference.isFixed && !isFromInferenceBlockedSource(source)) { const inferredType = inferTypeForHomomorphicMappedType(source, target, constraintType); if (inferredType) { - inferWithPriority( - inferredType, - inference.typeParameter, - getObjectFlags(source) & 262144 /* NonInferrableType */ ? 16 /* PartialHomomorphicMappedType */ : 8 /* HomomorphicMappedType */ - ); + inferWithPriority(inferredType, inference.typeParameter, getObjectFlags(source) & 262144 /* NonInferrableType */ ? 16 /* PartialHomomorphicMappedType */ : 8 /* HomomorphicMappedType */); } } + return true; } if (constraintType.flags & 262144 /* TypeParameter */) { - inferWithPriority(getIndexType( - source, - /*indexFlags*/ - !!source.pattern ? 2 /* NoIndexSignatures */ : 0 /* None */ - ), constraintType, 32 /* MappedTypeConstraint */); + inferWithPriority(getIndexType(source, /*indexFlags*/ + !!source.pattern ? 2 /* NoIndexSignatures */ : 0 /* None */), constraintType, 32 /* MappedTypeConstraint */); const extendedConstraint = getConstraintOfType(constraintType); if (extendedConstraint && inferToMappedType(source, target, extendedConstraint)) { return true; } const propTypes = map(getPropertiesOfType(source), getTypeOfSymbol); - const indexTypes = map(getIndexInfosOfType(source), (info) => info !== enumNumberIndexInfo ? info.type : neverType); + const indexTypes = map(getIndexInfosOfType(source), info => info !== enumNumberIndexInfo ? info.type : neverType); inferFromTypes(getUnionType(concatenate(propTypes, indexTypes)), getTemplateTypeFromMappedType(target)); return true; } @@ -66771,7 +61961,7 @@ ${lanes.join("\n")} function inferToTemplateLiteralType(source, target) { const matches = inferTypesFromTemplateLiteralType(source, target); const types = target.types; - if (matches || every(target.texts, (s) => s.length === 0)) { + if (matches || every(target.texts, s => s.length === 0)) { for (let i = 0; i < types.length; i++) { const source2 = matches ? matches[i] : neverType; const target2 = types[i]; @@ -66783,20 +61973,16 @@ ${lanes.join("\n")} let allTypeFlags = reduceLeft(constraintTypes, (flags, t) => flags | t.flags, 0); if (!(allTypeFlags & 4 /* String */)) { const str = source2.value; - if (allTypeFlags & 296 /* NumberLike */ && !isValidNumberString( - str, - /*roundTripOnly*/ - true - )) { + if (allTypeFlags & 296 /* NumberLike */ && !isValidNumberString(str, /*roundTripOnly*/ + true)) { allTypeFlags &= ~296 /* NumberLike */; } - if (allTypeFlags & 2112 /* BigIntLike */ && !isValidBigIntString( - str, - /*roundTripOnly*/ - true - )) { + + if (allTypeFlags & 2112 /* BigIntLike */ && !isValidBigIntString(str, /*roundTripOnly*/ + true)) { allTypeFlags &= ~2112 /* BigIntLike */; } + const matchingType = reduceLeft(constraintTypes, (left, right) => !(right.flags & allTypeFlags) ? left : left.flags & 4 /* String */ ? left : right.flags & 4 /* String */ ? source2 : left.flags & 134217728 /* TemplateLiteral */ ? left : right.flags & 134217728 /* TemplateLiteral */ && isTypeMatchedByTemplateLiteralType(source2, right) ? source2 : left.flags & 268435456 /* StringMapping */ ? left : right.flags & 268435456 /* StringMapping */ && str === applyStringMapping(right.symbol, str) ? source2 : left.flags & 128 /* StringLiteral */ ? left : right.flags & 128 /* StringLiteral */ && right.value === str ? right : left.flags & 8 /* Number */ ? left : right.flags & 8 /* Number */ ? getNumberLiteralType(+str) : left.flags & 32 /* Enum */ ? left : right.flags & 32 /* Enum */ ? getNumberLiteralType(+str) : left.flags & 256 /* NumberLiteral */ ? left : right.flags & 256 /* NumberLiteral */ && right.value === +str ? right : left.flags & 64 /* BigInt */ ? left : right.flags & 64 /* BigInt */ ? parseBigIntLiteralType(str) : left.flags & 2048 /* BigIntLiteral */ ? left : right.flags & 2048 /* BigIntLiteral */ && pseudoBigIntToString(right.value) === str ? right : left.flags & 16 /* Boolean */ ? left : right.flags & 16 /* Boolean */ ? str === "true" ? trueType : str === "false" ? falseType : booleanType : left.flags & 512 /* BooleanLiteral */ ? left : right.flags & 512 /* BooleanLiteral */ && right.intrinsicName === str ? right : left.flags & 32768 /* Undefined */ ? left : right.flags & 32768 /* Undefined */ && right.intrinsicName === str ? right : left.flags & 65536 /* Null */ ? left : right.flags & 65536 /* Null */ && right.intrinsicName === str ? right : left, neverType); if (!(matchingType.flags & 131072 /* Never */)) { inferFromTypes(matchingType, target2); @@ -66820,8 +62006,7 @@ ${lanes.join("\n")} 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); } if (getObjectFlags(target) & 32 /* Mapped */ && !target.declaration.nameType) { const constraintType = getConstraintTypeFromMappedType(target); @@ -66876,13 +62061,8 @@ ${lanes.join("\n")} const impliedArity = constraint.target.fixedLength; const endIndex = sourceArity - getEndElementCount(target.target, 3 /* Fixed */); const startIndex = endIndex - impliedArity; - const trailingSlice = createTupleType( - getTypeArguments(source).slice(startIndex, endIndex), - source.target.elementFlags.slice(startIndex, endIndex), - /*readonly*/ - false, - source.target.labeledElementDeclarations && source.target.labeledElementDeclarations.slice(startIndex, endIndex) - ); + const trailingSlice = createTupleType(getTypeArguments(source).slice(startIndex, endIndex), source.target.elementFlags.slice(startIndex, endIndex), /*readonly*/ + false, source.target.labeledElementDeclarations && source.target.labeledElementDeclarations.slice(startIndex, endIndex)); inferFromTypes(getElementTypeOfSliceOfTupleType(source, startLength, endLength + impliedArity), elementTypes[startLength]); inferFromTypes(trailingSlice, elementTypes[startLength + 1]); } @@ -66978,6 +62158,7 @@ ${lanes.join("\n")} function isTypeOrBaseIdenticalTo(s, t) { return t === missingType ? s === t : isTypeIdenticalTo(s, t) || !!(t.flags & 4 /* String */ && s.flags & 128 /* StringLiteral */ || t.flags & 8 /* Number */ && s.flags & 256 /* NumberLiteral */); } + function isTypeCloselyMatchedBy(s, t) { return !!(s.flags & 524288 /* Object */ && t.flags & 524288 /* Object */ && s.symbol && s.symbol === t.symbol || s.aliasSymbol && s.aliasTypeArguments && s.aliasSymbol === t.aliasSymbol); } @@ -66985,18 +62166,21 @@ ${lanes.join("\n")} const constraint = getConstraintOfTypeParameter(type); return !!constraint && maybeTypeOfKind(constraint.flags & 16777216 /* Conditional */ ? getDefaultConstraintOfConditionalType(constraint) : constraint, 402784252 /* Primitive */ | 4194304 /* Index */ | 134217728 /* TemplateLiteral */ | 268435456 /* StringMapping */); } + function isObjectLiteralType2(type) { return !!(getObjectFlags(type) & 128 /* ObjectLiteral */); } + function isObjectOrArrayLiteralType(type) { return !!(getObjectFlags(type) & (128 /* ObjectLiteral */ | 16384 /* ArrayLiteral */)); } + function unionObjectAndArrayLiteralCandidates(candidates) { if (candidates.length > 1) { const objectLiterals = filter(candidates, isObjectOrArrayLiteralType); if (objectLiterals.length) { const literalsType = getUnionType(objectLiterals, 2 /* Subtype */); - return concatenate(filter(candidates, (t) => !isObjectOrArrayLiteralType(t)), [literalsType]); + return concatenate(filter(candidates, t => !isObjectOrArrayLiteralType(t)), [literalsType]); } } return candidates; @@ -67021,7 +62205,7 @@ ${lanes.join("\n")} const inferredCovariantType = inference.candidates ? getCovariantInference(inference, context.signature) : void 0; const inferredContravariantType = inference.contraCandidates ? getContravariantInference(inference) : void 0; if (inferredCovariantType || inferredContravariantType) { - const preferCovariantType = inferredCovariantType && (!inferredContravariantType || !(inferredCovariantType.flags & 131072 /* Never */) && some(inference.contraCandidates, (t) => isTypeSubtypeOf(inferredCovariantType, t)) && every(context.inferences, (other) => other !== inference && getConstraintOfTypeParameter(other.typeParameter) !== inference.typeParameter || every(other.candidates, (t) => isTypeSubtypeOf(t, inferredCovariantType)))); + const preferCovariantType = inferredCovariantType && (!inferredContravariantType || !(inferredCovariantType.flags & 131072 /* Never */) && some(inference.contraCandidates, t => isTypeSubtypeOf(inferredCovariantType, t)) && every(context.inferences, other => other !== inference && getConstraintOfTypeParameter(other.typeParameter) !== inference.typeParameter || every(other.candidates, t => isTypeSubtypeOf(t, inferredCovariantType)))); inferredType = preferCovariantType ? inferredCovariantType : inferredContravariantType; fallbackType = preferCovariantType ? inferredContravariantType : inferredCovariantType; } else if (context.flags & 1 /* NoDefault */) { @@ -67107,21 +62291,13 @@ ${lanes.join("\n")} function getResolvedSymbol(node) { const links = getNodeLinks(node); if (!links.resolvedSymbol) { - links.resolvedSymbol = !nodeIsMissing(node) && resolveName( - node, - node.escapedText, - 111551 /* Value */ | 1048576 /* ExportValue */, - getCannotFindNameDiagnosticForName(node), - node, - !isWriteOnlyAccess(node), - /*excludeGlobals*/ - false - ) || unknownSymbol; + links.resolvedSymbol = !nodeIsMissing(node) && resolveName(node, node.escapedText, 111551 /* Value */ | 1048576 /* ExportValue */, getCannotFindNameDiagnosticForName(node), node, !isWriteOnlyAccess(node), /*excludeGlobals*/ + false) || unknownSymbol; } return links.resolvedSymbol; } function isInAmbientOrTypeNode(node) { - return !!(node.flags & 33554432 /* Ambient */ || findAncestor(node, (n) => isInterfaceDeclaration(n) || isTypeAliasDeclaration(n) || isTypeLiteralNode(n))); + return !!(node.flags & 33554432 /* Ambient */ || findAncestor(node, n => isInterfaceDeclaration(n) || isTypeAliasDeclaration(n) || isTypeLiteralNode(n))); } function getFlowCacheKey(node, declaredType, initialType, flowContainer) { switch (node.kind) { @@ -67212,17 +62388,11 @@ ${lanes.join("\n")} return isStringOrNumericLiteralLike(node.argumentExpression) ? escapeLeadingUnderscores(node.argumentExpression.text) : isEntityNameExpression(node.argumentExpression) ? tryGetNameFromEntityNameExpression(node.argumentExpression) : void 0; } function tryGetNameFromEntityNameExpression(node) { - const symbol = resolveEntityName( - node, - 111551 /* Value */, - /*ignoreErrors*/ - true - ); - if (!symbol || !(isConstantVariable(symbol) || symbol.flags & 8 /* EnumMember */)) - return void 0; + const symbol = resolveEntityName(node, 111551 /* Value */, /*ignoreErrors*/ + true); + if (!symbol || !(isConstantVariable(symbol) || symbol.flags & 8 /* EnumMember */)) return void 0; const declaration = symbol.valueDeclaration; - if (declaration === void 0) - return void 0; + if (declaration === void 0) return void 0; const type = tryGetTypeFromEffectiveTypeNode(declaration); if (type) { const name = tryGetNameFromType(type); @@ -67285,7 +62455,7 @@ ${lanes.join("\n")} return result; } function mapTypesByKeyProperty(types, name) { - const map2 = /* @__PURE__ */ new Map(); + const map2 = /* @__PURE__ */new Map(); let count = 0; for (const type of types) { if (type.flags & (524288 /* Object */ | 2097152 /* Intersection */ | 58982400 /* InstantiableNonPrimitive */)) { @@ -67295,7 +62465,7 @@ ${lanes.join("\n")} return void 0; } let duplicate = false; - forEachType(discriminant, (t) => { + forEachType(discriminant, t => { const id = getTypeId(getRegularTypeOfLiteralType(t)); const existing = map2.get(id); if (!existing) { @@ -67305,8 +62475,7 @@ ${lanes.join("\n")} duplicate = true; } }); - if (!duplicate) - count++; + if (!duplicate) count++; } } } @@ -67314,11 +62483,11 @@ ${lanes.join("\n")} } function getKeyPropertyName(unionType) { const types = unionType.types; - if (types.length < 10 || getObjectFlags(unionType) & 32768 /* PrimitiveUnion */ || countWhere(types, (t) => !!(t.flags & (524288 /* Object */ | 58982400 /* InstantiableNonPrimitive */))) < 10) { + if (types.length < 10 || getObjectFlags(unionType) & 32768 /* PrimitiveUnion */ || countWhere(types, t => !!(t.flags & (524288 /* Object */ | 58982400 /* InstantiableNonPrimitive */))) < 10) { return void 0; } if (unionType.keyPropertyName === void 0) { - const keyPropertyName = forEach(types, (t) => t.flags & (524288 /* Object */ | 58982400 /* InstantiableNonPrimitive */) ? forEach(getPropertiesOfType(t), (p) => isUnitType(getTypeOfSymbol(p)) ? p.escapedName : void 0) : void 0); + const keyPropertyName = forEach(types, t => t.flags & (524288 /* Object */ | 58982400 /* InstantiableNonPrimitive */) ? forEach(getPropertiesOfType(t), p => isUnitType(getTypeOfSymbol(p)) ? p.escapedName : void 0) : void 0); const mapByKeyProperty = keyPropertyName && mapTypesByKeyProperty(types, keyPropertyName); unionType.keyPropertyName = mapByKeyProperty ? keyPropertyName : ""; unionType.constituentMap = mapByKeyProperty; @@ -67337,7 +62506,7 @@ ${lanes.join("\n")} } function getMatchingUnionConstituentForObjectLiteral(unionType, node) { const keyPropertyName = getKeyPropertyName(unionType); - const propNode = keyPropertyName && find(node.properties, (p) => p.symbol && p.kind === 303 /* PropertyAssignment */ && p.symbol.escapedName === keyPropertyName && isPossiblyDiscriminantValue(p.initializer)); + const propNode = keyPropertyName && find(node.properties, p => p.symbol && p.kind === 303 /* PropertyAssignment */ && p.symbol.escapedName === keyPropertyName && isPossiblyDiscriminantValue(p.initializer)); const propType = propNode && getContextFreeTypeOfExpression(propNode.initializer); return propType && getConstituentTypeForKeyType(unionType, propType); } @@ -67376,6 +62545,7 @@ ${lanes.join("\n")} return false; } function getAssignmentReducedType(declaredType, assignedType) { + var _getCachedType2; if (declaredType === assignedType) { return declaredType; } @@ -67383,10 +62553,10 @@ ${lanes.join("\n")} return assignedType; } const key = `A${getTypeId(declaredType)},${getTypeId(assignedType)}`; - return getCachedType(key) ?? setCachedType(key, getAssignmentReducedTypeWorker(declaredType, assignedType)); + return (_getCachedType2 = getCachedType(key)) !== null && _getCachedType2 !== void 0 ? _getCachedType2 : setCachedType(key, getAssignmentReducedTypeWorker(declaredType, assignedType)); } function getAssignmentReducedTypeWorker(declaredType, assignedType) { - const filteredType = filterType(declaredType, (t) => typeMaybeAssignableTo(assignedType, t)); + const filteredType = filterType(declaredType, t => typeMaybeAssignableTo(assignedType, t)); const reducedType = assignedType.flags & 512 /* BooleanLiteral */ && isFreshLiteralType(assignedType) ? mapType(filteredType, getFreshTypeOfLiteralType) : filteredType; return isTypeAssignableTo(assignedType, reducedType) ? reducedType : declaredType; } @@ -67408,30 +62578,38 @@ ${lanes.join("\n")} if (flags & (4 /* String */ | 268435456 /* StringMapping */)) { return strictNullChecks ? 16317953 /* StringStrictFacts */ : 16776705 /* StringFacts */; } + if (flags & (128 /* StringLiteral */ | 134217728 /* TemplateLiteral */)) { const isEmpty = flags & 128 /* StringLiteral */ && type.value === ""; return strictNullChecks ? isEmpty ? 12123649 /* EmptyStringStrictFacts */ : 7929345 /* NonEmptyStringStrictFacts */ : isEmpty ? 12582401 /* EmptyStringFacts */ : 16776705 /* NonEmptyStringFacts */; } + if (flags & (8 /* Number */ | 32 /* Enum */)) { return strictNullChecks ? 16317698 /* NumberStrictFacts */ : 16776450 /* NumberFacts */; } + if (flags & 256 /* NumberLiteral */) { const isZero = type.value === 0; return strictNullChecks ? isZero ? 12123394 /* ZeroNumberStrictFacts */ : 7929090 /* NonZeroNumberStrictFacts */ : isZero ? 12582146 /* ZeroNumberFacts */ : 16776450 /* NonZeroNumberFacts */; } + if (flags & 64 /* BigInt */) { return strictNullChecks ? 16317188 /* BigIntStrictFacts */ : 16775940 /* BigIntFacts */; } + if (flags & 2048 /* BigIntLiteral */) { const isZero = isZeroBigInt(type); return strictNullChecks ? isZero ? 12122884 /* ZeroBigIntStrictFacts */ : 7928580 /* NonZeroBigIntStrictFacts */ : isZero ? 12581636 /* ZeroBigIntFacts */ : 16775940 /* NonZeroBigIntFacts */; } + if (flags & 16 /* Boolean */) { return strictNullChecks ? 16316168 /* BooleanStrictFacts */ : 16774920 /* BooleanFacts */; } + if (flags & 528 /* BooleanLike */) { return strictNullChecks ? type === falseType || type === regularFalseType ? 12121864 /* FalseStrictFacts */ : 7927560 /* TrueStrictFacts */ : type === falseType || type === regularFalseType ? 12580616 /* FalseFacts */ : 16774920 /* TrueFacts */; } + if (flags & 524288 /* Object */) { const possibleFacts = strictNullChecks ? 83427327 /* EmptyObjectStrictFacts */ | 7880640 /* FunctionStrictFacts */ | 7888800 /* ObjectStrictFacts */ : 83886079 /* EmptyObjectFacts */ | 16728e3 /* FunctionFacts */ | 16736160 /* ObjectFacts */; if ((callerOnlyNeeds & possibleFacts) === 0) { @@ -67439,32 +62617,41 @@ ${lanes.join("\n")} } return getObjectFlags(type) & 16 /* Anonymous */ && isEmptyObjectType(type) ? strictNullChecks ? 83427327 /* EmptyObjectStrictFacts */ : 83886079 /* EmptyObjectFacts */ : isFunctionObjectType(type) ? strictNullChecks ? 7880640 /* FunctionStrictFacts */ : 16728e3 /* FunctionFacts */ : strictNullChecks ? 7888800 /* ObjectStrictFacts */ : 16736160 /* ObjectFacts */; } + if (flags & 16384 /* Void */) { return 9830144 /* VoidFacts */; } + if (flags & 32768 /* Undefined */) { return 26607360 /* UndefinedFacts */; } + if (flags & 65536 /* Null */) { return 42917664 /* NullFacts */; } + if (flags & 12288 /* ESSymbolLike */) { return strictNullChecks ? 7925520 /* SymbolStrictFacts */ : 16772880 /* SymbolFacts */; } + if (flags & 67108864 /* NonPrimitive */) { return strictNullChecks ? 7888800 /* ObjectStrictFacts */ : 16736160 /* ObjectFacts */; } + if (flags & 131072 /* Never */) { return 0 /* None */; } + if (flags & 1048576 /* Union */) { return reduceLeft(type.types, (facts, t) => facts | getTypeFactsWorker(t, callerOnlyNeeds), 0 /* None */); } + if (flags & 2097152 /* Intersection */) { return getIntersectionTypeFacts(type, callerOnlyNeeds); } return 83886079 /* UnknownFacts */; } + function getIntersectionTypeFacts(type, callerOnlyNeeds) { const ignoreObjects = maybeTypeOfKind(type, 402784252 /* Primitive */); let oredFacts = 0 /* None */; @@ -67478,20 +62665,21 @@ ${lanes.join("\n")} } return oredFacts & 8256 /* OrFactsMask */ | andedFacts & 134209471 /* AndFactsMask */; } + function getTypeWithFacts(type, include) { - return filterType(type, (t) => hasTypeFacts(t, include)); + return filterType(type, t => hasTypeFacts(t, include)); } function getAdjustedTypeWithFacts(type, facts) { const reduced = recombineUnknownType(getTypeWithFacts(strictNullChecks && type.flags & 2 /* Unknown */ ? unknownUnionType : type, facts)); if (strictNullChecks) { switch (facts) { case 524288 /* NEUndefined */: - return mapType(reduced, (t) => hasTypeFacts(t, 65536 /* EQUndefined */) ? getIntersectionType([t, hasTypeFacts(t, 131072 /* EQNull */) && !maybeTypeOfKind(reduced, 65536 /* Null */) ? getUnionType([emptyObjectType, nullType]) : emptyObjectType]) : t); + return mapType(reduced, t => hasTypeFacts(t, 65536 /* EQUndefined */) ? getIntersectionType([t, hasTypeFacts(t, 131072 /* EQNull */) && !maybeTypeOfKind(reduced, 65536 /* Null */) ? getUnionType([emptyObjectType, nullType]) : emptyObjectType]) : t); case 1048576 /* NENull */: - return mapType(reduced, (t) => hasTypeFacts(t, 131072 /* EQNull */) ? getIntersectionType([t, hasTypeFacts(t, 65536 /* EQUndefined */) && !maybeTypeOfKind(reduced, 32768 /* Undefined */) ? getUnionType([emptyObjectType, undefinedType]) : emptyObjectType]) : t); + return mapType(reduced, t => hasTypeFacts(t, 131072 /* EQNull */) ? getIntersectionType([t, hasTypeFacts(t, 65536 /* EQUndefined */) && !maybeTypeOfKind(reduced, 32768 /* Undefined */) ? getUnionType([emptyObjectType, undefinedType]) : emptyObjectType]) : t); case 2097152 /* NEUndefinedOrNull */: case 4194304 /* Truthy */: - return mapType(reduced, (t) => hasTypeFacts(t, 262144 /* EQUndefinedOrNull */) ? getGlobalNonNullableTypeInstantiation(t) : t); + return mapType(reduced, t => hasTypeFacts(t, 262144 /* EQUndefinedOrNull */) ? getGlobalNonNullableTypeInstantiation(t) : t); } } return reduced; @@ -67505,33 +62693,21 @@ ${lanes.join("\n")} 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; } function getTypeOfDestructuredArrayElement(type, index) { - return everyType(type, isTupleLikeType) && getTupleElementType(type, index) || includeUndefinedInIndexSignature(checkIteratedTypeOrElementType( - 65 /* Destructuring */, - type, - undefinedType, - /*errorNode*/ - void 0 - )) || errorType; + return everyType(type, isTupleLikeType) && getTupleElementType(type, index) || includeUndefinedInIndexSignature(checkIteratedTypeOrElementType(65 /* Destructuring */, type, undefinedType, /*errorNode*/ + void 0)) || errorType; } function includeUndefinedInIndexSignature(type) { - if (!type) - return type; + if (!type) return type; return compilerOptions.noUncheckedIndexedAccess ? getUnionType([type, missingType]) : type; } function getTypeOfDestructuredSpreadExpression(type) { - return createArrayType(checkIteratedTypeOrElementType( - 65 /* Destructuring */, - type, - undefinedType, - /*errorNode*/ - void 0 - ) || errorType); + return createArrayType(checkIteratedTypeOrElementType(65 /* Destructuring */, type, undefinedType, /*errorNode*/ + void 0) || errorType); } function getAssignedTypeOfBinaryExpression(node) { const isDestructuringDefaultAssignment = node.parent.kind === 209 /* ArrayLiteralExpression */ && isDestructuringAssignmentTarget(node.parent) || node.parent.kind === 303 /* PropertyAssignment */ && isDestructuringAssignmentTarget(node.parent.parent); @@ -67553,7 +62729,9 @@ ${lanes.join("\n")} return getTypeWithDefault(getAssignedTypeOfPropertyAssignment(node), node.objectAssignmentInitializer); } function getAssignedType(node) { - const { parent: parent2 } = node; + const { + parent: parent2 + } = node; switch (parent2.kind) { case 249 /* ForInStatement */: return stringType; @@ -67620,7 +62798,9 @@ ${lanes.join("\n")} return node; } function getReferenceRoot(node) { - const { parent: parent2 } = node; + const { + parent: parent2 + } = node; return parent2.kind === 217 /* ParenthesizedExpression */ || parent2.kind === 226 /* BinaryExpression */ && parent2.operatorToken.kind === 64 /* EqualsToken */ && parent2.left === node || parent2.kind === 226 /* BinaryExpression */ && parent2.operatorToken.kind === 28 /* CommaToken */ && parent2.right === node ? getReferenceRoot(parent2) : node; } function getTypeOfSwitchClause(clause) { @@ -67640,7 +62820,7 @@ ${lanes.join("\n")} return links.switchTypes; } function getSwitchClauseTypeOfWitnesses(switchStatement) { - if (some(switchStatement.caseBlock.clauses, (clause) => clause.kind === 296 /* CaseClause */ && !isStringLiteralLike(clause.expression))) { + if (some(switchStatement.caseBlock.clauses, clause => clause.kind === 296 /* CaseClause */ && !isStringLiteralLike(clause.expression))) { return void 0; } const witnesses = []; @@ -67651,7 +62831,7 @@ ${lanes.join("\n")} return witnesses; } function eachTypeContainedIn(source, types) { - return source.flags & 1048576 /* Union */ ? !forEach(source.types, (t) => !contains(types, t)) : contains(types, source); + return source.flags & 1048576 /* Union */ ? !forEach(source.types, t => !contains(types, t)) : contains(types, source); } function isTypeSubsetOf(source, target) { return !!(source === target || source.flags & 131072 /* Never */ || target.flags & 1048576 /* Union */ && isTypeSubsetOfUnion(source, target)); @@ -67693,7 +62873,7 @@ ${lanes.join("\n")} let newOrigin; if (origin && origin.flags & 1048576 /* Union */) { const originTypes = origin.types; - const originFiltered = filter(originTypes, (t) => !!(t.flags & 1048576 /* Union */) || f(t)); + const originFiltered = filter(originTypes, t => !!(t.flags & 1048576 /* Union */) || f(t)); if (originTypes.length - originFiltered.length === types.length - filtered.length) { if (originFiltered.length === 1) { return originFiltered[0]; @@ -67701,20 +62881,14 @@ ${lanes.join("\n")} newOrigin = createOriginUnionOrIntersectionType(1048576 /* Union */, originFiltered); } } - return getUnionTypeFromSortedList( - filtered, - type.objectFlags & (32768 /* PrimitiveUnion */ | 16777216 /* ContainsIntersections */), - /*aliasSymbol*/ - void 0, - /*aliasTypeArguments*/ - void 0, - newOrigin - ); + return getUnionTypeFromSortedList(filtered, type.objectFlags & (32768 /* PrimitiveUnion */ | 16777216 /* ContainsIntersections */), /*aliasSymbol*/ + void 0, /*aliasTypeArguments*/ + void 0, newOrigin); } return type.flags & 131072 /* Never */ || f(type) ? type : neverType; } function removeType(type, targetType) { - return filterType(type, (t) => t !== targetType); + return filterType(type, t => t !== targetType); } function countTypes(type) { return type.flags & 1048576 /* Union */ ? type.types.length : 1; @@ -67747,11 +62921,11 @@ ${lanes.join("\n")} return type.flags & 1048576 /* Union */ && aliasSymbol ? getUnionType(map(type.types, mapper), 1 /* Literal */, aliasSymbol, aliasTypeArguments) : mapType(type, mapper); } function extractTypesOfKind(type, kind) { - return filterType(type, (t) => (t.flags & kind) !== 0); + return filterType(type, t => (t.flags & kind) !== 0); } function replacePrimitivesWithLiterals(typeWithPrimitives, typeWithLiterals) { if (maybeTypeOfKind(typeWithPrimitives, 4 /* String */ | 134217728 /* TemplateLiteral */ | 8 /* Number */ | 64 /* BigInt */) && maybeTypeOfKind(typeWithLiterals, 128 /* StringLiteral */ | 134217728 /* TemplateLiteral */ | 268435456 /* StringMapping */ | 256 /* NumberLiteral */ | 2048 /* BigIntLiteral */)) { - return mapType(typeWithPrimitives, (t) => t.flags & 4 /* String */ ? extractTypesOfKind(typeWithLiterals, 4 /* String */ | 128 /* StringLiteral */ | 134217728 /* TemplateLiteral */ | 268435456 /* StringMapping */) : isPatternLiteralType(t) && !maybeTypeOfKind(typeWithLiterals, 4 /* String */ | 134217728 /* TemplateLiteral */ | 268435456 /* StringMapping */) ? extractTypesOfKind(typeWithLiterals, 128 /* StringLiteral */) : t.flags & 8 /* Number */ ? extractTypesOfKind(typeWithLiterals, 8 /* Number */ | 256 /* NumberLiteral */) : t.flags & 64 /* BigInt */ ? extractTypesOfKind(typeWithLiterals, 64 /* BigInt */ | 2048 /* BigIntLiteral */) : t); + return mapType(typeWithPrimitives, t => t.flags & 4 /* String */ ? extractTypesOfKind(typeWithLiterals, 4 /* String */ | 128 /* StringLiteral */ | 134217728 /* TemplateLiteral */ | 268435456 /* StringMapping */) : isPatternLiteralType(t) && !maybeTypeOfKind(typeWithLiterals, 4 /* String */ | 134217728 /* TemplateLiteral */ | 268435456 /* StringMapping */) ? extractTypesOfKind(typeWithLiterals, 128 /* StringLiteral */) : t.flags & 8 /* Number */ ? extractTypesOfKind(typeWithLiterals, 8 /* Number */ | 256 /* NumberLiteral */) : t.flags & 64 /* BigInt */ ? extractTypesOfKind(typeWithLiterals, 64 /* BigInt */ | 2048 /* BigIntLiteral */) : t); } return typeWithPrimitives; } @@ -67762,7 +62936,10 @@ ${lanes.join("\n")} return flowType.flags === 0 ? flowType.type : flowType; } function createFlowType(type, incomplete) { - return incomplete ? { flags: 0, type: type.flags & 131072 /* Never */ ? silentNeverType : type } : type; + return incomplete ? { + flags: 0, + type: type.flags & 131072 /* Never */ ? silentNeverType : type + } : type; } function createEvolvingArrayType(elementType) { const result = createObjectType(256 /* EvolvingArray */); @@ -67777,9 +62954,7 @@ ${lanes.join("\n")} return isTypeSubsetOf(elementType, evolvingArrayType.elementType) ? evolvingArrayType : getEvolvingArrayType(getUnionType([evolvingArrayType.elementType, elementType])); } function createFinalArrayType(elementType) { - return elementType.flags & 131072 /* Never */ ? autoArrayType : createArrayType( - elementType.flags & 1048576 /* Union */ ? getUnionType(elementType.types, 2 /* Subtype */) : elementType - ); + return elementType.flags & 131072 /* Never */ ? autoArrayType : createArrayType(elementType.flags & 1048576 /* Union */ ? getUnionType(elementType.types, 2 /* Subtype */) : elementType); } function getFinalArrayType(evolvingArrayType) { return evolvingArrayType.finalArrayType || (evolvingArrayType.finalArrayType = createFinalArrayType(evolvingArrayType.elementType)); @@ -67831,20 +63006,12 @@ ${lanes.join("\n")} } if (isVariableDeclaration(declaration) && declaration.parent.parent.kind === 250 /* ForOfStatement */) { const statement = declaration.parent.parent; - const expressionType = getTypeOfDottedName( - statement.expression, - /*diagnostic*/ - void 0 - ); + const expressionType = getTypeOfDottedName(statement.expression, /*diagnostic*/ + void 0); if (expressionType) { const use = statement.awaitModifier ? 15 /* ForAwaitOf */ : 13 /* ForOf */; - return checkIteratedTypeOrElementType( - use, - expressionType, - undefinedType, - /*errorNode*/ - void 0 - ); + return checkIteratedTypeOrElementType(use, expressionType, undefinedType, /*errorNode*/ + void 0); } } if (diagnostic) { @@ -67863,23 +63030,24 @@ ${lanes.join("\n")} return getExplicitThisType(node); case 108 /* SuperKeyword */: return checkSuperExpression(node); - case 211 /* PropertyAccessExpression */: { - const type = getTypeOfDottedName(node.expression, diagnostic); - if (type) { - const name = node.name; - let prop; - if (isPrivateIdentifier(name)) { - if (!type.symbol) { - return void 0; + case 211 /* PropertyAccessExpression */: + { + const type = getTypeOfDottedName(node.expression, diagnostic); + if (type) { + const name = node.name; + let prop; + if (isPrivateIdentifier(name)) { + if (!type.symbol) { + return void 0; + } + prop = getPropertyOfType(type, getSymbolNameForPrivateIdentifier(type.symbol, name.escapedText)); + } else { + prop = getPropertyOfType(type, name.escapedText); } - prop = getPropertyOfType(type, getSymbolNameForPrivateIdentifier(type.symbol, name.escapedText)); - } else { - prop = getPropertyOfType(type, name.escapedText); + return prop && getExplicitTypeOfSymbol(prop, diagnostic); } - return prop && getExplicitTypeOfSymbol(prop, diagnostic); + return void 0; } - return void 0; - } case 217 /* ParenthesizedExpression */: return getTypeOfDottedName(node.expression, diagnostic); } @@ -67894,17 +63062,11 @@ ${lanes.join("\n")} const rightType = checkNonNullExpression(node.right); funcType = getSymbolHasInstanceMethodOfObjectType(rightType); } else if (node.parent.kind === 244 /* ExpressionStatement */) { - funcType = getTypeOfDottedName( - node.expression, - /*diagnostic*/ - void 0 - ); + funcType = getTypeOfDottedName(node.expression, /*diagnostic*/ + void 0); } else if (node.expression.kind !== 108 /* SuperKeyword */) { if (isOptionalChain(node)) { - funcType = checkNonNullType( - getOptionalExpressionType(checkExpression(node.expression), node.expression), - node.expression - ); + funcType = checkNonNullType(getOptionalExpressionType(checkExpression(node.expression), node.expression), node.expression); } else { funcType = checkNonNullExpression(node.expression); } @@ -67918,6 +63080,7 @@ ${lanes.join("\n")} function hasTypePredicateOrNeverReturnType(signature) { return !!(getTypePredicateOfSignature(signature) || signature.declaration && (getReturnTypeFromAnnotation(signature.declaration) || unknownType).flags & 131072 /* Never */); } + function getTypePredicateArgument(predicate, callExpression) { if (predicate.kind === 1 /* Identifier */ || predicate.kind === 3 /* AssertsIdentifier */) { return callExpression.arguments[predicate.parameterIndex]; @@ -67932,21 +63095,15 @@ ${lanes.join("\n")} diagnostics.add(createFileDiagnostic(sourceFile, span.start, span.length, Diagnostics.The_containing_function_or_module_body_is_too_large_for_control_flow_analysis)); } function isReachableFlowNode(flow) { - const result = isReachableFlowNodeWorker( - flow, - /*noCacheCheck*/ - false - ); + const result = isReachableFlowNodeWorker(flow, /*noCacheCheck*/ + false); lastFlowNode = flow; lastFlowNodeReachable = result; return result; } function isFalseExpression(expr) { - const node = skipParentheses( - expr, - /*excludeJSDocTypeAssertions*/ - true - ); + const node = skipParentheses(expr, /*excludeJSDocTypeAssertions*/ + true); return node.kind === 97 /* FalseKeyword */ || node.kind === 226 /* BinaryExpression */ && (node.operatorToken.kind === 56 /* AmpersandAmpersandToken */ && (isFalseExpression(node.left) || isFalseExpression(node.right)) || node.operatorToken.kind === 57 /* BarBarToken */ && isFalseExpression(node.left) && isFalseExpression(node.right)); } function isReachableFlowNodeWorker(flow, noCacheCheck) { @@ -67959,11 +63116,8 @@ ${lanes.join("\n")} if (!noCacheCheck) { const id = getFlowNodeId(flow); const reachable = flowNodeReachable[id]; - return reachable !== void 0 ? reachable : flowNodeReachable[id] = isReachableFlowNodeWorker( - flow, - /*noCacheCheck*/ - true - ); + return reachable !== void 0 ? reachable : flowNodeReachable[id] = isReachableFlowNodeWorker(flow, /*noCacheCheck*/ + true); } noCacheCheck = false; } @@ -67985,11 +63139,8 @@ ${lanes.join("\n")} } flow = flow.antecedent; } else if (flags & 4 /* BranchLabel */) { - return some(flow.antecedents, (f) => isReachableFlowNodeWorker( - f, - /*noCacheCheck*/ - false - )); + return some(flow.antecedents, f => isReachableFlowNodeWorker(f, /*noCacheCheck*/ + false)); } else if (flags & 8 /* LoopLabel */) { const antecedents = flow.antecedents; if (antecedents === void 0 || antecedents.length === 0) { @@ -68006,11 +63157,8 @@ ${lanes.join("\n")} const target = flow.target; const saveAntecedents = target.antecedents; target.antecedents = flow.antecedents; - const result = isReachableFlowNodeWorker( - flow.antecedent, - /*noCacheCheck*/ - false - ); + const result = isReachableFlowNodeWorker(flow.antecedent, /*noCacheCheck*/ + false); target.antecedents = saveAntecedents; return result; } else { @@ -68018,6 +63166,7 @@ ${lanes.join("\n")} } } } + function isPostSuperFlowNode(flow, noCacheCheck) { while (true) { const flags = flow.flags; @@ -68025,11 +63174,8 @@ ${lanes.join("\n")} if (!noCacheCheck) { const id = getFlowNodeId(flow); const postSuper = flowNodePostSuper[id]; - return postSuper !== void 0 ? postSuper : flowNodePostSuper[id] = isPostSuperFlowNode( - flow, - /*noCacheCheck*/ - true - ); + return postSuper !== void 0 ? postSuper : flowNodePostSuper[id] = isPostSuperFlowNode(flow, /*noCacheCheck*/ + true); } noCacheCheck = false; } @@ -68041,22 +63187,16 @@ ${lanes.join("\n")} } flow = flow.antecedent; } else if (flags & 4 /* BranchLabel */) { - return every(flow.antecedents, (f) => isPostSuperFlowNode( - f, - /*noCacheCheck*/ - false - )); + return every(flow.antecedents, f => isPostSuperFlowNode(f, /*noCacheCheck*/ + false)); } else if (flags & 8 /* LoopLabel */) { flow = flow.antecedents[0]; } else if (flags & 1024 /* ReduceLabel */) { const target = flow.target; const saveAntecedents = target.antecedents; target.antecedents = flow.antecedents; - const result = isPostSuperFlowNode( - flow.antecedent, - /*noCacheCheck*/ - false - ); + const result = isPostSuperFlowNode(flow.antecedent, /*noCacheCheck*/ + false); target.antecedents = saveAntecedents; return result; } else { @@ -68064,6 +63204,7 @@ ${lanes.join("\n")} } } } + function isConstantReference(node) { switch (node.kind) { case 110 /* ThisKeyword */: @@ -68080,7 +63221,7 @@ ${lanes.join("\n")} } return false; } - function getFlowTypeOfReference(reference, declaredType, initialType = declaredType, flowContainer, flowNode = ((_a) => (_a = tryCast(reference, canHaveFlowNode)) == null ? void 0 : _a.flowNode)()) { + function getFlowTypeOfReference(reference, declaredType, initialType = declaredType, flowContainer, flowNode = (_a => (_a = tryCast(reference, canHaveFlowNode)) == null ? void 0 : _a.flowNode)()) { let key; let isKeySet = false; let flowDepth = 0; @@ -68109,7 +63250,9 @@ ${lanes.join("\n")} function getTypeAtFlowNode(flow) { var _a2; if (flowDepth === 2e3) { - (_a2 = tracing) == null ? void 0 : _a2.instant(tracing.Phase.CheckTypes, "getTypeAtFlowNode_DepthLimit", { flowId: flow.id }); + (_a2 = tracing) == null ? void 0 : _a2.instant(tracing.Phase.CheckTypes, "getTypeAtFlowNode_DepthLimit", { + flowId: flow.id + }); flowAnalysisDisabled = true; reportFlowControlError(reference); return errorType; @@ -68183,10 +63326,7 @@ ${lanes.join("\n")} } function getInitialOrAssignedType(flow) { const node = flow.node; - return getNarrowableTypeForReference( - node.kind === 260 /* VariableDeclaration */ || node.kind === 208 /* BindingElement */ ? getInitialType(node) : getAssignedType(node), - reference - ); + return getNarrowableTypeForReference(node.kind === 260 /* VariableDeclaration */ || node.kind === 208 /* BindingElement */ ? getInitialType(node) : getAssignedType(node), reference); } function getTypeAtFlowAssignment(flow) { const node = flow.node; @@ -68229,11 +63369,8 @@ ${lanes.join("\n")} return void 0; } function narrowTypeByAssertion(type, expr) { - const node = skipParentheses( - expr, - /*excludeJSDocTypeAssertions*/ - true - ); + const node = skipParentheses(expr, /*excludeJSDocTypeAssertions*/ + true); if (node.kind === 97 /* FalseKeyword */) { return unreachableNeverType; } @@ -68245,12 +63382,8 @@ ${lanes.join("\n")} return getUnionType([narrowTypeByAssertion(type, node.left), narrowTypeByAssertion(type, node.right)]); } } - return narrowType( - type, - node, - /*assumeTrue*/ - true - ); + return narrowType(type, node, /*assumeTrue*/ + true); } function getTypeAtFlowCall(flow) { const signature = getEffectsSignature(flow.node); @@ -68259,13 +63392,8 @@ ${lanes.join("\n")} if (predicate && (predicate.kind === 2 /* AssertsThis */ || predicate.kind === 3 /* AssertsIdentifier */)) { const flowType = getTypeAtFlowNode(flow.antecedent); const type = finalizeEvolvingArrayType(getTypeFromFlowType(flowType)); - const narrowedType = predicate.type ? narrowTypeByTypePredicate( - type, - predicate, - flow.node, - /*assumeTrue*/ - true - ) : predicate.kind === 3 /* AssertsIdentifier */ && predicate.parameterIndex >= 0 && predicate.parameterIndex < flow.node.arguments.length ? narrowTypeByAssertion(type, flow.node.arguments[predicate.parameterIndex]) : type; + const narrowedType = predicate.type ? narrowTypeByTypePredicate(type, predicate, flow.node, /*assumeTrue*/ + true) : predicate.kind === 3 /* AssertsIdentifier */ && predicate.parameterIndex >= 0 && predicate.parameterIndex < flow.node.arguments.length ? narrowTypeByAssertion(type, flow.node.arguments[predicate.parameterIndex]) : type; return narrowedType === type ? flowType : createFlowType(narrowedType, isIncomplete(flowType)); } if (getReturnTypeOfSignature(signature).flags & 131072 /* Never */) { @@ -68327,9 +63455,9 @@ ${lanes.join("\n")} } else { if (strictNullChecks) { if (optionalChainContainsReference(expr, reference)) { - type = narrowTypeBySwitchOptionalChainContainment(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd, (t) => !(t.flags & (32768 /* Undefined */ | 131072 /* Never */))); + type = narrowTypeBySwitchOptionalChainContainment(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd, t => !(t.flags & (32768 /* Undefined */ | 131072 /* Never */))); } else if (expr.kind === 221 /* TypeOfExpression */ && optionalChainContainsReference(expr.expression, reference)) { - type = narrowTypeBySwitchOptionalChainContainment(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd, (t) => !(t.flags & 131072 /* Never */ || t.flags & 128 /* StringLiteral */ && t.value === "undefined")); + type = narrowTypeBySwitchOptionalChainContainment(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd, t => !(t.flags & 131072 /* Never */ || t.flags & 128 /* StringLiteral */ && t.value === "undefined")); } } const access = getDiscriminantPropertyAccess(expr, type); @@ -68382,7 +63510,7 @@ ${lanes.join("\n")} } function getTypeAtFlowLoopLabel(flow) { const id = getFlowNodeId(flow); - const cache = flowLoopCaches[id] || (flowLoopCaches[id] = /* @__PURE__ */ new Map()); + const cache = flowLoopCaches[id] || (flowLoopCaches[id] = /* @__PURE__ */new Map()); const key2 = getOrSetCacheKey(); if (!key2) { return declaredType; @@ -68393,11 +63521,8 @@ ${lanes.join("\n")} } for (let i = flowLoopStart; i < flowLoopCount; i++) { if (flowLoopNodes[i] === flow && flowLoopKeys[i] === key2 && flowLoopTypes[i].length) { - return createFlowType( - getUnionOrEvolvingArrayType(flowLoopTypes[i], 1 /* Literal */), - /*incomplete*/ - true - ); + return createFlowType(getUnionOrEvolvingArrayType(flowLoopTypes[i], 1 /* Literal */), /*incomplete*/ + true); } } const antecedentTypes = []; @@ -68433,11 +63558,8 @@ ${lanes.join("\n")} } const result = getUnionOrEvolvingArrayType(antecedentTypes, subtypeReduction ? 2 /* Subtype */ : 1 /* Literal */); if (isIncomplete(firstAntecedentType)) { - return createFlowType( - result, - /*incomplete*/ - true - ); + return createFlowType(result, /*incomplete*/ + true); } cache.set(key2, result); return result; @@ -68510,7 +63632,7 @@ ${lanes.join("\n")} } propType = removeNullable && optionalChain ? getOptionalType(propType) : propType; const narrowedPropType = narrowType2(propType); - return filterType(type, (t) => { + return filterType(type, t => { const discriminantType = getTypeOfPropertyOrIndexSignatureOfType(t, propName) || unknownType; return !(discriminantType.flags & 131072 /* Never */) && !(narrowedPropType.flags & 131072 /* Never */) && areTypesComparable(narrowedPropType, discriminantType); }); @@ -68525,29 +63647,32 @@ ${lanes.join("\n")} } } } - return narrowTypeByDiscriminant(type, access, (t) => narrowTypeByEquality(t, operator, value, assumeTrue)); + return narrowTypeByDiscriminant(type, access, t => narrowTypeByEquality(t, operator, value, assumeTrue)); } function narrowTypeBySwitchOnDiscriminantProperty(type, access, switchStatement, clauseStart, clauseEnd) { if (clauseStart < clauseEnd && type.flags & 1048576 /* Union */ && getKeyPropertyName(type) === getAccessedPropertyName(access)) { const clauseTypes = getSwitchClauseTypes(switchStatement).slice(clauseStart, clauseEnd); - const candidate = getUnionType(map(clauseTypes, (t) => getConstituentTypeForKeyType(type, t) || unknownType)); + const candidate = getUnionType(map(clauseTypes, t => getConstituentTypeForKeyType(type, t) || unknownType)); if (candidate !== unknownType) { return candidate; } } - return narrowTypeByDiscriminant(type, access, (t) => narrowTypeBySwitchOnDiscriminant(t, switchStatement, clauseStart, clauseEnd)); + return narrowTypeByDiscriminant(type, access, t => narrowTypeBySwitchOnDiscriminant(t, switchStatement, clauseStart, clauseEnd)); } function narrowTypeByTruthiness(type, expr, assumeTrue) { if (isMatchingReference(reference, expr)) { return getAdjustedTypeWithFacts(type, assumeTrue ? 4194304 /* Truthy */ : 8388608 /* Falsy */); } + if (strictNullChecks && assumeTrue && optionalChainContainsReference(expr, reference)) { type = getAdjustedTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */); } + const access = getDiscriminantPropertyAccess(expr, type); if (access) { - return narrowTypeByDiscriminant(type, access, (t) => getTypeWithFacts(t, assumeTrue ? 4194304 /* Truthy */ : 8388608 /* Falsy */)); + return narrowTypeByDiscriminant(type, access, t => getTypeWithFacts(t, assumeTrue ? 4194304 /* Truthy */ : 8388608 /* Falsy */)); } + return type; } function isTypePresencePossible(type, propName, assumeTrue) { @@ -68556,14 +63681,10 @@ ${lanes.join("\n")} } function narrowTypeByInKeyword(type, nameType, assumeTrue) { const name = getPropertyNameFromType(nameType); - const isKnownProperty2 = someType(type, (t) => isTypePresencePossible( - t, - name, - /*assumeTrue*/ - true - )); + const isKnownProperty2 = someType(type, t => isTypePresencePossible(t, name, /*assumeTrue*/ + true)); if (isKnownProperty2) { - return filterType(type, (t) => isTypePresencePossible(t, name, assumeTrue)); + return filterType(type, t => isTypePresencePossible(t, name, assumeTrue)); } if (assumeTrue) { const recordSymbol = getGlobalRecordSymbol(); @@ -68644,6 +63765,7 @@ ${lanes.join("\n")} return getTypeWithFacts(type, assumeTrue ? 524288 /* NEUndefined */ : 65536 /* EQUndefined */); } } + if (isMatchingReference(reference, target)) { const leftType = getTypeOfExpression(expr.left); if (isTypeUsableAsPropertyName(leftType)) { @@ -68654,49 +63776,17 @@ ${lanes.join("\n")} case 28 /* CommaToken */: return narrowType(type, expr.right, assumeTrue); case 56 /* AmpersandAmpersandToken */: - return assumeTrue ? narrowType( - narrowType( - type, - expr.left, - /*assumeTrue*/ - true - ), - expr.right, - /*assumeTrue*/ - true - ) : getUnionType([narrowType( - type, - expr.left, - /*assumeTrue*/ - false - ), narrowType( - type, - expr.right, - /*assumeTrue*/ - false - )]); + return assumeTrue ? narrowType(narrowType(type, expr.left, /*assumeTrue*/ + true), expr.right, /*assumeTrue*/ + true) : getUnionType([narrowType(type, expr.left, /*assumeTrue*/ + false), narrowType(type, expr.right, /*assumeTrue*/ + false)]); case 57 /* BarBarToken */: - return assumeTrue ? getUnionType([narrowType( - type, - expr.left, - /*assumeTrue*/ - true - ), narrowType( - type, - expr.right, - /*assumeTrue*/ - true - )]) : narrowType( - narrowType( - type, - expr.left, - /*assumeTrue*/ - false - ), - expr.right, - /*assumeTrue*/ - false - ); + return assumeTrue ? getUnionType([narrowType(type, expr.left, /*assumeTrue*/ + true), narrowType(type, expr.right, /*assumeTrue*/ + true)]) : narrowType(narrowType(type, expr.left, /*assumeTrue*/ + false), expr.right, /*assumeTrue*/ + false); } return type; } @@ -68712,19 +63802,14 @@ ${lanes.join("\n")} } const classSymbol = symbol.parent; const targetType = hasStaticModifier(Debug.checkDefined(symbol.valueDeclaration, "should always have a declaration")) ? getTypeOfSymbol(classSymbol) : getDeclaredTypeOfSymbol(classSymbol); - return getNarrowedType( - type, - targetType, - assumeTrue, - /*checkDerived*/ - true - ); + return getNarrowedType(type, targetType, assumeTrue, /*checkDerived*/ + true); } function narrowTypeByOptionalChainContainment(type, operator, value, assumeTrue) { const equalsOperator = operator === 35 /* EqualsEqualsToken */ || operator === 37 /* EqualsEqualsEqualsToken */; const nullableFlags = operator === 35 /* EqualsEqualsToken */ || operator === 36 /* ExclamationEqualsToken */ ? 98304 /* Nullable */ : 32768 /* Undefined */; const valueType = getTypeOfExpression(value); - const removeNullable = equalsOperator !== assumeTrue && everyType(valueType, (t) => !!(t.flags & nullableFlags)) || equalsOperator === assumeTrue && everyType(valueType, (t) => !(t.flags & (3 /* AnyOrUnknown */ | nullableFlags))); + const removeNullable = equalsOperator !== assumeTrue && everyType(valueType, t => !!(t.flags & nullableFlags)) || equalsOperator === assumeTrue && everyType(valueType, t => !(t.flags & (3 /* AnyOrUnknown */ | nullableFlags))); return removeNullable ? getAdjustedTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */) : type; } function narrowTypeByEquality(type, operator, value, assumeTrue) { @@ -68752,11 +63837,11 @@ ${lanes.join("\n")} return nonPrimitiveType; } } - const filteredType = filterType(type, (t) => areTypesComparable(t, valueType) || doubleEquals && isCoercibleUnderDoubleEquals(t, valueType)); + const filteredType = filterType(type, t => areTypesComparable(t, valueType) || doubleEquals && isCoercibleUnderDoubleEquals(t, valueType)); return replacePrimitivesWithLiterals(filteredType, valueType); } if (isUnitType(valueType)) { - return filterType(type, (t) => !(isUnitLikeType(t) && areTypesComparable(t, valueType))); + return filterType(type, t => !(isUnitLikeType(t) && areTypesComparable(t, valueType))); } return type; } @@ -68769,9 +63854,10 @@ ${lanes.join("\n")} if (strictNullChecks && optionalChainContainsReference(target, reference) && assumeTrue === (literal.text !== "undefined")) { type = getAdjustedTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */); } + const propertyAccess = getDiscriminantPropertyAccess(target, type); if (propertyAccess) { - return narrowTypeByDiscriminant(type, propertyAccess, (t) => narrowTypeByLiteralExpression(t, literal, assumeTrue)); + return narrowTypeByDiscriminant(type, propertyAccess, t => narrowTypeByLiteralExpression(t, literal, assumeTrue)); } return type; } @@ -68780,6 +63866,7 @@ ${lanes.join("\n")} function narrowTypeByLiteralExpression(type, literal, assumeTrue) { return assumeTrue ? narrowTypeByTypeName(type, literal.text) : getAdjustedTypeWithFacts(type, typeofNEFacts.get(literal.text) || 32768 /* TypeofNEHostObject */); } + function narrowTypeBySwitchOptionalChainContainment(type, switchStatement, clauseStart, clauseEnd, clauseCheck) { const everyClauseChecks = clauseStart !== clauseEnd && every(getSwitchClauseTypes(switchStatement).slice(clauseStart, clauseEnd), clauseCheck); return everyClauseChecks ? getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */) : type; @@ -68811,11 +63898,11 @@ ${lanes.join("\n")} return getUnionType(groundClauseTypes === void 0 ? clauseTypes : groundClauseTypes); } const discriminantType = getUnionType(clauseTypes); - const caseType = discriminantType.flags & 131072 /* Never */ ? neverType : replacePrimitivesWithLiterals(filterType(type, (t) => areTypesComparable(discriminantType, t)), discriminantType); + const caseType = discriminantType.flags & 131072 /* Never */ ? neverType : replacePrimitivesWithLiterals(filterType(type, t => areTypesComparable(discriminantType, t)), discriminantType); 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, getRegularTypeOfLiteralType(extractUnitType(t))))); return caseType.flags & 131072 /* Never */ ? defaultType : getUnionType([caseType, defaultType]); } function narrowTypeByTypeName(type, typeName) { @@ -68837,75 +63924,62 @@ ${lanes.join("\n")} case "undefined": return narrowTypeByTypeFacts(type, undefinedType, 65536 /* EQUndefined */); } + return narrowTypeByTypeFacts(type, nonPrimitiveType, 128 /* TypeofEQHostObject */); } + function narrowTypeByTypeFacts(type, impliedType, facts) { - return mapType(type, (t) => ( - // We first check if a constituent is a subtype of the implied type. If so, we either keep or eliminate - // the constituent based on its type facts. We use the strict subtype relation because it treats `object` - // as a subtype of `{}`, and we need the type facts check because function types are subtypes of `object`, - // but are classified as "function" according to `typeof`. - isTypeRelatedTo(t, impliedType, strictSubtypeRelation) ? hasTypeFacts(t, facts) ? t : neverType : ( - // We next check if the consituent is a supertype of the implied type. If so, we substitute the implied - // type. This handles top types like `unknown` and `{}`, and supertypes like `{ toString(): string }`. - isTypeSubtypeOf(impliedType, t) ? impliedType : ( - // Neither the constituent nor the implied type is a subtype of the other, however their domains may still - // overlap. For example, an unconstrained type parameter and type `string`. If the type facts indicate - // possible overlap, we form an intersection. Otherwise, we eliminate the constituent. - hasTypeFacts(t, facts) ? getIntersectionType([t, impliedType]) : neverType - ) - ) - )); + return mapType(type, t => + // We first check if a constituent is a subtype of the implied type. If so, we either keep or eliminate + // the constituent based on its type facts. We use the strict subtype relation because it treats `object` + // as a subtype of `{}`, and we need the type facts check because function types are subtypes of `object`, + // but are classified as "function" according to `typeof`. + isTypeRelatedTo(t, impliedType, strictSubtypeRelation) ? hasTypeFacts(t, facts) ? t : neverType : + // We next check if the consituent is a supertype of the implied type. If so, we substitute the implied + // type. This handles top types like `unknown` and `{}`, and supertypes like `{ toString(): string }`. + isTypeSubtypeOf(impliedType, t) ? impliedType : + // Neither the constituent nor the implied type is a subtype of the other, however their domains may still + // overlap. For example, an unconstrained type parameter and type `string`. If the type facts indicate + // possible overlap, we form an intersection. Otherwise, we eliminate the constituent. + hasTypeFacts(t, facts) ? getIntersectionType([t, impliedType]) : neverType); } function narrowTypeBySwitchOnTypeOf(type, switchStatement, clauseStart, clauseEnd) { const witnesses = getSwitchClauseTypeOfWitnesses(switchStatement); if (!witnesses) { return type; } - const defaultIndex = findIndex(switchStatement.caseBlock.clauses, (clause) => clause.kind === 297 /* DefaultClause */); + const defaultIndex = findIndex(switchStatement.caseBlock.clauses, clause => clause.kind === 297 /* DefaultClause */); const hasDefaultClause = clauseStart === clauseEnd || defaultIndex >= clauseStart && defaultIndex < clauseEnd; if (hasDefaultClause) { const notEqualFacts = getNotEqualFactsFromTypeofSwitch(clauseStart, clauseEnd, witnesses); - return filterType(type, (t) => getTypeFacts(t, notEqualFacts) === notEqualFacts); + return filterType(type, t => getTypeFacts(t, notEqualFacts) === notEqualFacts); } const clauseWitnesses = witnesses.slice(clauseStart, clauseEnd); - return getUnionType(map(clauseWitnesses, (text) => text ? narrowTypeByTypeName(type, text) : neverType)); + return getUnionType(map(clauseWitnesses, text => text ? narrowTypeByTypeName(type, text) : neverType)); } function narrowTypeBySwitchOnTrue(type, switchStatement, clauseStart, clauseEnd) { - const defaultIndex = findIndex(switchStatement.caseBlock.clauses, (clause) => clause.kind === 297 /* DefaultClause */); + const defaultIndex = findIndex(switchStatement.caseBlock.clauses, clause => clause.kind === 297 /* DefaultClause */); const hasDefaultClause = clauseStart === clauseEnd || defaultIndex >= clauseStart && defaultIndex < clauseEnd; for (let i = 0; i < clauseStart; i++) { const clause = switchStatement.caseBlock.clauses[i]; if (clause.kind === 296 /* CaseClause */) { - type = narrowType( - type, - clause.expression, - /*assumeTrue*/ - false - ); + type = narrowType(type, clause.expression, /*assumeTrue*/ + false); } } if (hasDefaultClause) { for (let i = clauseEnd; i < switchStatement.caseBlock.clauses.length; i++) { const clause = switchStatement.caseBlock.clauses[i]; if (clause.kind === 296 /* CaseClause */) { - type = narrowType( - type, - clause.expression, - /*assumeTrue*/ - false - ); + type = narrowType(type, clause.expression, /*assumeTrue*/ + false); } } return type; } const clauses = switchStatement.caseBlock.clauses.slice(clauseStart, clauseEnd); - return getUnionType(map(clauses, (clause) => clause.kind === 296 /* CaseClause */ ? narrowType( - type, - clause.expression, - /*assumeTrue*/ - true - ) : neverType)); + return getUnionType(map(clauses, clause => clause.kind === 296 /* CaseClause */ ? narrowType(type, clause.expression, /*assumeTrue*/ + true) : neverType)); } function isMatchingConstructorReference(expr) { return (isPropertyAccessExpression(expr) && idText(expr.name) === "constructor" || isElementAccessExpression(expr) && isStringLiteralLike(expr.argumentExpression) && expr.argumentExpression.text === "constructor") && isMatchingReference(reference, expr.expression); @@ -68930,7 +64004,7 @@ ${lanes.join("\n")} if (isTypeAny(type)) { return candidate; } - return filterType(type, (t) => isConstructedBy(t, candidate)); + return filterType(type, t => isConstructedBy(t, candidate)); function isConstructedBy(source, target) { if (source.flags & 524288 /* Object */ && getObjectFlags(source) & 1 /* Class */ || target.flags & 524288 /* Object */ && getObjectFlags(target) & 1 /* Class */) { return source.symbol === target.symbol; @@ -68944,6 +64018,7 @@ ${lanes.join("\n")} if (assumeTrue && strictNullChecks && optionalChainContainsReference(left, reference)) { return getAdjustedTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */); } + return type; } const right = expr.right; @@ -68954,13 +64029,8 @@ ${lanes.join("\n")} const signature = getEffectsSignature(expr); const predicate = signature && getTypePredicateOfSignature(signature); if (predicate && predicate.kind === 1 /* Identifier */ && predicate.parameterIndex === 0) { - return getNarrowedType( - type, - predicate.type, - assumeTrue, - /*checkDerived*/ - true - ); + return getNarrowedType(type, predicate.type, assumeTrue, /*checkDerived*/ + true); } if (!isTypeDerivedFrom(rightType, globalFunctionType)) { return type; @@ -68969,13 +64039,8 @@ ${lanes.join("\n")} if (isTypeAny(type) && (instanceType === globalObjectType || instanceType === globalFunctionType) || !assumeTrue && !(instanceType.flags & 524288 /* Object */ && !isEmptyAnonymousObjectType(instanceType))) { return type; } - return getNarrowedType( - type, - instanceType, - assumeTrue, - /*checkDerived*/ - true - ); + return getNarrowedType(type, instanceType, assumeTrue, /*checkDerived*/ + true); } function getInstanceType(constructorType) { const prototypePropertyType = getTypeOfPropertyOfType(constructorType, "prototype"); @@ -68984,42 +64049,35 @@ ${lanes.join("\n")} } const constructSignatures = getSignaturesOfType(constructorType, 1 /* Construct */); if (constructSignatures.length) { - return getUnionType(map(constructSignatures, (signature) => getReturnTypeOfSignature(getErasedSignature(signature)))); + return getUnionType(map(constructSignatures, signature => getReturnTypeOfSignature(getErasedSignature(signature)))); } return emptyObjectType; } function getNarrowedType(type, candidate, assumeTrue, checkDerived) { + var _getCachedType3; const key2 = type.flags & 1048576 /* Union */ ? `N${getTypeId(type)},${getTypeId(candidate)},${(assumeTrue ? 1 : 0) | (checkDerived ? 2 : 0)}` : void 0; - return getCachedType(key2) ?? setCachedType(key2, getNarrowedTypeWorker(type, candidate, assumeTrue, checkDerived)); + return (_getCachedType3 = getCachedType(key2)) !== null && _getCachedType3 !== void 0 ? _getCachedType3 : setCachedType(key2, getNarrowedTypeWorker(type, candidate, assumeTrue, checkDerived)); } function getNarrowedTypeWorker(type, candidate, assumeTrue, checkDerived) { if (!assumeTrue) { if (checkDerived) { - return filterType(type, (t) => !isTypeDerivedFrom(t, candidate)); + return filterType(type, t => !isTypeDerivedFrom(t, candidate)); } - const trueType2 = getNarrowedType( - type, - candidate, - /*assumeTrue*/ - true, - /*checkDerived*/ - false - ); - return filterType(type, (t) => !isTypeSubsetOf(t, trueType2)); + const trueType2 = getNarrowedType(type, candidate, /*assumeTrue*/ + true, /*checkDerived*/ + false); + return filterType(type, t => !isTypeSubsetOf(t, trueType2)); } if (type.flags & 3 /* AnyOrUnknown */) { return candidate; } const isRelated = checkDerived ? isTypeDerivedFrom : isTypeSubtypeOf; const keyPropertyName = type.flags & 1048576 /* Union */ ? getKeyPropertyName(type) : void 0; - const narrowedType = mapType(candidate, (c) => { + const narrowedType = mapType(candidate, c => { const discriminant = keyPropertyName && getTypeOfPropertyOfType(c, keyPropertyName); const matching = discriminant && getConstituentTypeForKeyType(type, discriminant); - const directlyRelated = mapType( - matching || type, - checkDerived ? (t) => isTypeDerivedFrom(t, c) ? t : isTypeDerivedFrom(c, t) ? c : neverType : (t) => isTypeStrictSubtypeOf(t, c) ? t : isTypeStrictSubtypeOf(c, t) ? c : isTypeSubtypeOf(t, c) ? t : isTypeSubtypeOf(c, t) ? c : neverType - ); - return directlyRelated.flags & 131072 /* Never */ ? mapType(type, (t) => maybeTypeOfKind(t, 465829888 /* Instantiable */) && isRelated(c, getBaseConstraintOfType(t) || unknownType) ? getIntersectionType([t, c]) : neverType) : directlyRelated; + const directlyRelated = mapType(matching || type, checkDerived ? t => isTypeDerivedFrom(t, c) ? t : isTypeDerivedFrom(c, t) ? c : neverType : t => isTypeStrictSubtypeOf(t, c) ? t : isTypeStrictSubtypeOf(c, t) ? c : isTypeSubtypeOf(t, c) ? t : isTypeSubtypeOf(c, t) ? c : neverType); + return directlyRelated.flags & 131072 /* Never */ ? mapType(type, t => maybeTypeOfKind(t, 465829888 /* Instantiable */) && isRelated(c, getBaseConstraintOfType(t) || unknownType) ? getIntersectionType([t, c]) : neverType) : directlyRelated; }); return !(narrowedType.flags & 131072 /* Never */) ? narrowedType : isTypeSubtypeOf(candidate, type) ? candidate : isTypeAssignableTo(type, candidate) ? type : isTypeAssignableTo(candidate, type) ? candidate : getIntersectionType([type, candidate]); } @@ -69040,6 +64098,7 @@ ${lanes.join("\n")} } } } + return type; } function narrowTypeByTypePredicate(type, predicate, callExpression, assumeTrue) { @@ -69047,26 +64106,17 @@ ${lanes.join("\n")} const predicateArgument = getTypePredicateArgument(predicate, callExpression); if (predicateArgument) { if (isMatchingReference(reference, predicateArgument)) { - return getNarrowedType( - type, - predicate.type, - assumeTrue, - /*checkDerived*/ - false - ); + return getNarrowedType(type, predicate.type, assumeTrue, /*checkDerived*/ + false); } if (strictNullChecks && optionalChainContainsReference(predicateArgument, reference) && (assumeTrue && !hasTypeFacts(predicate.type, 65536 /* EQUndefined */) || !assumeTrue && everyType(predicate.type, isNullableType))) { type = getAdjustedTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */); } + const access = getDiscriminantPropertyAccess(predicateArgument, type); if (access) { - return narrowTypeByDiscriminant(type, access, (t) => getNarrowedType( - t, - predicate.type, - assumeTrue, - /*checkDerived*/ - false - )); + return narrowTypeByDiscriminant(type, access, t => getNarrowedType(t, predicate.type, assumeTrue, /*checkDerived*/ + false)); } } } @@ -69114,10 +64164,12 @@ ${lanes.join("\n")} if (isMatchingReference(reference, expr)) { return getAdjustedTypeWithFacts(type, assumePresent ? 2097152 /* NEUndefinedOrNull */ : 262144 /* EQUndefinedOrNull */); } + const access = getDiscriminantPropertyAccess(expr, type); if (access) { - return narrowTypeByDiscriminant(type, access, (t) => getTypeWithFacts(t, assumePresent ? 2097152 /* NEUndefinedOrNull */ : 262144 /* EQUndefinedOrNull */)); + return narrowTypeByDiscriminant(type, access, t => getTypeWithFacts(t, assumePresent ? 2097152 /* NEUndefinedOrNull */ : 262144 /* EQUndefinedOrNull */)); } + return type; } } @@ -69128,15 +64180,9 @@ ${lanes.join("\n")} location = location.parent; } if (isExpressionNode(location) && (!isAssignmentTarget(location) || isWriteAccess(location))) { - const type = removeOptionalTypeMarker( - isWriteAccess(location) && location.kind === 211 /* PropertyAccessExpression */ ? checkPropertyAccessExpression( - location, - /*checkMode*/ - void 0, - /*writeOnly*/ - true - ) : getTypeOfExpression(location) - ); + const type = removeOptionalTypeMarker(isWriteAccess(location) && location.kind === 211 /* PropertyAccessExpression */ ? checkPropertyAccessExpression(location, /*checkMode*/ + void 0, /*writeOnly*/ + true) : getTypeOfExpression(location)); if (getExportSymbolOfValueSymbolIfExported(getNodeLinks(location).resolvedSymbol) === symbol) { return type; } @@ -69148,8 +64194,9 @@ ${lanes.join("\n")} return isRightSideOfAccessExpression(location) && isWriteAccess(location.parent) ? getWriteTypeOfSymbol(symbol) : getNonMissingTypeOfSymbol(symbol); } function getControlFlowContainer(node) { - return findAncestor(node.parent, (node2) => isFunctionLike(node2) && !getImmediatelyInvokedFunctionExpression(node2) || node2.kind === 268 /* ModuleBlock */ || node2.kind === 312 /* SourceFile */ || node2.kind === 172 /* PropertyDeclaration */); + return findAncestor(node.parent, node2 => isFunctionLike(node2) && !getImmediatelyInvokedFunctionExpression(node2) || node2.kind === 268 /* ModuleBlock */ || node2.kind === 312 /* SourceFile */ || node2.kind === 172 /* PropertyDeclaration */); } + function isSymbolAssigned(symbol) { if (!symbol.valueDeclaration) { return false; @@ -69165,8 +64212,9 @@ ${lanes.join("\n")} return symbol.isAssigned || false; } function hasParentWithAssignmentsMarked(node) { - return !!findAncestor(node.parent, (node2) => (isFunctionLike(node2) || isCatchClause(node2)) && !!(getNodeLinks(node2).flags & 131072 /* AssignmentsMarked */)); + return !!findAncestor(node.parent, node2 => (isFunctionLike(node2) || isCatchClause(node2)) && !!(getNodeLinks(node2).flags & 131072 /* AssignmentsMarked */)); } + function markNodeAssignments(node) { if (node.kind === 80 /* Identifier */) { if (isAssignmentTarget(node)) { @@ -69209,15 +64257,14 @@ ${lanes.join("\n")} function isGenericTypeWithUnionConstraint(type) { return type.flags & 2097152 /* Intersection */ ? some(type.types, isGenericTypeWithUnionConstraint) : !!(type.flags & 465829888 /* Instantiable */ && getBaseConstraintOrType(type).flags & (98304 /* Nullable */ | 1048576 /* Union */)); } + function isGenericTypeWithoutNullableConstraint(type) { return type.flags & 2097152 /* Intersection */ ? some(type.types, isGenericTypeWithoutNullableConstraint) : !!(type.flags & 465829888 /* Instantiable */ && !maybeTypeOfKind(getBaseConstraintOrType(type), 98304 /* Nullable */)); } + function hasContextualTypeWithNoGenericTypes(node, checkMode) { - const contextualType = (isIdentifier(node) || isPropertyAccessExpression(node) || isElementAccessExpression(node)) && !((isJsxOpeningElement(node.parent) || isJsxSelfClosingElement(node.parent)) && node.parent.tagName === node) && (checkMode && checkMode & 32 /* RestBindingElement */ ? getContextualType2(node, 8 /* SkipBindingPatterns */) : getContextualType2( - node, - /*contextFlags*/ - void 0 - )); + const contextualType = (isIdentifier(node) || isPropertyAccessExpression(node) || isElementAccessExpression(node)) && !((isJsxOpeningElement(node.parent) || isJsxSelfClosingElement(node.parent)) && node.parent.tagName === node) && (checkMode && checkMode & 32 /* RestBindingElement */ ? getContextualType2(node, 8 /* SkipBindingPatterns */) : getContextualType2(node, /*contextFlags*/ + void 0)); return contextualType && !isGenericType(contextualType); } function getNarrowableTypeForReference(type, reference, checkMode) { @@ -69225,7 +64272,7 @@ ${lanes.join("\n")} return substituteConstraints ? mapType(type, getBaseConstraintOrType) : type; } function isExportOrExportExpression(location) { - return !!findAncestor(location, (n) => { + return !!findAncestor(location, n => { const parent2 = n.parent; if (parent2 === void 0) { return "quit"; @@ -69243,17 +64290,11 @@ ${lanes.join("\n")} if (!canCollectSymbolAliasAccessabilityData) { return; } - if (isNonLocalAlias( - symbol, - /*excludes*/ - 111551 /* Value */ - ) && !isInTypeQuery(location)) { + if (isNonLocalAlias(symbol, /*excludes*/ + 111551 /* Value */) && !isInTypeQuery(location)) { const target = resolveAlias(symbol); - if (getSymbolFlags( - symbol, - /*excludeTypeOnlyMeanings*/ - true - ) & (111551 /* Value */ | 1048576 /* ExportValue */)) { + if (getSymbolFlags(symbol, /*excludeTypeOnlyMeanings*/ + true) & (111551 /* Value */ | 1048576 /* ExportValue */)) { if (getIsolatedModules(compilerOptions) || shouldPreserveConstEnums(compilerOptions) && isExportOrExportExpression(location) || !isConstEnumOrConstEnumOnlyModule(getExportSymbolOfValueSymbolIfExported(target))) { markAliasSymbolAsReferenced(symbol); } else { @@ -69278,23 +64319,13 @@ ${lanes.join("\n")} links.flags &= ~4194304 /* InCheckIdentifier */; if (parentTypeConstraint && parentTypeConstraint.flags & 1048576 /* Union */ && !(parent2.kind === 169 /* Parameter */ && isSymbolAssigned(symbol))) { const pattern = declaration.parent; - const narrowedType = getFlowTypeOfReference( - pattern, - parentTypeConstraint, - parentTypeConstraint, - /*flowContainer*/ - void 0, - location.flowNode - ); + const narrowedType = getFlowTypeOfReference(pattern, parentTypeConstraint, parentTypeConstraint, /*flowContainer*/ + void 0, location.flowNode); if (narrowedType.flags & 131072 /* Never */) { return neverType; } - return getBindingElementTypeFromParentType( - declaration, - narrowedType, - /*noTupleBoundsCheck*/ - true - ); + return getBindingElementTypeFromParentType(declaration, narrowedType, /*noTupleBoundsCheck*/ + true); } } } @@ -69306,14 +64337,8 @@ ${lanes.join("\n")} if (contextualSignature && contextualSignature.parameters.length === 1 && signatureHasRestParameter(contextualSignature)) { const restType = getReducedApparentType(instantiateType(getTypeOfSymbol(contextualSignature.parameters[0]), (_a = getInferenceContext(func)) == null ? void 0 : _a.nonFixingMapper)); if (restType.flags & 1048576 /* Union */ && everyType(restType, isTupleType) && !isSymbolAssigned(symbol)) { - const narrowedType = getFlowTypeOfReference( - func, - restType, - restType, - /*flowContainer*/ - void 0, - location.flowNode - ); + const narrowedType = getFlowTypeOfReference(func, restType, restType, /*flowContainer*/ + void 0, location.flowNode); const index = func.parameters.indexOf(declaration) - (getThisParameter(func) ? 1 : 0); return getIndexedAccessType(narrowedType, getNumberLiteralType(index)); } @@ -69358,21 +64383,13 @@ ${lanes.join("\n")} let declaration = localOrExportSymbol.valueDeclaration; if (declaration && localOrExportSymbol.flags & 32 /* Class */) { if (isClassLike(declaration) && declaration.name !== node) { - let container = getThisContainer( - node, - /*includeArrowFunctions*/ - false, - /*includeClassComputedPropertyName*/ - false - ); + let container = getThisContainer(node, /*includeArrowFunctions*/ + false, /*includeClassComputedPropertyName*/ + false); while (container.kind !== 312 /* SourceFile */ && container.parent !== declaration) { - container = getThisContainer( - container, - /*includeArrowFunctions*/ - false, - /*includeClassComputedPropertyName*/ - false - ); + container = getThisContainer(container, /*includeArrowFunctions*/ + false, /*includeClassComputedPropertyName*/ + false); } if (container.kind !== 312 /* SourceFile */) { getNodeLinks(declaration).flags |= 262144 /* ContainsConstructorReference */; @@ -69381,6 +64398,7 @@ ${lanes.join("\n")} } } } + checkNestedBlockScopedBinding(node, symbol); let type = getNarrowedTypeOfSymbol(localOrExportSymbol, node); const assignmentKind = getAssignmentTargetKind(node); @@ -69465,17 +64483,14 @@ ${lanes.join("\n")} return true; } function isInsideFunctionOrInstancePropertyInitializer(node, threshold) { - return !!findAncestor(node, (n) => n === threshold ? "quit" : isFunctionLike(n) || n.parent && isPropertyDeclaration(n.parent) && !hasStaticModifier(n.parent) && n.parent.initializer === n); + return !!findAncestor(node, n => n === threshold ? "quit" : isFunctionLike(n) || n.parent && isPropertyDeclaration(n.parent) && !hasStaticModifier(n.parent) && n.parent.initializer === n); } function getPartOfForStatementContainingNode(node, container) { - return findAncestor(node, (n) => n === container ? "quit" : n === container.initializer || n === container.condition || n === container.incrementor || n === container.statement); + return findAncestor(node, n => n === container ? "quit" : n === container.initializer || n === container.condition || n === container.incrementor || n === container.statement); } function getEnclosingIterationStatement(node) { - return findAncestor(node, (n) => !n || nodeStartsNewLexicalEnvironment(n) ? "quit" : isIterationStatement( - n, - /*lookInLabeledStatements*/ - false - )); + return findAncestor(node, n => !n || nodeStartsNewLexicalEnvironment(n) ? "quit" : isIterationStatement(n, /*lookInLabeledStatements*/ + false)); } function checkNestedBlockScopedBinding(node, symbol) { if (languageVersion >= 2 /* ES2015 */ || (symbol.flags & (2 /* BlockScopedVariable */ | 32 /* Class */)) === 0 || !symbol.valueDeclaration || isSourceFile(symbol.valueDeclaration) || symbol.valueDeclaration.parent.kind === 299 /* CatchClause */) { @@ -69506,18 +64521,22 @@ ${lanes.join("\n")} getNodeLinks(enclosingIterationStatement).flags |= 4096 /* LoopWithCapturedBlockScopedBinding */; } } + if (isForStatement(container)) { const varDeclList = getAncestor(symbol.valueDeclaration, 261 /* VariableDeclarationList */); if (varDeclList && varDeclList.parent === container && isAssignedInBodyOfForStatement(node, container)) { getNodeLinks(symbol.valueDeclaration).flags |= 65536 /* NeedsLoopOutParameter */; } } + getNodeLinks(symbol.valueDeclaration).flags |= 32768 /* BlockScopedBindingInLoop */; } + if (isCaptured) { getNodeLinks(symbol.valueDeclaration).flags |= 16384 /* CapturedBlockScopedBinding */; } } + function isBindingCapturedByNode(node, decl) { const links = getNodeLinks(node); return !!links && contains(links.capturedBlockScopeBindings, getSymbolOfDeclaration(decl)); @@ -69534,10 +64553,11 @@ ${lanes.join("\n")} const expr = current.parent; isAssigned = expr.operator === 46 /* PlusPlusToken */ || expr.operator === 47 /* MinusMinusToken */; } + if (!isAssigned) { return false; } - return !!findAncestor(current, (n) => n === container ? "quit" : n === container.statement); + return !!findAncestor(current, n => n === container ? "quit" : n === container.statement); } function captureLexicalThis(node, container) { getNodeLinks(node).flags |= 2 /* LexicalThis */; @@ -69548,6 +64568,7 @@ ${lanes.join("\n")} getNodeLinks(container).flags |= 4 /* CaptureThis */; } } + function findFirstSuperCall(node) { return isSuperCall(node) ? node : isFunctionLike(node) ? void 0 : forEachChild(node, findFirstSuperCall); } @@ -69561,11 +64582,8 @@ ${lanes.join("\n")} const containingClassDecl = container.parent; const baseTypeNode = getClassExtendsHeritageElement(containingClassDecl); if (baseTypeNode && !classDeclarationExtendsNull(containingClassDecl)) { - if (canHaveFlowNode(node) && node.flowNode && !isPostSuperFlowNode( - node.flowNode, - /*noCacheCheck*/ - false - )) { + if (canHaveFlowNode(node) && node.flowNode && !isPostSuperFlowNode(node.flowNode, /*noCacheCheck*/ + false)) { error2(node, diagnosticMessage); } } @@ -69577,13 +64595,9 @@ ${lanes.join("\n")} } function checkThisExpression(node) { const isNodeInTypeQuery = isInTypeQuery(node); - let container = getThisContainer( - node, - /*includeArrowFunctions*/ - true, - /*includeClassComputedPropertyName*/ - true - ); + let container = getThisContainer(node, /*includeArrowFunctions*/ + true, /*includeClassComputedPropertyName*/ + true); let capturedByArrowFunction = false; let thisInComputedPropertyName = false; if (container.kind === 176 /* Constructor */) { @@ -69591,21 +64605,13 @@ ${lanes.join("\n")} } while (true) { if (container.kind === 219 /* ArrowFunction */) { - container = getThisContainer( - container, - /*includeArrowFunctions*/ - false, - !thisInComputedPropertyName - ); + container = getThisContainer(container, /*includeArrowFunctions*/ + false, !thisInComputedPropertyName); capturedByArrowFunction = true; } if (container.kind === 167 /* ComputedPropertyName */) { - container = getThisContainer( - container, - !capturedByArrowFunction, - /*includeClassComputedPropertyName*/ - false - ); + container = getThisContainer(container, !capturedByArrowFunction, /*includeClassComputedPropertyName*/ + false); thisInComputedPropertyName = true; continue; } @@ -69632,12 +64638,8 @@ ${lanes.join("\n")} if (!isNodeInTypeQuery && capturedByArrowFunction && languageVersion < 2 /* ES2015 */) { captureLexicalThis(node, container); } - const type = tryGetThisTypeAt( - node, - /*includeGlobalThis*/ - true, - container - ); + const type = tryGetThisTypeAt(node, /*includeGlobalThis*/ + true, container); if (noImplicitThis) { const globalThisType2 = getTypeOfSymbol(globalThisSymbol); if (type === globalThisType2 && capturedByArrowFunction) { @@ -69654,13 +64656,9 @@ ${lanes.join("\n")} } return type || anyType; } - function tryGetThisTypeAt(node, includeGlobalThis = true, container = getThisContainer( - node, - /*includeArrowFunctions*/ - false, - /*includeClassComputedPropertyName*/ - false - )) { + function tryGetThisTypeAt(node, includeGlobalThis = true, container = getThisContainer(node, /*includeArrowFunctions*/ + false, /*includeClassComputedPropertyName*/ + false)) { const isInJS = isInJSFile(node); if (isFunctionLike(container) && (!isInParameterInitializerBeforeContainingFunction(node) || getThisParameter(container))) { let thisType = getThisTypeOfDeclaration(container) || isInJS && getTypeForThisExpressionFromJSDoc(container); @@ -69697,13 +64695,9 @@ ${lanes.join("\n")} } } function getExplicitThisType(node) { - const container = getThisContainer( - node, - /*includeArrowFunctions*/ - false, - /*includeClassComputedPropertyName*/ - false - ); + const container = getThisContainer(node, /*includeArrowFunctions*/ + false, /*includeClassComputedPropertyName*/ + false); if (isFunctionLike(container)) { const signature = getSignatureFromDeclaration(container); if (signature.thisParameter) { @@ -69739,35 +64733,28 @@ ${lanes.join("\n")} } } function isInConstructorArgumentInitializer(node, constructorDecl) { - return !!findAncestor(node, (n) => isFunctionLikeDeclaration(n) ? "quit" : n.kind === 169 /* Parameter */ && n.parent === constructorDecl); + return !!findAncestor(node, n => isFunctionLikeDeclaration(n) ? "quit" : n.kind === 169 /* Parameter */ && n.parent === constructorDecl); } function checkSuperExpression(node) { const isCallExpression2 = node.parent.kind === 213 /* CallExpression */ && node.parent.expression === node; - const immediateContainer = getSuperContainer( - node, - /*stopOnFunctions*/ - true - ); + const immediateContainer = getSuperContainer(node, /*stopOnFunctions*/ + true); let container = immediateContainer; let needToCaptureLexicalThis = false; let inAsyncFunction = false; if (!isCallExpression2) { while (container && container.kind === 219 /* ArrowFunction */) { - if (hasSyntacticModifier(container, 1024 /* Async */)) - inAsyncFunction = true; - container = getSuperContainer( - container, - /*stopOnFunctions*/ - true - ); + if (hasSyntacticModifier(container, 1024 /* Async */)) inAsyncFunction = true; + container = getSuperContainer(container, /*stopOnFunctions*/ + true); 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)) { - const current = findAncestor(node, (n) => n === container ? "quit" : n.kind === 167 /* ComputedPropertyName */); + const current = findAncestor(node, n => n === container ? "quit" : n.kind === 167 /* ComputedPropertyName */); if (current && current.kind === 167 /* ComputedPropertyName */) { error2(node, Diagnostics.super_cannot_be_referenced_in_a_computed_property_name); } else if (isCallExpression2) { @@ -69785,7 +64772,7 @@ ${lanes.join("\n")} if (isStatic(container) || isCallExpression2) { nodeCheckFlag = 32 /* SuperStatic */; if (!isCallExpression2 && languageVersion >= 2 /* ES2015 */ && languageVersion <= 8 /* ES2021 */ && (isPropertyDeclaration(container) || isClassStaticBlockDeclaration(container))) { - forEachEnclosingBlockScopeContainer(node.parent, (current) => { + forEachEnclosingBlockScopeContainer(node.parent, current => { if (!isSourceFile(current) || isExternalOrCommonJsModule(current)) { getNodeLinks(current).flags |= 2097152 /* ContainsSuperPropertyInStaticInitializer */; } @@ -69794,6 +64781,7 @@ ${lanes.join("\n")} } else { nodeCheckFlag = 16 /* SuperInstance */; } + getNodeLinks(node).flags |= nodeCheckFlag; if (container.kind === 174 /* MethodDeclaration */ && inAsyncFunction) { if (isSuperProperty(node.parent) && isAssignmentTarget(node.parent)) { @@ -69802,6 +64790,7 @@ ${lanes.join("\n")} getNodeLinks(container).flags |= 128 /* MethodWithSuperPropertyAccessInAsync */; } } + if (needToCaptureLexicalThis) { captureLexicalThis(node.parent, container); } @@ -69843,6 +64832,7 @@ ${lanes.join("\n")} } } } + return false; } } @@ -69853,7 +64843,7 @@ ${lanes.join("\n")} return getObjectFlags(type) & 4 /* Reference */ && type.target === globalThisType ? getTypeArguments(type)[0] : void 0; } function getThisTypeFromContextualType(type) { - return mapType(type, (t) => { + return mapType(type, t => { return t.flags & 2097152 /* Intersection */ ? forEach(t.types, getThisTypeArgument) : getThisTypeArgument(t); }); } @@ -69869,11 +64859,8 @@ ${lanes.join("\n")} break; } literal = literal.parent.parent; - type = getApparentTypeOfContextualType( - literal, - /*contextFlags*/ - void 0 - ); + type = getApparentTypeOfContextualType(literal, /*contextFlags*/ + void 0); } } function getContextualThisParameterType(func) { @@ -69893,11 +64880,8 @@ ${lanes.join("\n")} if (noImplicitThis || inJs) { const containingLiteral = getContainingObjectLiteral(func); if (containingLiteral) { - const contextualType = getApparentTypeOfContextualType( - containingLiteral, - /*contextFlags*/ - void 0 - ); + const contextualType = getApparentTypeOfContextualType(containingLiteral, /*contextFlags*/ + void 0); const thisType = getThisTypeOfObjectLiteralFromContextualType(containingLiteral, contextualType); if (thisType) { return instantiateType(thisType, getMapperFromContext(getInferenceContext(containingLiteral))); @@ -69908,7 +64892,9 @@ ${lanes.join("\n")} if (isAssignmentExpression(parent2)) { const target = parent2.left; if (isAccessExpression(target)) { - const { expression } = target; + const { + expression + } = target; if (inJs && isIdentifier(expression)) { const sourceFile = getSourceFileOfNode(parent2); if (sourceFile.commonJsModuleIndicator && getResolvedSymbol(expression) === sourceFile.symbol) { @@ -69931,16 +64917,10 @@ ${lanes.join("\n")} const args = getEffectiveCallArguments(iife); const indexOfParameter = func.parameters.indexOf(parameter); if (parameter.dotDotDotToken) { - return getSpreadArgumentType( - args, - indexOfParameter, - args.length, - anyType, - /*context*/ - void 0, - 0 /* Normal */ - ); + return getSpreadArgumentType(args, indexOfParameter, args.length, anyType, /*context*/ + void 0, 0 /* Normal */); } + const links = getNodeLinks(iife); const cached = links.resolvedSignature; links.resolvedSignature = anySignature; @@ -69974,12 +64954,10 @@ ${lanes.join("\n")} 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); @@ -69990,8 +64968,7 @@ ${lanes.join("\n")} } 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) { @@ -70002,13 +64979,9 @@ ${lanes.join("\n")} return result; } if (!(contextFlags & 8 /* SkipBindingPatterns */) && isBindingPattern(declaration.name) && declaration.name.elements.length > 0) { - return getTypeFromBindingPattern( - declaration.name, - /*includePatternInType*/ - true, - /*reportErrors*/ - false - ); + return getTypeFromBindingPattern(declaration.name, /*includePatternInType*/ + true, /*reportErrors*/ + false); } } return void 0; @@ -70022,7 +64995,7 @@ ${lanes.join("\n")} if (functionFlags & 1 /* Generator */) { const isAsyncGenerator = (functionFlags & 2 /* Async */) !== 0; if (contextualReturnType.flags & 1048576 /* Union */) { - contextualReturnType = filterType(contextualReturnType, (type) => !!getIterationTypeOfGeneratorFunctionReturnType(1 /* Return */, type, isAsyncGenerator)); + contextualReturnType = filterType(contextualReturnType, type => !!getIterationTypeOfGeneratorFunctionReturnType(1 /* Return */, type, isAsyncGenerator)); } const iterationReturnType = getIterationTypeOfGeneratorFunctionReturnType(1 /* Return */, contextualReturnType, (functionFlags & 2 /* Async */) !== 0); if (!iterationReturnType) { @@ -70055,7 +65028,7 @@ ${lanes.join("\n")} if (contextualReturnType) { const isAsyncGenerator = (functionFlags & 2 /* Async */) !== 0; if (!node.asteriskToken && contextualReturnType.flags & 1048576 /* Union */) { - contextualReturnType = filterType(contextualReturnType, (type) => !!getIterationTypeOfGeneratorFunctionReturnType(1 /* Return */, type, isAsyncGenerator)); + contextualReturnType = filterType(contextualReturnType, type => !!getIterationTypeOfGeneratorFunctionReturnType(1 /* Return */, type, isAsyncGenerator)); } return node.asteriskToken ? contextualReturnType : getIterationTypeOfGeneratorFunctionReturnType(0 /* Yield */, contextualReturnType, isAsyncGenerator); } @@ -70077,11 +65050,8 @@ ${lanes.join("\n")} } function getContextualIterationType(kind, functionDecl) { const isAsync = !!(getFunctionFlags(functionDecl) & 2 /* Async */); - const contextualReturnType = getContextualReturnType( - functionDecl, - /*contextFlags*/ - void 0 - ); + const contextualReturnType = getContextualReturnType(functionDecl, /*contextFlags*/ + void 0); if (contextualReturnType) { return getIterationTypeOfGeneratorFunctionReturnType(kind, contextualReturnType, isAsync) || void 0; } @@ -70097,17 +65067,13 @@ ${lanes.join("\n")} const returnType2 = getReturnTypeOfSignature(signature); const functionFlags = getFunctionFlags(functionDecl); if (functionFlags & 1 /* Generator */) { - return filterType(returnType2, (t) => { - return !!(t.flags & (3 /* AnyOrUnknown */ | 16384 /* Void */ | 58982400 /* InstantiableNonPrimitive */)) || checkGeneratorInstantiationAssignabilityToReturnType( - t, - functionFlags, - /*errorNode*/ - void 0 - ); + return filterType(returnType2, t => { + return !!(t.flags & (3 /* AnyOrUnknown */ | 16384 /* Void */ | 58982400 /* InstantiableNonPrimitive */)) || checkGeneratorInstantiationAssignabilityToReturnType(t, functionFlags, /*errorNode*/ + void 0); }); } if (functionFlags & 2 /* Async */) { - return filterType(returnType2, (t) => { + return filterType(returnType2, t => { return !!(t.flags & (3 /* AnyOrUnknown */ | 16384 /* Void */ | 58982400 /* InstantiableNonPrimitive */)) || !!getAwaitedTypeOfPromise(t); }); } @@ -70126,10 +65092,8 @@ ${lanes.join("\n")} } function getContextualTypeForArgumentAtIndex(callTarget, argIndex) { if (isImportCall(callTarget)) { - return argIndex === 0 ? stringType : argIndex === 1 ? getGlobalImportCallOptionsType( - /*reportErrors*/ - false - ) : anyType; + return argIndex === 0 ? stringType : argIndex === 1 ? getGlobalImportCallOptionsType( /*reportErrors*/ + false) : anyType; } const signature = getNodeLinks(callTarget).resolvedSignature === resolvingSignature ? resolvingSignature : getResolvedSignature(callTarget); if (isJsxOpeningLikeElement(callTarget) && argIndex === 0) { @@ -70150,7 +65114,11 @@ ${lanes.join("\n")} } function getContextualTypeForBinaryOperand(node, contextFlags) { const binaryExpression = node.parent; - const { left, operatorToken, right } = binaryExpression; + const { + left, + operatorToken, + right + } = binaryExpression; switch (operatorToken.kind) { case 64 /* EqualsToken */: case 77 /* AmpersandAmpersandEqualsToken */: @@ -70225,16 +65193,9 @@ ${lanes.join("\n")} return getTypeFromTypeNode(overallAnnotation); } else if (isIdentifier(lhs.expression)) { const id = lhs.expression; - const parentSymbol = resolveName( - id, - id.escapedText, - 111551 /* Value */, - /*nameNotFoundMessage*/ - void 0, - id.escapedText, - /*isUse*/ - true - ); + const parentSymbol = resolveName(id, id.escapedText, 111551 /* Value */, /*nameNotFoundMessage*/ + void 0, id.escapedText, /*isUse*/ + true); if (parentSymbol) { const annotated2 = parentSymbol.valueDeclaration && getEffectiveTypeAnnotationNode(parentSymbol.valueDeclaration); if (annotated2) { @@ -70275,24 +65236,15 @@ ${lanes.join("\n")} return false; } const name = declaration.left.expression.escapedText; - const symbol = resolveName( - declaration.left, - name, - 111551 /* Value */, - /*nameNotFoundMessage*/ - void 0, - /*nameArg*/ - void 0, - /*isUse*/ - true, - /*excludeGlobals*/ - true - ); + const symbol = resolveName(declaration.left, name, 111551 /* Value */, /*nameNotFoundMessage*/ + void 0, /*nameArg*/ + void 0, /*isUse*/ + true, /*excludeGlobals*/ + true); return isThisInitializedDeclaration(symbol == null ? void 0 : symbol.valueDeclaration); } function getContextualTypeForThisPropertyAssignment(binaryExpression) { - 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) { @@ -70303,13 +65255,9 @@ ${lanes.join("\n")} } } const thisAccess = cast(binaryExpression.left, isAccessExpression); - if (!isObjectLiteralMethod(getThisContainer( - thisAccess.expression, - /*includeArrowFunctions*/ - false, - /*includeClassComputedPropertyName*/ - false - ))) { + if (!isObjectLiteralMethod(getThisContainer(thisAccess.expression, /*includeArrowFunctions*/ + false, /*includeClassComputedPropertyName*/ + false))) { return void 0; } const thisType = checkThisExpression(thisAccess.expression); @@ -70320,44 +65268,35 @@ ${lanes.join("\n")} return !!(getCheckFlags(symbol) & 262144 /* Mapped */ && !symbol.links.type && findResolutionCycleStartIndex(symbol, 0 /* Type */) >= 0); } function getTypeOfPropertyOfContextualType(type, name, nameType) { - return mapType( - type, - (t) => { - var _a; - if (isGenericMappedType(t) && !t.declaration.nameType) { - const constraint = getConstraintTypeFromMappedType(t); - const constraintOfConstraint = getBaseConstraintOfType(constraint) || constraint; - const propertyNameType = nameType || getStringLiteralType(unescapeLeadingUnderscores(name)); - if (isTypeAssignableTo(propertyNameType, constraintOfConstraint)) { - return substituteIndexedMappedType(t, propertyNameType); - } - } else if (t.flags & 3670016 /* StructuredType */) { - const prop = getPropertyOfType(t, name); - if (prop) { - return isCircularMappedProperty(prop) ? void 0 : removeMissingType(getTypeOfSymbol(prop), !!(prop && prop.flags & 16777216 /* Optional */)); - } - if (isTupleType(t) && isNumericLiteralName(name) && +name >= 0) { - const restType = getElementTypeOfSliceOfTupleType( - t, - t.target.fixedLength, - /*endSkipCount*/ - 0, - /*writing*/ - false, - /*noReductions*/ - true - ); - if (restType) { - return restType; - } - } - return (_a = findApplicableIndexInfo(getIndexInfosOfStructuredType(t), nameType || getStringLiteralType(unescapeLeadingUnderscores(name)))) == null ? void 0 : _a.type; + return mapType(type, t => { + var _a; + if (isGenericMappedType(t) && !t.declaration.nameType) { + const constraint = getConstraintTypeFromMappedType(t); + const constraintOfConstraint = getBaseConstraintOfType(constraint) || constraint; + const propertyNameType = nameType || getStringLiteralType(unescapeLeadingUnderscores(name)); + if (isTypeAssignableTo(propertyNameType, constraintOfConstraint)) { + return substituteIndexedMappedType(t, propertyNameType); } - return void 0; - }, - /*noReductions*/ - true - ); + } else if (t.flags & 3670016 /* StructuredType */) { + const prop = getPropertyOfType(t, name); + if (prop) { + return isCircularMappedProperty(prop) ? void 0 : removeMissingType(getTypeOfSymbol(prop), !!(prop && prop.flags & 16777216 /* Optional */)); + } + + if (isTupleType(t) && isNumericLiteralName(name) && +name >= 0) { + const restType = getElementTypeOfSliceOfTupleType(t, t.target.fixedLength, /*endSkipCount*/ + 0, /*writing*/ + false, /*noReductions*/ + true); + if (restType) { + return restType; + } + } + return (_a = findApplicableIndexInfo(getIndexInfosOfStructuredType(t), nameType || getStringLiteralType(unescapeLeadingUnderscores(name)))) == null ? void 0 : _a.type; + } + return void 0; + }, /*noReductions*/ + true); } function getContextualTypeForObjectLiteralMethod(node, contextFlags) { Debug.assert(isObjectLiteralMethod(node)); @@ -70390,15 +65329,11 @@ ${lanes.join("\n")} } if (element.name) { const nameType = getLiteralTypeFromPropertyName(element.name); - return mapType( - type, - (t) => { - var _a; - return (_a = findApplicableIndexInfo(getIndexInfosOfStructuredType(t), nameType)) == null ? void 0 : _a.type; - }, - /*noReductions*/ - true - ); + return mapType(type, t => { + var _a; + return (_a = findApplicableIndexInfo(getIndexInfosOfStructuredType(t), nameType)) == null ? void 0 : _a.type; + }, /*noReductions*/ + true); } } return void 0; @@ -70407,48 +65342,37 @@ ${lanes.join("\n")} let first2, last2; for (let i = 0; i < elements.length; i++) { if (isSpreadElement(elements[i])) { - first2 ?? (first2 = i); + var _first; + (_first = first2) !== null && _first !== void 0 ? _first : first2 = i; last2 = i; } } - return { first: first2, last: last2 }; + return { + first: first2, + last: last2 + }; } function getContextualTypeForElementExpression(type, index, length2, firstSpreadIndex, lastSpreadIndex) { - return type && mapType( - type, - (t) => { - if (isTupleType(t)) { - if ((firstSpreadIndex === void 0 || index < firstSpreadIndex) && index < t.target.fixedLength) { - return removeMissingType(getTypeArguments(t)[index], !!(t.target.elementFlags[index] && 2 /* Optional */)); - } - const offset = length2 !== void 0 && (lastSpreadIndex === void 0 || index > lastSpreadIndex) ? length2 - index : 0; - const fixedEndLength = offset > 0 && t.target.hasRestElement ? getEndElementCount(t.target, 3 /* Fixed */) : 0; - if (offset > 0 && offset <= fixedEndLength) { - return getTypeArguments(t)[getTypeReferenceArity(t) - offset]; - } - return getElementTypeOfSliceOfTupleType( - t, - firstSpreadIndex === void 0 ? t.target.fixedLength : Math.min(t.target.fixedLength, firstSpreadIndex), - length2 === void 0 || lastSpreadIndex === void 0 ? fixedEndLength : Math.min(fixedEndLength, length2 - lastSpreadIndex), - /*writing*/ - false, - /*noReductions*/ - true - ); + return type && mapType(type, t => { + if (isTupleType(t)) { + if ((firstSpreadIndex === void 0 || index < firstSpreadIndex) && index < t.target.fixedLength) { + return removeMissingType(getTypeArguments(t)[index], !!(t.target.elementFlags[index] && 2 /* Optional */)); } - return (!firstSpreadIndex || index < firstSpreadIndex) && getTypeOfPropertyOfContextualType(t, "" + index) || getIteratedTypeOrElementType( - 1 /* Element */, - t, - undefinedType, - /*errorNode*/ - void 0, - /*checkAssignability*/ - false - ); - }, - /*noReductions*/ - true - ); + + const offset = length2 !== void 0 && (lastSpreadIndex === void 0 || index > lastSpreadIndex) ? length2 - index : 0; + const fixedEndLength = offset > 0 && t.target.hasRestElement ? getEndElementCount(t.target, 3 /* Fixed */) : 0; + if (offset > 0 && offset <= fixedEndLength) { + return getTypeArguments(t)[getTypeReferenceArity(t) - offset]; + } + return getElementTypeOfSliceOfTupleType(t, firstSpreadIndex === void 0 ? t.target.fixedLength : Math.min(t.target.fixedLength, firstSpreadIndex), length2 === void 0 || lastSpreadIndex === void 0 ? fixedEndLength : Math.min(fixedEndLength, length2 - lastSpreadIndex), /*writing*/ + false, /*noReductions*/ + true); + } + return (!firstSpreadIndex || index < firstSpreadIndex) && getTypeOfPropertyOfContextualType(t, "" + index) || getIteratedTypeOrElementType(1 /* Element */, t, undefinedType, /*errorNode*/ + void 0, /*checkAssignability*/ + false); + }, /*noReductions*/ + true); } function getContextualTypeForConditionalOperand(node, contextFlags) { const conditional = node.parent; @@ -70463,18 +65387,14 @@ ${lanes.join("\n")} const realChildren = getSemanticJsxChildren(node.children); const childIndex = realChildren.indexOf(child); const childFieldType = getTypeOfPropertyOfContextualType(attributesType, jsxChildrenPropertyName); - return childFieldType && (realChildren.length === 1 ? childFieldType : mapType( - childFieldType, - (t) => { - if (isArrayLikeType(t)) { - return getIndexedAccessType(t, getNumberLiteralType(childIndex)); - } else { - return t; - } - }, - /*noReductions*/ - true - )); + return childFieldType && (realChildren.length === 1 ? childFieldType : mapType(childFieldType, t => { + if (isArrayLikeType(t)) { + return getIndexedAccessType(t, getNumberLiteralType(childIndex)); + } else { + return t; + } + }, /*noReductions*/ + true)); } function getContextualTypeForJsxExpression(node, contextFlags) { const exprParent = node.parent; @@ -70513,76 +65433,47 @@ ${lanes.join("\n")} return false; } function discriminateContextualTypeByObjectMembers(node, contextualType) { - return 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; - }), - (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] - ) - ), - isTypeAssignableTo - ); + return 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; + }), 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])), isTypeAssignableTo); } function discriminateContextualTypeByJSXAttributes(node, contextualType) { const jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(node)); - return discriminateTypeByDiscriminableItems( - contextualType, - concatenate( - map( - filter(node.properties, (p) => !!p.symbol && p.kind === 291 /* JsxAttribute */ && isDiscriminantProperty(contextualType, p.symbol.escapedName) && (!p.initializer || isPossiblyDiscriminantValue(p.initializer))), - (prop) => [!prop.initializer ? () => trueType : () => getContextFreeTypeOfExpression(prop.initializer), prop.symbol.escapedName] - ), - map( - filter(getPropertiesOfType(contextualType), (s) => { - var _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 - ); + return discriminateTypeByDiscriminableItems(contextualType, concatenate(map(filter(node.properties, p => !!p.symbol && p.kind === 291 /* JsxAttribute */ && isDiscriminantProperty(contextualType, p.symbol.escapedName) && (!p.initializer || isPossiblyDiscriminantValue(p.initializer))), prop => [!prop.initializer ? () => trueType : () => getContextFreeTypeOfExpression(prop.initializer), prop.symbol.escapedName]), map(filter(getPropertiesOfType(contextualType), s => { + var _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); } function getApparentTypeOfContextualType(node, contextFlags) { const contextualType = isObjectLiteralMethod(node) ? getContextualTypeForObjectLiteralMethod(node, contextFlags) : getContextualType2(node, contextFlags); const instantiatedType = instantiateContextualType(contextualType, node, contextFlags); if (instantiatedType && !(contextFlags && contextFlags & 2 /* NoConstraints */ && instantiatedType.flags & 8650752 /* TypeVariable */)) { - const apparentType = mapType( - instantiatedType, - // When obtaining apparent type of *contextual* type we don't want to get apparent type of mapped types. - // That would evaluate mapped types with array or tuple type constraints too eagerly - // and thus it would prevent `getTypeOfPropertyOfContextualType` from obtaining per-position contextual type for elements of array literal expressions. - // Apparent type of other mapped types is already the mapped type itself so we can just avoid calling `getApparentType` here for all mapped types. - (t) => getObjectFlags(t) & 32 /* Mapped */ ? t : getApparentType(t), - /*noReductions*/ - true - ); + const apparentType = mapType(instantiatedType, + // When obtaining apparent type of *contextual* type we don't want to get apparent type of mapped types. + // That would evaluate mapped types with array or tuple type constraints too eagerly + // and thus it would prevent `getTypeOfPropertyOfContextualType` from obtaining per-position contextual type for elements of array literal expressions. + // Apparent type of other mapped types is already the mapped type itself so we can just avoid calling `getApparentType` here for all mapped types. + t => getObjectFlags(t) & 32 /* Mapped */ ? t : getApparentType(t), /*noReductions*/ + true); return apparentType.flags & 1048576 /* Union */ && isObjectLiteralExpression(node) ? discriminateContextualTypeByObjectMembers(node, apparentType) : apparentType.flags & 1048576 /* Union */ && isJsxAttributes(node) ? discriminateContextualTypeByJSXAttributes(node, apparentType) : apparentType; } } @@ -70594,7 +65485,7 @@ ${lanes.join("\n")} } if (inferenceContext == null ? void 0 : inferenceContext.returnMapper) { const type = instantiateInstantiableTypes(contextualType, inferenceContext.returnMapper); - return type.flags & 1048576 /* Union */ && containsType(type.types, regularFalseType) && containsType(type.types, regularTrueType) ? filterType(type, (t) => t !== regularFalseType && t !== regularTrueType) : type; + return type.flags & 1048576 /* Union */ && containsType(type.types, regularFalseType) && containsType(type.types, regularTrueType) ? filterType(type, t => t !== regularFalseType && t !== regularTrueType) : type; } } return contextualType; @@ -70604,10 +65495,11 @@ ${lanes.join("\n")} return instantiateType(type, mapper); } if (type.flags & 1048576 /* Union */) { - return getUnionType(map(type.types, (t) => instantiateInstantiableTypes(t, mapper)), 0 /* None */); + return getUnionType(map(type.types, t => instantiateInstantiableTypes(t, mapper)), 0 /* None */); } + if (type.flags & 2097152 /* Intersection */) { - return getIntersectionType(map(type.types, (t) => instantiateInstantiableTypes(t, mapper))); + return getIntersectionType(map(type.types, t => instantiateInstantiableTypes(t, mapper))); } return type; } @@ -70616,15 +65508,14 @@ ${lanes.join("\n")} if (node.flags & 67108864 /* InWithStatement */) { return void 0; } - const index = findContextualNode( - node, - /*includeCaches*/ - !contextFlags - ); + const index = findContextualNode(node, /*includeCaches*/ + !contextFlags); if (index >= 0) { return contextualTypes[index]; } - const { parent: parent2 } = node; + const { + parent: parent2 + } = node; switch (parent2.kind) { case 260 /* VariableDeclaration */: case 169 /* Parameter */: @@ -70654,30 +65545,33 @@ ${lanes.join("\n")} return getContextualTypeForObjectLiteralElement(parent2, contextFlags); case 305 /* SpreadAssignment */: return getContextualType2(parent2.parent, contextFlags); - case 209 /* ArrayLiteralExpression */: { - const arrayLiteral = parent2; - const type = getApparentTypeOfContextualType(arrayLiteral, contextFlags); - const elementIndex = indexOfNode(arrayLiteral.elements, node); - const spreadIndices = (_a = getNodeLinks(arrayLiteral)).spreadIndices ?? (_a.spreadIndices = getSpreadIndices(arrayLiteral.elements)); - return getContextualTypeForElementExpression(type, elementIndex, arrayLiteral.elements.length, spreadIndices.first, spreadIndices.last); - } + case 209 /* ArrayLiteralExpression */: + { + var _a$spreadIndices; + const arrayLiteral = parent2; + const type = getApparentTypeOfContextualType(arrayLiteral, contextFlags); + const elementIndex = indexOfNode(arrayLiteral.elements, node); + const spreadIndices = (_a$spreadIndices = (_a = getNodeLinks(arrayLiteral)).spreadIndices) !== null && _a$spreadIndices !== void 0 ? _a$spreadIndices : _a.spreadIndices = getSpreadIndices(arrayLiteral.elements); + return getContextualTypeForElementExpression(type, elementIndex, arrayLiteral.elements.length, spreadIndices.first, spreadIndices.last); + } case 227 /* ConditionalExpression */: return getContextualTypeForConditionalOperand(node, contextFlags); case 239 /* TemplateSpan */: Debug.assert(parent2.parent.kind === 228 /* TemplateExpression */); return getContextualTypeForSubstitutionExpression(parent2.parent, node); - case 217 /* ParenthesizedExpression */: { - if (isInJSFile(parent2)) { - if (isJSDocSatisfiesExpression(parent2)) { - return getTypeFromTypeNode(getJSDocSatisfiesExpressionType(parent2)); - } - const typeTag = getJSDocTypeTag(parent2); - if (typeTag && !isConstTypeReference(typeTag.typeExpression.type)) { - return getTypeFromTypeNode(typeTag.typeExpression.type); + case 217 /* ParenthesizedExpression */: + { + if (isInJSFile(parent2)) { + if (isJSDocSatisfiesExpression(parent2)) { + return getTypeFromTypeNode(getJSDocSatisfiesExpressionType(parent2)); + } + const typeTag = getJSDocTypeTag(parent2); + if (typeTag && !isConstTypeReference(typeTag.typeExpression.type)) { + return getTypeFromTypeNode(typeTag.typeExpression.type); + } } + return getContextualType2(parent2, contextFlags); } - return getContextualType2(parent2, contextFlags); - } case 235 /* NonNullExpression */: return getContextualType2(parent2, contextFlags); case 238 /* SatisfiesExpression */: @@ -70696,16 +65590,9 @@ ${lanes.join("\n")} return void 0; } function pushCachedContextualType(node) { - pushContextualType( - node, - getContextualType2( - node, - /*contextFlags*/ - void 0 - ), - /*isCache*/ - true - ); + pushContextualType(node, getContextualType2(node, /*contextFlags*/ + void 0), /*isCache*/ + true); } function pushContextualType(node, type, isCache) { contextualTypeNodes[contextualTypeCount] = node; @@ -70741,11 +65628,8 @@ ${lanes.join("\n")} } function getContextualJsxElementAttributesType(node, contextFlags) { if (isJsxOpeningElement(node) && contextFlags !== 4 /* Completions */) { - const index = findContextualNode( - node.parent, - /*includeCaches*/ - !contextFlags - ); + const index = findContextualNode(node.parent, /*includeCaches*/ + !contextFlags); if (index >= 0) { return contextualTypes[index]; } @@ -70834,8 +65718,7 @@ ${lanes.join("\n")} 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); @@ -70846,10 +65729,7 @@ ${lanes.join("\n")} } } function getIntersectedSignatures(signatures) { - return getStrictOptionValue(compilerOptions, "noImplicitAny") ? reduceLeft( - signatures, - (left, right) => left === right || !left ? left : compareTypeParametersIdentical(left.typeParameters, right.typeParameters) ? combineSignaturesOfIntersectionMembers(left, right) : void 0 - ) : void 0; + return getStrictOptionValue(compilerOptions, "noImplicitAny") ? reduceLeft(signatures, (left, right) => left === right || !left ? left : compareTypeParametersIdentical(left.typeParameters, right.typeParameters) ? combineSignaturesOfIntersectionMembers(left, right) : void 0) : void 0; } function combineIntersectionThisParam(left, right, mapper) { if (!left || !right) { @@ -70882,10 +65762,7 @@ ${lanes.join("\n")} const leftName = i >= leftCount ? void 0 : getParameterNameAtPosition(left, i); const rightName = i >= rightCount ? void 0 : getParameterNameAtPosition(right, i); const paramName = leftName === rightName ? leftName : !leftName ? rightName : !rightName ? leftName : void 0; - const paramSymbol = createSymbol( - 1 /* FunctionScopedVariable */ | (isOptional && !isRestParam ? 16777216 /* Optional */ : 0), - paramName || `arg${i}` - ); + const paramSymbol = createSymbol(1 /* FunctionScopedVariable */ | (isOptional && !isRestParam ? 16777216 /* Optional */ : 0), paramName || `arg${i}`); paramSymbol.links.type = isRestParam ? createArrayType(unionParamType) : unionParamType; params[i] = paramSymbol; } @@ -70909,18 +65786,10 @@ ${lanes.join("\n")} const params = combineIntersectionParameters(left, right, paramMapper); const thisParam = combineIntersectionThisParam(left.thisParameter, right.thisParameter, paramMapper); const minArgCount = Math.max(left.minArgumentCount, right.minArgumentCount); - const result = createSignature( - declaration, - typeParams, - thisParam, - params, - /*resolvedReturnType*/ - void 0, - /*resolvedTypePredicate*/ - void 0, - minArgCount, - (left.flags | right.flags) & 167 /* PropagatingFlags */ - ); + const result = createSignature(declaration, typeParams, thisParam, params, /*resolvedReturnType*/ + void 0, /*resolvedTypePredicate*/ + void 0, minArgCount, (left.flags | right.flags) & 167 /* PropagatingFlags */); + result.compositeKind = 2097152 /* Intersection */; result.compositeSignatures = concatenate(left.compositeKind === 2097152 /* Intersection */ && left.compositeSignatures || [left], [right]); if (paramMapper) { @@ -70930,7 +65799,7 @@ ${lanes.join("\n")} } function getContextualCallSignature(type, node) { const signatures = getSignaturesOfType(type, 0 /* Call */); - const applicableByArity = filter(signatures, (s) => !isAritySmaller(s, node)); + const applicableByArity = filter(signatures, s => !isAritySmaller(s, node)); return applicableByArity.length === 1 ? applicableByArity[0] : getIntersectedSignatures(applicableByArity); } function isAritySmaller(signature, target) { @@ -70969,17 +65838,10 @@ ${lanes.join("\n")} if (signature) { if (!signatureList) { signatureList = [signature]; - } else if (!compareSignaturesIdentical( - signatureList[0], - signature, - /*partialMatch*/ - false, - /*ignoreThisTypes*/ - true, - /*ignoreReturnTypes*/ - true, - compareTypesIdentical - )) { + } else if (!compareSignaturesIdentical(signatureList[0], signature, /*partialMatch*/ + false, /*ignoreThisTypes*/ + true, /*ignoreReturnTypes*/ + true, compareTypesIdentical)) { return void 0; } else { signatureList.push(signature); @@ -70994,6 +65856,7 @@ ${lanes.join("\n")} if (languageVersion < 2 /* ES2015 */) { checkExternalEmitHelpers(node, compilerOptions.downlevelIteration ? 1536 /* SpreadIncludes */ : 1024 /* SpreadArray */); } + const arrayOrIterableType = checkExpression(node.expression, checkMode); return checkIteratedTypeOrElementType(33 /* Spread */, arrayOrIterableType, undefinedType, node.expression); } @@ -71003,6 +65866,7 @@ ${lanes.join("\n")} function hasDefaultValue(node) { return node.kind === 208 /* BindingElement */ && !!node.initializer || node.kind === 226 /* BinaryExpression */ && node.operatorToken.kind === 64 /* EqualsToken */; } + function isSpreadIntoCallOrNew(node) { const parent2 = walkUpParenthesizedExpressions(node.parent); return isSpreadElement(parent2) && isCallOrNewExpression(parent2.parent); @@ -71015,11 +65879,8 @@ ${lanes.join("\n")} pushCachedContextualType(node); const inDestructuringPattern = isAssignmentTarget(node); const inConstContext = isConstContext(node); - const contextualType = getApparentTypeOfContextualType( - node, - /*contextFlags*/ - void 0 - ); + const contextualType = getApparentTypeOfContextualType(node, /*contextFlags*/ + void 0); const inTupleContext = isSpreadIntoCallOrNew(node) || !!contextualType && someType(contextualType, isTupleLikeType); let hasOmittedExpression = false; for (let i = 0; i < elementCount; i++) { @@ -71028,20 +65889,15 @@ ${lanes.join("\n")} if (languageVersion < 2 /* ES2015 */) { checkExternalEmitHelpers(e, compilerOptions.downlevelIteration ? 1536 /* SpreadIncludes */ : 1024 /* SpreadArray */); } + const spreadType = checkExpression(e.expression, checkMode, forceTuple); if (isArrayLikeType(spreadType)) { elementTypes.push(spreadType); elementFlags.push(8 /* Variadic */); } else if (inDestructuringPattern) { - const restElementType = getIndexTypeOfType(spreadType, numberType) || getIteratedTypeOrElementType( - 65 /* Destructuring */, - spreadType, - undefinedType, - /*errorNode*/ - void 0, - /*checkAssignability*/ - false - ) || unknownType; + const restElementType = getIndexTypeOfType(spreadType, numberType) || getIteratedTypeOrElementType(65 /* Destructuring */, spreadType, undefinedType, /*errorNode*/ + void 0, /*checkAssignability*/ + false) || unknownType; elementTypes.push(restElementType); elementFlags.push(4 /* Rest */); } else { @@ -71054,12 +65910,8 @@ ${lanes.join("\n")} elementFlags.push(2 /* Optional */); } else { const type = checkExpressionForMutableLocation(e, checkMode, forceTuple); - elementTypes.push(addOptionality( - type, - /*isProperty*/ - true, - hasOmittedExpression - )); + elementTypes.push(addOptionality(type, /*isProperty*/ + true, hasOmittedExpression)); elementFlags.push(hasOmittedExpression ? 2 /* Optional */ : 1 /* Required */); if (inTupleContext && checkMode && checkMode & 2 /* Inferential */ && !(checkMode & 4 /* SkipContextSensitive */) && isContextSensitive(e)) { const inferenceContext = getInferenceContext(node); @@ -71073,17 +65925,10 @@ ${lanes.join("\n")} return createTupleType(elementTypes, elementFlags); } if (forceTuple || inConstContext || inTupleContext) { - return createArrayLiteralType(createTupleType( - elementTypes, - elementFlags, - /*readonly*/ - inConstContext && !(contextualType && someType(contextualType, isMutableArrayLikeType)) - )); + return createArrayLiteralType(createTupleType(elementTypes, elementFlags, /*readonly*/ + inConstContext && !(contextualType && someType(contextualType, isMutableArrayLikeType)))); } - return createArrayLiteralType(createArrayType( - elementTypes.length ? getUnionType(sameMap(elementTypes, (t, i) => elementFlags[i] & 8 /* Variadic */ ? getIndexedAccessTypeOrUndefined(t, numberType) || anyType : t), 2 /* Subtype */) : strictNullChecks ? implicitNeverType : undefinedWideningType, - inConstContext - )); + return createArrayLiteralType(createArrayType(elementTypes.length ? getUnionType(sameMap(elementTypes, (t, i) => elementFlags[i] & 8 /* Variadic */ ? getIndexedAccessTypeOrUndefined(t, numberType) || anyType : t), 2 /* Subtype */) : strictNullChecks ? implicitNeverType : undefinedWideningType, inConstContext)); } function createArrayLiteralType(type) { if (!(getObjectFlags(type) & 4 /* Reference */)) { @@ -71094,6 +65939,7 @@ ${lanes.join("\n")} literalType = type.literalType = cloneTypeReference(type); literalType.objectFlags |= 16384 /* ArrayLiteral */ | 131072 /* ContainsObjectOrArrayLiteral */; } + return literalType; } function isNumericName(name) { @@ -71112,6 +65958,7 @@ ${lanes.join("\n")} function isNumericComputedName(name) { return isTypeAssignableToKind(checkComputedPropertyName(name), 296 /* NumberLike */); } + function checkComputedPropertyName(node) { const links = getNodeLinks(node.expression); if (!links.resolvedType) { @@ -71128,6 +65975,7 @@ ${lanes.join("\n")} getNodeLinks(node.parent.parent).flags |= 32768 /* BlockScopedBindingInLoop */; } } + if (links.resolvedType.flags & 98304 /* Nullable */ || !isTypeAssignableToKind(links.resolvedType, 402653316 /* StringLike */ | 296 /* NumberLike */ | 12288 /* ESSymbolLike */) && !isTypeAssignableTo(links.resolvedType, stringNumberSymbolType)) { error2(node, Diagnostics.A_computed_property_name_must_be_of_type_string_number_symbol_or_any); } @@ -71144,6 +65992,7 @@ ${lanes.join("\n")} const firstDecl = (_a = symbol.declarations) == null ? void 0 : _a[0]; return isKnownSymbol(symbol) || firstDecl && isNamedDeclaration(firstDecl) && isComputedPropertyName(firstDecl.name) && isTypeAssignableToKind(checkComputedPropertyName(firstDecl.name), 4096 /* ESSymbol */); } + function getObjectLiteralIndexInfo(node, offset, properties, keyType) { const propTypes = []; for (let i = offset; i < properties.length; i++) { @@ -71160,13 +66009,9 @@ ${lanes.join("\n")} const links = getSymbolLinks(symbol); if (!links.immediateTarget) { const node = getDeclarationOfAliasSymbol(symbol); - if (!node) - return Debug.fail(); - links.immediateTarget = getTargetOfAliasDeclaration( - node, - /*dontRecursivelyResolve*/ - true - ); + if (!node) return Debug.fail(); + links.immediateTarget = getTargetOfAliasDeclaration(node, /*dontRecursivelyResolve*/ + true); } return links.immediateTarget; } @@ -71179,11 +66024,8 @@ ${lanes.join("\n")} let propertiesArray = []; let spread = emptyObjectType; pushCachedContextualType(node); - const contextualType = getApparentTypeOfContextualType( - node, - /*contextFlags*/ - void 0 - ); + const contextualType = getApparentTypeOfContextualType(node, /*contextFlags*/ + void 0); const contextualTypeHasPattern = contextualType && contextualType.pattern && (contextualType.pattern.kind === 206 /* ObjectBindingPattern */ || contextualType.pattern.kind === 210 /* ObjectLiteralExpression */); const inConstContext = isConstContext(node); const checkFlags = inConstContext ? 8 /* Readonly */ : 0; @@ -71205,12 +66047,11 @@ ${lanes.join("\n")} let member = getSymbolOfDeclaration(memberDecl); const computedNameType = memberDecl.name && memberDecl.name.kind === 167 /* ComputedPropertyName */ ? checkComputedPropertyName(memberDecl.name) : void 0; if (memberDecl.kind === 303 /* PropertyAssignment */ || memberDecl.kind === 304 /* ShorthandPropertyAssignment */ || isObjectLiteralMethod(memberDecl)) { - let type = memberDecl.kind === 303 /* PropertyAssignment */ ? checkPropertyAssignment(memberDecl, checkMode) : ( - // avoid resolving the left side of the ShorthandPropertyAssignment outside of the destructuring - // for error recovery purposes. For example, if a user wrote `{ a = 100 }` instead of `{ a: 100 }`. - // we don't want to say "could not find 'a'". - memberDecl.kind === 304 /* ShorthandPropertyAssignment */ ? checkExpressionForMutableLocation(!inDestructuringPattern && memberDecl.objectAssignmentInitializer ? memberDecl.objectAssignmentInitializer : memberDecl.name, checkMode) : checkObjectLiteralMethod(memberDecl, checkMode) - ); + let type = memberDecl.kind === 303 /* PropertyAssignment */ ? checkPropertyAssignment(memberDecl, checkMode) : + // avoid resolving the left side of the ShorthandPropertyAssignment outside of the destructuring + // for error recovery purposes. For example, if a user wrote `{ a = 100 }` instead of `{ a: 100 }`. + // we don't want to say "could not find 'a'". + memberDecl.kind === 304 /* ShorthandPropertyAssignment */ ? checkExpressionForMutableLocation(!inDestructuringPattern && memberDecl.objectAssignmentInitializer ? memberDecl.objectAssignmentInitializer : memberDecl.name, checkMode) : checkObjectLiteralMethod(memberDecl, checkMode); if (isInJavascript) { const jsDocType = getTypeForDeclarationFromJSDocComment(memberDecl); if (jsDocType) { @@ -71258,6 +66099,7 @@ ${lanes.join("\n")} if (languageVersion < 2 /* ES2015 */) { checkExternalEmitHelpers(memberDecl, 2 /* Assign */); } + if (propertiesArray.length > 0) { spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, objectFlags, inConstContext); propertiesArray = []; @@ -71306,8 +66148,8 @@ ${lanes.join("\n")} } popContextualType(); if (contextualTypeHasPattern) { - const rootPatternParent = findAncestor(contextualType.pattern.parent, (n) => n.kind === 260 /* VariableDeclaration */ || n.kind === 226 /* BinaryExpression */ || n.kind === 169 /* Parameter */); - const spreadOrOutsideRootObject = findAncestor(node, (n) => n === rootPatternParent || n.kind === 305 /* SpreadAssignment */); + const rootPatternParent = findAncestor(contextualType.pattern.parent, n => n.kind === 260 /* VariableDeclaration */ || n.kind === 226 /* BinaryExpression */ || n.kind === 169 /* Parameter */); + const spreadOrOutsideRootObject = findAncestor(node, n => n === rootPatternParent || n.kind === 305 /* SpreadAssignment */); if (spreadOrOutsideRootObject.kind !== 305 /* SpreadAssignment */) { for (const prop of getPropertiesOfType(contextualType)) { if (!propertiesTable.get(prop.escapedName) && !getPropertyOfType(spread, prop.escapedName)) { @@ -71331,25 +66173,24 @@ ${lanes.join("\n")} hasComputedStringProperty = false; hasComputedNumberProperty = false; } - return mapType(spread, (t) => t === emptyObjectType ? createObjectLiteralType() : t); + return mapType(spread, t => t === emptyObjectType ? createObjectLiteralType() : t); } 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) { result.objectFlags |= 4096 /* JSLiteral */; } + if (patternWithComputedProperties) { result.objectFlags |= 512 /* ObjectLiteralPatternWithComputedProperties */; } + if (inDestructuringPattern) { result.pattern = node; } @@ -71384,10 +66225,7 @@ ${lanes.join("\n")} checkJsxOpeningLikeElementOrOpeningFragment(node.openingFragment); const nodeSourceFile = getSourceFileOfNode(node); if (getJSXTransformEnabled(compilerOptions) && (compilerOptions.jsxFactory || nodeSourceFile.pragmas.has("jsx")) && !compilerOptions.jsxFragmentFactory && !nodeSourceFile.pragmas.has("jsxfrag")) { - error2( - node, - compilerOptions.jsxFactory ? Diagnostics.The_jsxFragmentFactory_compiler_option_must_be_provided_to_use_JSX_fragments_with_the_jsxFactory_compiler_option : Diagnostics.An_jsxFrag_pragma_is_required_when_using_an_jsx_pragma_with_JSX_fragments - ); + error2(node, compilerOptions.jsxFactory ? Diagnostics.The_jsxFragmentFactory_compiler_option_must_be_provided_to_use_JSX_fragments_with_the_jsxFactory_compiler_option : Diagnostics.An_jsxFrag_pragma_is_required_when_using_an_jsx_pragma_with_JSX_fragments); } checkJsxChildren(node); return getJsxElementTypeAt(node) || anyType; @@ -71445,14 +66283,8 @@ ${lanes.join("\n")} } else { Debug.assert(attributeDecl.kind === 293 /* JsxSpreadAttribute */); if (attributesTable.size > 0) { - spread = getSpreadType( - spread, - createJsxAttributesType(), - attributes.symbol, - objectFlags, - /*readonly*/ - false - ); + spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, objectFlags, /*readonly*/ + false); attributesTable = createSymbolTable(); } const exprType = getReducedType(checkExpression(attributeDecl.expression, checkMode & 2 /* Inferential */)); @@ -71460,14 +66292,8 @@ ${lanes.join("\n")} hasSpreadAnyType = true; } if (isValidSpreadType(exprType)) { - spread = getSpreadType( - spread, - exprType, - attributes.symbol, - objectFlags, - /*readonly*/ - false - ); + spread = getSpreadType(spread, exprType, attributes.symbol, objectFlags, /*readonly*/ + false); if (allAttributesTable) { checkSpreadPropOverrides(exprType, allAttributesTable, attributeDecl); } @@ -71479,14 +66305,8 @@ ${lanes.join("\n")} } if (!hasSpreadAnyType) { if (attributesTable.size > 0) { - spread = getSpreadType( - spread, - createJsxAttributesType(), - attributes.symbol, - objectFlags, - /*readonly*/ - false - ); + spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, objectFlags, /*readonly*/ + false); } } const parent2 = openingLikeElement.parent.kind === 284 /* JsxElement */ ? openingLikeElement.parent : void 0; @@ -71496,35 +66316,21 @@ ${lanes.join("\n")} if (explicitlySpecifyChildrenAttribute) { error2(attributes, Diagnostics._0_are_specified_twice_The_attribute_named_0_will_be_overwritten, unescapeLeadingUnderscores(jsxChildrenPropertyName)); } - const contextualType2 = getApparentTypeOfContextualType( - openingLikeElement.attributes, - /*contextFlags*/ - void 0 - ); + const contextualType2 = getApparentTypeOfContextualType(openingLikeElement.attributes, /*contextFlags*/ + void 0); const childrenContextualType = contextualType2 && getTypeOfPropertyOfContextualType(contextualType2, jsxChildrenPropertyName); const childrenPropSymbol = createSymbol(4 /* Property */, jsxChildrenPropertyName); childrenPropSymbol.links.type = childrenTypes.length === 1 ? childrenTypes[0] : childrenContextualType && someType(childrenContextualType, isTupleLikeType) ? createTupleType(childrenTypes) : createArrayType(getUnionType(childrenTypes)); - childrenPropSymbol.valueDeclaration = factory.createPropertySignature( - /*modifiers*/ - void 0, - unescapeLeadingUnderscores(jsxChildrenPropertyName), - /*questionToken*/ - void 0, - /*type*/ - void 0 - ); + childrenPropSymbol.valueDeclaration = factory.createPropertySignature( /*modifiers*/ + void 0, unescapeLeadingUnderscores(jsxChildrenPropertyName), /*questionToken*/ + void 0, /*type*/ + void 0); setParent(childrenPropSymbol.valueDeclaration, attributes); childrenPropSymbol.valueDeclaration.symbol = childrenPropSymbol; const childPropMap = createSymbolTable(); childPropMap.set(jsxChildrenPropertyName, childrenPropSymbol); - spread = getSpreadType( - spread, - createAnonymousType(attributes.symbol, childPropMap, emptyArray, emptyArray, emptyArray), - attributes.symbol, - objectFlags, - /*readonly*/ - false - ); + spread = getSpreadType(spread, createAnonymousType(attributes.symbol, childPropMap, emptyArray, emptyArray, emptyArray), attributes.symbol, objectFlags, /*readonly*/ + false); } } if (hasSpreadAnyType) { @@ -71581,8 +66387,7 @@ ${lanes.join("\n")} 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) { @@ -71640,16 +66445,9 @@ ${lanes.join("\n")} let resolvedNamespace = getJsxNamespaceContainerForImplicitImport(location); if (!resolvedNamespace || resolvedNamespace === unknownSymbol) { const namespaceName = getJsxNamespace(location); - resolvedNamespace = resolveName( - location, - namespaceName, - 1920 /* Namespace */, - /*nameNotFoundMessage*/ - void 0, - namespaceName, - /*isUse*/ - false - ); + resolvedNamespace = resolveName(location, namespaceName, 1920 /* Namespace */, /*nameNotFoundMessage*/ + void 0, namespaceName, /*isUse*/ + false); } if (resolvedNamespace) { const candidate = resolveSymbol(getSymbol2(getExportsOfSymbol(resolveSymbol(resolvedNamespace)), JsxNames.JSX, 1920 /* Namespace */)); @@ -71664,12 +66462,8 @@ ${lanes.join("\n")} links.jsxNamespace = false; } } - const s = resolveSymbol(getGlobalSymbol( - JsxNames.JSX, - 1920 /* Namespace */, - /*diagnostic*/ - void 0 - )); + const s = resolveSymbol(getGlobalSymbol(JsxNames.JSX, 1920 /* Namespace */, /*diagnostic*/ + void 0)); if (s === unknownSymbol) { return void 0; } @@ -71693,9 +66487,11 @@ ${lanes.join("\n")} function getJsxLibraryManagedAttributes(jsxNamespace) { return jsxNamespace && getSymbol2(jsxNamespace.exports, JsxNames.LibraryManagedAttributes, 788968 /* Type */); } + function getJsxElementTypeSymbol(jsxNamespace) { return jsxNamespace && getSymbol2(jsxNamespace.exports, JsxNames.ElementType, 788968 /* Type */); } + function getJsxElementPropertiesName(jsxNamespace) { return getNameFromJsxElementAttributesContainer(JsxNames.ElementAttributesPropertyNameContainer, jsxNamespace); } @@ -71720,8 +66516,9 @@ ${lanes.join("\n")} if (signatures.length === 0) { signatures = getSignaturesOfType(apparentElemType, 0 /* Call */); } + if (signatures.length === 0 && apparentElemType.flags & 1048576 /* Union */) { - signatures = getUnionSignatures(map(apparentElemType.types, (t) => getUninstantiatedJsxSignaturesOfType(t, caller))); + signatures = getUnionSignatures(map(apparentElemType.types, t => getUninstantiatedJsxSignaturesOfType(t, caller))); } return signatures; } @@ -71763,12 +66560,8 @@ ${lanes.join("\n")} } function generateInitialErrorChain() { const componentName = getTextOfNode(openingLikeElement.tagName); - return chainDiagnosticMessages( - /*details*/ - void 0, - Diagnostics._0_cannot_be_used_as_a_JSX_component, - componentName - ); + return chainDiagnosticMessages( /*details*/ + void 0, Diagnostics._0_cannot_be_used_as_a_JSX_component, componentName); } } function getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node) { @@ -71790,8 +66583,7 @@ ${lanes.join("\n")} } 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) { @@ -71805,14 +66597,11 @@ ${lanes.join("\n")} } 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) { @@ -71856,15 +66645,8 @@ ${lanes.join("\n")} const jsxFactoryLocation = isNodeOpeningLikeElement ? node.tagName : node; let jsxFactorySym; if (!(isJsxOpeningFragment(node) && jsxFactoryNamespace === "null")) { - jsxFactorySym = resolveName( - jsxFactoryLocation, - jsxFactoryNamespace, - 111551 /* Value */, - jsxFactoryRefErr, - jsxFactoryNamespace, - /*isUse*/ - true - ); + jsxFactorySym = resolveName(jsxFactoryLocation, jsxFactoryNamespace, 111551 /* Value */, jsxFactoryRefErr, jsxFactoryNamespace, /*isUse*/ + true); } if (jsxFactorySym) { jsxFactorySym.isReferenced = 67108863 /* All */; @@ -71876,15 +66658,8 @@ ${lanes.join("\n")} const file = getSourceFileOfNode(node); const localJsxNamespace = getLocalJsxNamespace(file); if (localJsxNamespace) { - resolveName( - jsxFactoryLocation, - localJsxNamespace, - 111551 /* Value */, - jsxFactoryRefErr, - localJsxNamespace, - /*isUse*/ - true - ); + resolveName(jsxFactoryLocation, localJsxNamespace, 111551 /* Value */, jsxFactoryRefErr, localJsxNamespace, /*isUse*/ + true); } } } @@ -71898,12 +66673,8 @@ ${lanes.join("\n")} const tagType = isJsxIntrinsicTagName(tagName) ? getStringLiteralType(intrinsicTagNameToString(tagName)) : checkExpression(tagName); checkTypeRelatedTo(tagType, elementTypeConstraint, assignableRelation, tagName, Diagnostics.Its_type_0_is_not_a_valid_JSX_element_type, () => { const componentName = getTextOfNode(tagName); - return chainDiagnosticMessages( - /*details*/ - void 0, - Diagnostics._0_cannot_be_used_as_a_JSX_component, - componentName - ); + return chainDiagnosticMessages( /*details*/ + void 0, Diagnostics._0_cannot_be_used_as_a_JSX_component, componentName); }); } else { checkJsxReturnAssignableToAppropriateBound(getJsxReferenceKind(jsxOpeningLikeNode), getReturnTypeOfSignature(sig), jsxOpeningLikeNode); @@ -71951,6 +66722,7 @@ ${lanes.join("\n")} return parent2 && isBinaryExpression(parent2) && getAssignmentDeclarationKind(parent2) === 3 /* PrototypeProperty */; } } + function checkPropertyAccessibility(node, isSuper, writing, type, prop, reportError = true) { const errorNode = !reportError ? void 0 : node.kind === 166 /* QualifiedName */ ? node.right : node.kind === 205 /* ImportType */ ? node : node.kind === 208 /* BindingElement */ && node.propertyName ? node.propertyName : node.name; return checkPropertyAccessibilityAtLocation(node, isSuper, writing, type, prop, errorNode); @@ -72005,7 +66777,7 @@ ${lanes.join("\n")} if (isSuper) { return true; } - let enclosingClass = forEachEnclosingClass(location, (enclosingDeclaration) => { + let enclosingClass = forEachEnclosingClass(location, enclosingDeclaration => { const enclosingClass2 = getDeclaredTypeOfSymbol(getSymbolOfDeclaration(enclosingDeclaration)); return isClassDerivedFromDeclaringClasses(enclosingClass2, prop, writing); }); @@ -72045,24 +66817,22 @@ ${lanes.join("\n")} return void 0; } function getThisParameterFromNodeContext(node) { - const thisContainer = getThisContainer( - node, - /*includeArrowFunctions*/ - false, - /*includeClassComputedPropertyName*/ - false - ); + const thisContainer = getThisContainer(node, /*includeArrowFunctions*/ + false, /*includeClassComputedPropertyName*/ + false); return thisContainer && isFunctionLike(thisContainer) ? getThisParameter(thisContainer) : void 0; } function symbolHasNonMethodDeclaration(symbol) { - return !!forEachProperty2(symbol, (prop) => !(prop.flags & 8192 /* Method */)); + return !!forEachProperty2(symbol, prop => !(prop.flags & 8192 /* Method */)); } + function checkNonNullExpression(node) { return checkNonNullType(checkExpression(node), node); } function isNullableType(type) { return hasTypeFacts(type, 50331648 /* IsUndefinedOrNull */); } + function getNonNullableTypeIfNeeded(type) { return isNullableType(type) ? getNonNullableType(type) : type; } @@ -72077,23 +66847,13 @@ ${lanes.join("\n")} error2(node, Diagnostics.The_value_0_cannot_be_used_here, "undefined"); return; } - error2( - node, - facts & 16777216 /* IsUndefined */ ? facts & 33554432 /* IsNull */ ? Diagnostics._0_is_possibly_null_or_undefined : Diagnostics._0_is_possibly_undefined : Diagnostics._0_is_possibly_null, - nodeText2 - ); + error2(node, facts & 16777216 /* IsUndefined */ ? facts & 33554432 /* IsNull */ ? Diagnostics._0_is_possibly_null_or_undefined : Diagnostics._0_is_possibly_undefined : Diagnostics._0_is_possibly_null, nodeText2); } else { - error2( - node, - facts & 16777216 /* IsUndefined */ ? facts & 33554432 /* IsNull */ ? Diagnostics.Object_is_possibly_null_or_undefined : Diagnostics.Object_is_possibly_undefined : Diagnostics.Object_is_possibly_null - ); + error2(node, facts & 16777216 /* IsUndefined */ ? facts & 33554432 /* IsNull */ ? Diagnostics.Object_is_possibly_null_or_undefined : Diagnostics.Object_is_possibly_undefined : Diagnostics.Object_is_possibly_null); } } function reportCannotInvokePossiblyNullOrUndefinedError(node, facts) { - error2( - node, - facts & 16777216 /* IsUndefined */ ? facts & 33554432 /* IsNull */ ? Diagnostics.Cannot_invoke_an_object_which_is_possibly_null_or_undefined : Diagnostics.Cannot_invoke_an_object_which_is_possibly_undefined : Diagnostics.Cannot_invoke_an_object_which_is_possibly_null - ); + error2(node, facts & 16777216 /* IsUndefined */ ? facts & 33554432 /* IsNull */ ? Diagnostics.Cannot_invoke_an_object_which_is_possibly_null_or_undefined : Diagnostics.Cannot_invoke_an_object_which_is_possibly_undefined : Diagnostics.Cannot_invoke_an_object_which_is_possibly_null); } function checkNonNullTypeWithReporter(type, node, reportError) { if (strictNullChecks && type.flags & 2 /* Unknown */) { @@ -72156,7 +66916,9 @@ ${lanes.join("\n")} } function lookupSymbolForPrivateIdentifierDeclaration(propName, location) { for (let containingClass = getContainingClassExcludingClassDecorators(location); !!containingClass; containingClass = getContainingClass(containingClass)) { - const { symbol } = containingClass; + const { + symbol + } = containingClass; const name = getSymbolNameForPrivateIdentifier(symbol, propName); const prop = symbol.members && symbol.members.get(name) || symbol.exports && symbol.exports.get(name); if (prop) { @@ -72183,13 +66945,9 @@ ${lanes.join("\n")} checkGrammarPrivateIdentifierExpression(privId); const symbol = getSymbolForPrivateIdentifierExpression(privId); if (symbol) { - markPropertyAsReferenced( - symbol, - /*nodeForCheckWriteOnly*/ - void 0, - /*isSelfTypeAccess*/ - false - ); + markPropertyAsReferenced(symbol, /*nodeForCheckWriteOnly*/ + void 0, /*isSelfTypeAccess*/ + false); } return anyType; } @@ -72210,7 +66968,7 @@ ${lanes.join("\n")} let propertyOnType; const properties = getPropertiesOfType(leftType); if (properties) { - forEach(properties, (symbol) => { + forEach(properties, symbol => { const decl = symbol.valueDeclaration; if (decl && isNamedDeclaration(decl) && isPrivateIdentifier(decl.name) && decl.name.escapedText === right.escapedText) { propertyOnType = symbol; @@ -72226,47 +66984,21 @@ ${lanes.join("\n")} const lexicalValueDecl = lexicallyScopedIdentifier.valueDeclaration; const lexicalClass = getContainingClass(lexicalValueDecl); Debug.assert(!!lexicalClass); - if (findAncestor(lexicalClass, (n) => typeClass === n)) { - const diagnostic = error2( - right, - Diagnostics.The_property_0_cannot_be_accessed_on_type_1_within_this_class_because_it_is_shadowed_by_another_private_identifier_with_the_same_spelling, - diagName, - typeToString(leftType) - ); - addRelatedInfo( - diagnostic, - createDiagnosticForNode( - lexicalValueDecl, - Diagnostics.The_shadowing_declaration_of_0_is_defined_here, - diagName - ), - createDiagnosticForNode( - typeValueDecl, - Diagnostics.The_declaration_of_0_that_you_probably_intended_to_use_is_defined_here, - diagName - ) - ); + if (findAncestor(lexicalClass, n => typeClass === n)) { + const diagnostic = error2(right, Diagnostics.The_property_0_cannot_be_accessed_on_type_1_within_this_class_because_it_is_shadowed_by_another_private_identifier_with_the_same_spelling, diagName, typeToString(leftType)); + addRelatedInfo(diagnostic, createDiagnosticForNode(lexicalValueDecl, Diagnostics.The_shadowing_declaration_of_0_is_defined_here, diagName), createDiagnosticForNode(typeValueDecl, Diagnostics.The_declaration_of_0_that_you_probably_intended_to_use_is_defined_here, diagName)); return true; } } - error2( - right, - Diagnostics.Property_0_is_not_accessible_outside_class_1_because_it_has_a_private_identifier, - diagName, - diagnosticName(typeClass.name || anon) - ); + error2(right, Diagnostics.Property_0_is_not_accessible_outside_class_1_because_it_has_a_private_identifier, diagName, diagnosticName(typeClass.name || anon)); return true; } return false; } function isThisPropertyAccessInConstructor(node, prop) { - return (isConstructorDeclaredProperty(prop) || isThisProperty(node) && isAutoTypedProperty(prop)) && getThisContainer( - node, - /*includeArrowFunctions*/ - true, - /*includeClassComputedPropertyName*/ - false - ) === getDeclaringConstructor(prop); + return (isConstructorDeclaredProperty(prop) || isThisProperty(node) && isAutoTypedProperty(prop)) && getThisContainer(node, /*includeArrowFunctions*/ + true, /*includeClassComputedPropertyName*/ + false) === getDeclaringConstructor(prop); } function checkPropertyAccessExpressionOrQualifiedName(node, left, leftType, right, checkMode, writeOnly) { const parentSymbol = getNodeLinks(left).resolvedSymbol; @@ -72279,10 +67011,12 @@ ${lanes.join("\n")} if (assignmentKind !== 0 /* None */) { checkExternalEmitHelpers(node, 1048576 /* ClassPrivateFieldSet */); } + if (assignmentKind !== 1 /* Definite */) { checkExternalEmitHelpers(node, 524288 /* ClassPrivateFieldGet */); } } + const lexicallyScopedSymbol = lookupSymbolForPrivateIdentifierDeclaration(right.escapedText, right); if (assignmentKind && lexicallyScopedSymbol && lexicallyScopedSymbol.valueDeclaration && isMethodDeclaration(lexicallyScopedSymbol.valueDeclaration)) { grammarErrorOnNode(right, Diagnostics.Cannot_assign_to_private_method_0_Private_methods_are_not_writable, idText(right)); @@ -72318,15 +67052,11 @@ ${lanes.join("\n")} } return isErrorType(apparentType) ? errorType : apparentType; } - prop = getPropertyOfType( - apparentType, - right.escapedText, - /*skipObjectFunctionPropertyAugment*/ - isConstEnumObjectType(apparentType), - /*includeTypeOnlyMembers*/ - node.kind === 166 /* QualifiedName */ - ); + prop = getPropertyOfType(apparentType, right.escapedText, /*skipObjectFunctionPropertyAugment*/ + isConstEnumObjectType(apparentType), /*includeTypeOnlyMembers*/ + 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); } @@ -72334,12 +67064,8 @@ ${lanes.join("\n")} if (!prop) { const indexInfo = !isPrivateIdentifier(right) && (assignmentKind === 0 /* None */ || !isGenericObjectType(leftType) || isThisTypeParameter(leftType)) ? getApplicableIndexInfoForName(apparentType, right.escapedText) : void 0; if (!(indexInfo && indexInfo.type)) { - const isUncheckedJS = isUncheckedJSSuggestion( - node, - leftType.symbol, - /*excludeClasses*/ - true - ); + const isUncheckedJS = isUncheckedJSSuggestion(node, leftType.symbol, /*excludeClasses*/ + true); if (!isUncheckedJS && isJSLiteralType(leftType)) { return anyType; } @@ -72389,11 +67115,8 @@ ${lanes.join("\n")} if (file) { if (compilerOptions.checkJs === void 0 && file.checkJsDirective === void 0 && (file.scriptKind === 1 /* JS */ || file.scriptKind === 2 /* JSX */)) { const declarationFile = forEach(suggestion == null ? void 0 : suggestion.declarations, getSourceFileOfNode); - const suggestionHasNoExtendsOrDecorators = !(suggestion == null ? void 0 : suggestion.valueDeclaration) || !isClassLike(suggestion.valueDeclaration) || ((_a = suggestion.valueDeclaration.heritageClauses) == null ? void 0 : _a.length) || classOrConstructorParameterIsDecorated( - /*useLegacyDecorators*/ - false, - suggestion.valueDeclaration - ); + const suggestionHasNoExtendsOrDecorators = !(suggestion == null ? void 0 : suggestion.valueDeclaration) || !isClassLike(suggestion.valueDeclaration) || ((_a = suggestion.valueDeclaration.heritageClauses) == null ? void 0 : _a.length) || classOrConstructorParameterIsDecorated( /*useLegacyDecorators*/ + false, suggestion.valueDeclaration); return !(file !== declarationFile && !!declarationFile && isGlobalSourceFile(declarationFile)) && !(excludeClasses && suggestion && suggestion.flags & 32 /* Class */ && suggestionHasNoExtendsOrDecorators) && !(!!node && excludeClasses && isPropertyAccessExpression(node) && node.expression.kind === 110 /* ThisKeyword */ && suggestionHasNoExtendsOrDecorators); } } @@ -72404,6 +67127,7 @@ ${lanes.join("\n")} if (assignmentKind === 1 /* Definite */) { return removeMissingType(propType, !!(prop && prop.flags & 16777216 /* Optional */)); } + if (prop && !(prop.flags & (3 /* Variable */ | 4 /* Property */ | 98304 /* Accessor */)) && !(prop.flags & 8192 /* Method */ && propType.flags & 1048576 /* Union */) && !isDuplicatedCommonJSExport(prop.declarations)) { return propType; } @@ -72433,7 +67157,9 @@ ${lanes.join("\n")} return assignmentKind ? getBaseTypeOfLiteralType(flowType) : flowType; } function checkPropertyNotUsedBeforeDeclaration(prop, node, right) { - const { valueDeclaration } = prop; + const { + valueDeclaration + } = prop; if (!valueDeclaration || getSourceFileOfNode(node).isDeclarationFile) { return; } @@ -72449,7 +67175,7 @@ ${lanes.join("\n")} } } function isInPropertyInitializerOrClassStaticBlock(node) { - return !!findAncestor(node, (node2) => { + return !!findAncestor(node, node2 => { switch (node2.kind) { case 172 /* PropertyDeclaration */: return true; @@ -72546,7 +67272,7 @@ ${lanes.join("\n")} addErrorOrSuggestion(!isUncheckedJS || errorInfo.code !== Diagnostics.Property_0_may_not_exist_on_type_1_Did_you_mean_2.code, resultDiagnostic); } function containerSeemsToBeEmptyDomElement(containingType) { - return compilerOptions.lib && !compilerOptions.lib.includes("dom") && everyContainedType(containingType, (type) => type.symbol && /^(EventTarget|Node|((HTML[a-zA-Z]*)?Element))$/.test(unescapeLeadingUnderscores(type.symbol.escapedName))) && isEmptyObjectType(containingType); + return compilerOptions.lib && !compilerOptions.lib.includes("dom") && everyContainedType(containingType, type => type.symbol && /^(EventTarget|Node|((HTML[a-zA-Z]*)?Element))$/.test(unescapeLeadingUnderscores(type.symbol.escapedName))) && isEmptyObjectType(containingType); } function typeHasStaticProperty(propName, containingType) { const prop = containingType.symbol && getPropertyOfType(getTypeOfSymbol(containingType.symbol), propName); @@ -72577,60 +67303,49 @@ ${lanes.join("\n")} function getSuggestedSymbolForNonexistentClassMember(name, baseType) { return getSpellingSuggestionForName(name, getPropertiesOfType(baseType), 106500 /* ClassMember */); } + function getSuggestedSymbolForNonexistentProperty(name, containingType) { let props = getPropertiesOfType(containingType); if (typeof name !== "string") { const parent2 = name.parent; if (isPropertyAccessExpression(parent2)) { - props = filter(props, (prop) => isValidPropertyAccessForCompletions(parent2, containingType, prop)); + props = filter(props, prop => isValidPropertyAccessForCompletions(parent2, containingType, prop)); } name = idText(name); } return getSpellingSuggestionForName(name, props, 111551 /* Value */); } + function getSuggestedSymbolForNonexistentJSXAttribute(name, containingType) { const strName = isString(name) ? name : idText(name); const properties = getPropertiesOfType(containingType); - const jsxSpecific = strName === "for" ? find(properties, (x) => symbolName(x) === "htmlFor") : strName === "class" ? find(properties, (x) => symbolName(x) === "className") : void 0; - return jsxSpecific ?? getSpellingSuggestionForName(strName, properties, 111551 /* Value */); + const jsxSpecific = strName === "for" ? find(properties, x => symbolName(x) === "htmlFor") : strName === "class" ? find(properties, x => symbolName(x) === "className") : void 0; + return jsxSpecific !== null && jsxSpecific !== void 0 ? jsxSpecific : getSpellingSuggestionForName(strName, properties, 111551 /* Value */); } + function getSuggestionForNonexistentProperty(name, containingType) { const suggestion = getSuggestedSymbolForNonexistentProperty(name, containingType); return suggestion && symbolName(suggestion); } function getSuggestedSymbolForNonexistentSymbol(location, outerName, meaning) { Debug.assert(outerName !== void 0, "outername should always be defined"); - const result = resolveNameHelper( - location, - outerName, - meaning, - /*nameNotFoundMessage*/ - void 0, - outerName, - /*isUse*/ - false, - /*excludeGlobals*/ - false, - /*getSpellingSuggestions*/ - true, - (symbols, name, meaning2) => { - Debug.assertEqual(outerName, name, "name should equal outerName"); - const symbol = getSymbol2(symbols, name, meaning2); - if (symbol) - return symbol; - let candidates; - if (symbols === globals) { - const primitives = mapDefined( - ["string", "number", "boolean", "object", "bigint", "symbol"], - (s) => symbols.has(s.charAt(0).toUpperCase() + s.slice(1)) ? createSymbol(524288 /* TypeAlias */, s) : void 0 - ); - candidates = primitives.concat(arrayFrom(symbols.values())); - } else { - candidates = arrayFrom(symbols.values()); - } - return getSpellingSuggestionForName(unescapeLeadingUnderscores(name), candidates, meaning2); + const result = resolveNameHelper(location, outerName, meaning, /*nameNotFoundMessage*/ + void 0, outerName, /*isUse*/ + false, /*excludeGlobals*/ + false, /*getSpellingSuggestions*/ + true, (symbols, name, meaning2) => { + Debug.assertEqual(outerName, name, "name should equal outerName"); + const symbol = getSymbol2(symbols, name, meaning2); + if (symbol) return symbol; + let candidates; + if (symbols === globals) { + const primitives = mapDefined(["string", "number", "boolean", "object", "bigint", "symbol"], s => symbols.has(s.charAt(0).toUpperCase() + s.slice(1)) ? createSymbol(524288 /* TypeAlias */, s) : void 0); + candidates = primitives.concat(arrayFrom(symbols.values())); + } else { + candidates = arrayFrom(symbols.values()); } - ); + return getSpellingSuggestionForName(unescapeLeadingUnderscores(name), candidates, meaning2); + }); return result; } function getSuggestionForNonexistentSymbol(location, outerName, meaning) { @@ -72640,6 +67355,7 @@ ${lanes.join("\n")} function getSuggestedSymbolForNonexistentModule(name, targetModule) { return targetModule.exports && getSpellingSuggestionForName(idText(name), getExportsOfModuleAsArray(targetModule), 2623475 /* ModuleMember */); } + function getSuggestionForNonexistentExport(name, targetModule) { const suggestion = getSuggestedSymbolForNonexistentModule(name, targetModule); return suggestion && symbolName(suggestion); @@ -72666,8 +67382,8 @@ ${lanes.join("\n")} return suggestion; } function getSuggestedTypeForNonexistentStringLiteralType(source, target) { - const candidates = target.types.filter((type) => !!(type.flags & 128 /* StringLiteral */)); - return getSpellingSuggestion(source.value, candidates, (type) => type.value); + const candidates = target.types.filter(type => !!(type.flags & 128 /* StringLiteral */)); + return getSpellingSuggestion(source.value, candidates, type => type.value); } function getSpellingSuggestionForName(name, symbols, meaning) { return getSpellingSuggestion(name, symbols, getCandidateName); @@ -72709,6 +67425,7 @@ ${lanes.join("\n")} } (getCheckFlags(prop) & 1 /* Instantiated */ ? getSymbolLinks(prop).target : prop).isReferenced = 67108863 /* All */; } + function isSelfTypeAccess(name, parent2) { return name.kind === 110 /* ThisKeyword */ || !!parent2 && isEntityNameExpression(name) && parent2 === getResolvedSymbol(getFirstIdentifier(name)); } @@ -72717,46 +67434,24 @@ ${lanes.join("\n")} case 211 /* PropertyAccessExpression */: return isValidPropertyAccessWithType(node, node.expression.kind === 108 /* SuperKeyword */, propertyName, getWidenedType(checkExpression(node.expression))); case 166 /* QualifiedName */: - return isValidPropertyAccessWithType( - node, - /*isSuper*/ - false, - propertyName, - getWidenedType(checkExpression(node.left)) - ); + return isValidPropertyAccessWithType(node, /*isSuper*/ + false, propertyName, getWidenedType(checkExpression(node.left))); case 205 /* ImportType */: - return isValidPropertyAccessWithType( - node, - /*isSuper*/ - false, - propertyName, - getTypeFromTypeNode(node) - ); + return isValidPropertyAccessWithType(node, /*isSuper*/ + false, propertyName, getTypeFromTypeNode(node)); } } function isValidPropertyAccessForCompletions(node, type, property) { - return isPropertyAccessible( - node, - node.kind === 211 /* PropertyAccessExpression */ && node.expression.kind === 108 /* SuperKeyword */, - /*isWrite*/ - false, - type, - property - ); + return isPropertyAccessible(node, node.kind === 211 /* PropertyAccessExpression */ && node.expression.kind === 108 /* SuperKeyword */, /*isWrite*/ + false, type, property); } function isValidPropertyAccessWithType(node, isSuper, propertyName, type) { if (isTypeAny(type)) { return true; } const prop = getPropertyOfType(type, propertyName); - return !!prop && isPropertyAccessible( - node, - isSuper, - /*isWrite*/ - false, - type, - prop - ); + return !!prop && isPropertyAccessible(node, isSuper, /*isWrite*/ + false, type, prop); } function isPropertyAccessible(node, isSuper, isWrite, containingType, property) { if (isTypeAny(containingType)) { @@ -72764,7 +67459,7 @@ ${lanes.join("\n")} } if (property.valueDeclaration && isPrivateIdentifierClassElementDeclaration(property.valueDeclaration)) { const declClass = getContainingClass(property.valueDeclaration); - return !isOptionalChain(node) && !!findAncestor(node, (parent2) => parent2 === declClass); + return !isOptionalChain(node) && !!findAncestor(node, parent2 => parent2 === declClass); } return checkPropertyAccessibilityAtLocation(node, isSuper, isWrite, containingType, property); } @@ -72839,7 +67534,7 @@ ${lanes.join("\n")} } else if (isBinaryExpression(node)) { checkExpression(node.left); } else if (isCallOrNewExpression(node)) { - forEach(node.arguments, (argument) => { + forEach(node.arguments, argument => { checkExpression(argument); }); } @@ -72891,9 +67586,11 @@ ${lanes.join("\n")} function acceptsVoid(t) { return !!(t.flags & 16384 /* Void */); } + function acceptsVoidUndefinedUnknownOrAny(t) { return !!(t.flags & (16384 /* Void */ | 32768 /* Undefined */ | 2 /* Unknown */ | 1 /* Any */)); } + function hasCorrectArity(node, args, signature, signatureHelpTrailingComma = false) { let argCount; let callIsIncomplete = false; @@ -72952,25 +67649,13 @@ ${lanes.join("\n")} return !some(typeArguments) || typeArguments.length >= minTypeArgumentCount && typeArguments.length <= numTypeParameters; } function getSingleCallSignature(type) { - return getSingleSignature( - type, - 0 /* Call */, - /*allowMembers*/ - false - ); + return getSingleSignature(type, 0 /* Call */, /*allowMembers*/ + false); } function getSingleCallOrConstructSignature(type) { - return getSingleSignature( - type, - 0 /* Call */, - /*allowMembers*/ - false - ) || getSingleSignature( - type, - 1 /* Construct */, - /*allowMembers*/ - false - ); + return getSingleSignature(type, 0 /* Call */, /*allowMembers*/ + false) || getSingleSignature(type, 1 /* Construct */, /*allowMembers*/ + false); } function getSingleSignature(type, kind, allowMembers) { if (type.flags & 524288 /* Object */) { @@ -72999,6 +67684,7 @@ ${lanes.join("\n")} inferTypes(context.inferences, source, target, 128 /* ReturnType */); }); } + return getSignatureInstantiation(signature, getInferredTypes(context), isInJSFile(contextualSignature.declaration)); } function inferJsxTypeArguments(node, signature, checkMode, context) { @@ -73019,7 +67705,7 @@ ${lanes.join("\n")} return inferJsxTypeArguments(node, signature, checkMode, context); } if (node.kind !== 170 /* Decorator */ && node.kind !== 226 /* BinaryExpression */) { - const skipBindingPatterns = every(signature.typeParameters, (p) => !!getDefaultFromTypeParameter(p)); + const skipBindingPatterns = every(signature.typeParameters, p => !!getDefaultFromTypeParameter(p)); const contextualType = getContextualType2(node, skipBindingPatterns ? 8 /* SkipBindingPatterns */ : 0 /* None */); if (contextualType) { const inferenceTargetType = getReturnTypeOfSignature(signature); @@ -73033,6 +67719,7 @@ ${lanes.join("\n")} const inferenceSourceType = contextualSignature && contextualSignature.typeParameters ? getOrCreateTypeFromSignature(getSignatureInstantiationWithoutFillingInTypeArguments(contextualSignature, contextualSignature.typeParameters)) : instantiatedType; inferTypes(context.inferences, inferenceSourceType, inferenceTargetType, 128 /* ReturnType */); } + const returnContext = createInferenceContext(signature.typeParameters, signature, context.flags); const returnSourceType = instantiateType(contextualType, outerContext && outerContext.returnMapper); inferTypes(returnContext.inferences, returnSourceType, inferenceTargetType); @@ -73043,7 +67730,7 @@ ${lanes.join("\n")} const restType = getNonArrayRestType(signature); const argCount = restType ? Math.min(getParameterCount(signature) - 1, args.length) : args.length; if (restType && restType.flags & 262144 /* TypeParameter */) { - const info = find(context.inferences, (info2) => info2.typeParameter === restType); + const info = find(context.inferences, info2 => info2.typeParameter === restType); if (info) { info.impliedArity = findIndex(args, isSpreadArgument, argCount) < 0 ? args.length - argCount : void 0; } @@ -73070,14 +67757,10 @@ ${lanes.join("\n")} return getInferredTypes(context); } function getMutableArrayOrTupleType(type) { - return type.flags & 1048576 /* Union */ ? mapType(type, getMutableArrayOrTupleType) : type.flags & 1 /* Any */ || isMutableArrayOrTuple(getBaseConstraintOfType(type) || type) ? type : isTupleType(type) ? createTupleType( - getElementTypes(type), - type.target.elementFlags, - /*readonly*/ - false, - type.target.labeledElementDeclarations - ) : createTupleType([type], [8 /* Variadic */]); + return type.flags & 1048576 /* Union */ ? mapType(type, getMutableArrayOrTupleType) : type.flags & 1 /* Any */ || isMutableArrayOrTuple(getBaseConstraintOfType(type) || type) ? type : isTupleType(type) ? createTupleType(getElementTypes(type), type.target.elementFlags, /*readonly*/ + false, type.target.labeledElementDeclarations) : createTupleType([type], [8 /* Variadic */]); } + function getSpreadArgumentType(args, index, argCount, restType, context, checkMode) { const inConstContext = isConstTypeVariable(restType); if (index >= argCount - 1) { @@ -73111,6 +67794,7 @@ ${lanes.join("\n")} types.push(hasPrimitiveContextualType ? getRegularTypeOfLiteralType(argType) : getWidenedLiteralType(argType)); flags.push(1 /* Required */); } + if (arg.kind === 237 /* SyntheticExpression */ && arg.tupleNameSource) { names.push(arg.tupleNameSource); } else { @@ -73128,23 +67812,14 @@ ${lanes.join("\n")} Debug.assert(typeParameters[i] !== void 0, "Should not call checkTypeArguments with too many type arguments"); const constraint = getConstraintOfTypeParameter(typeParameters[i]); if (constraint) { - const errorInfo = reportErrors2 && headMessage ? () => chainDiagnosticMessages( - /*details*/ - void 0, - Diagnostics.Type_0_does_not_satisfy_the_constraint_1 - ) : void 0; + const errorInfo = reportErrors2 && headMessage ? () => chainDiagnosticMessages( /*details*/ + void 0, Diagnostics.Type_0_does_not_satisfy_the_constraint_1) : void 0; const typeArgumentHeadMessage = headMessage || Diagnostics.Type_0_does_not_satisfy_the_constraint_1; if (!mapper) { mapper = createTypeMapper(typeParameters, typeArgumentTypes); } const typeArgument = typeArgumentTypes[i]; - if (!checkTypeAssignableTo( - typeArgument, - getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument), - reportErrors2 ? typeArgumentNodes[i] : void 0, - typeArgumentHeadMessage, - errorInfo - )) { + if (!checkTypeAssignableTo(typeArgument, getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument), reportErrors2 ? typeArgumentNodes[i] : void 0, typeArgumentHeadMessage, errorInfo)) { return void 0; } } @@ -73155,36 +67830,26 @@ ${lanes.join("\n")} if (isJsxIntrinsicTagName(node.tagName)) { return 2 /* Mixed */; } + const tagType = getApparentType(checkExpression(node.tagName)); if (length(getSignaturesOfType(tagType, 1 /* Construct */))) { return 0 /* Component */; } + if (length(getSignaturesOfType(tagType, 0 /* Call */))) { return 1 /* Function */; } + return 2 /* Mixed */; } + function checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation, checkMode, reportErrors2, containingMessageChain, errorOutputContainer) { const paramType = getEffectiveFirstArgumentForJsxSignature(signature, node); - const attributesType = checkExpressionWithContextualType( - node.attributes, - paramType, - /*inferenceContext*/ - void 0, - checkMode - ); + const attributesType = checkExpressionWithContextualType(node.attributes, paramType, /*inferenceContext*/ + void 0, checkMode); const checkAttributesType = checkMode & 4 /* SkipContextSensitive */ ? getRegularTypeOfObjectLiteral(attributesType) : attributesType; - return checkTagNameDoesNotExpectTooManyArguments() && checkTypeRelatedToAndOptionallyElaborate( - checkAttributesType, - paramType, - relation, - reportErrors2 ? node.tagName : void 0, - node.attributes, - /*headMessage*/ - void 0, - containingMessageChain, - errorOutputContainer - ); + return checkTagNameDoesNotExpectTooManyArguments() && checkTypeRelatedToAndOptionallyElaborate(checkAttributesType, paramType, relation, reportErrors2 ? node.tagName : void 0, node.attributes, /*headMessage*/ + void 0, containingMessageChain, errorOutputContainer); function checkTagNameDoesNotExpectTooManyArguments() { var _a; if (getJsxNamespaceContainerForImplicitImport(node)) { @@ -73202,15 +67867,9 @@ ${lanes.join("\n")} if (!factory2) { return true; } - const factorySymbol = resolveEntityName( - factory2, - 111551 /* Value */, - /*ignoreErrors*/ - true, - /*dontResolveAlias*/ - false, - node - ); + const factorySymbol = resolveEntityName(factory2, 111551 /* Value */, /*ignoreErrors*/ + true, /*dontResolveAlias*/ + false, node); if (!factorySymbol) { return true; } @@ -73224,8 +67883,7 @@ ${lanes.join("\n")} 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)) { @@ -73267,7 +67925,10 @@ ${lanes.join("\n")} } } function getSignatureApplicabilityError(node, args, signature, relation, checkMode, reportErrors2, containingMessageChain) { - const errorOutputContainer = { errors: void 0, skipLogging: true }; + const errorOutputContainer = { + errors: void 0, + skipLogging: true + }; if (isJsxOpeningLikeElement(node)) { if (!checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation, checkMode, reportErrors2, containingMessageChain, errorOutputContainer)) { Debug.assert(!reportErrors2 || !!errorOutputContainer.errors, "jsx should have errors when reporting errors"); @@ -73293,13 +67954,8 @@ ${lanes.join("\n")} const arg = args[i]; if (arg.kind !== 232 /* OmittedExpression */) { const paramType = getTypeAtPosition(signature, i); - const argType = checkExpressionWithContextualType( - arg, - paramType, - /*inferenceContext*/ - void 0, - checkMode - ); + const argType = checkExpressionWithContextualType(arg, paramType, /*inferenceContext*/ + void 0, checkMode); const checkArgType = checkMode & 4 /* SkipContextSensitive */ ? getRegularTypeOfObjectLiteral(argType) : argType; if (!checkTypeRelatedToAndOptionallyElaborate(checkArgType, paramType, relation, reportErrors2 ? arg : void 0, arg, headMessage, containingMessageChain, errorOutputContainer)) { Debug.assert(!reportErrors2 || !!errorOutputContainer.errors, "parameter should have errors when reporting errors"); @@ -73309,27 +67965,12 @@ ${lanes.join("\n")} } } if (restType) { - const spreadType = getSpreadArgumentType( - args, - argCount, - args.length, - restType, - /*context*/ - void 0, - checkMode - ); + const spreadType = getSpreadArgumentType(args, argCount, args.length, restType, /*context*/ + void 0, checkMode); const restArgCount = args.length - argCount; const errorNode = !reportErrors2 ? void 0 : restArgCount === 0 ? node : restArgCount === 1 ? args[argCount] : setTextRangePosEnd(createSyntheticExpression(node, spreadType), args[argCount].pos, args[args.length - 1].end); - if (!checkTypeRelatedTo( - spreadType, - restType, - relation, - errorNode, - headMessage, - /*containingMessageChain*/ - void 0, - errorOutputContainer - )) { + if (!checkTypeRelatedTo(spreadType, restType, relation, errorNode, headMessage, /*containingMessageChain*/ + void 0, errorOutputContainer)) { Debug.assert(!reportErrors2 || !!errorOutputContainer.errors, "rest parameter should have errors when reporting errors"); maybeAddMissingAwaitInfo(errorNode, spreadType, restType); return errorOutputContainer.errors || emptyArray; @@ -73371,7 +68012,7 @@ ${lanes.join("\n")} const template = node.template; const args2 = [createSyntheticExpression(template, getGlobalTemplateStringsArrayType())]; if (template.kind === 228 /* TemplateExpression */) { - forEach(template.templateSpans, (span) => { + forEach(template.templateSpans, span => { args2.push(span.expression); }); } @@ -73454,11 +68095,19 @@ ${lanes.join("\n")} start = expressionSpan.start; length2 = doNotIncludeArguments ? expressionSpan.length : node.end - start; } - return { start, length: length2, sourceFile }; + return { + start, + length: length2, + sourceFile + }; } function getDiagnosticForCallNode(node, message, ...args) { if (isCallExpression(node)) { - const { sourceFile, start, length: length2 } = getDiagnosticSpanForCallNode(node); + const { + sourceFile, + start, + length: length2 + } = getDiagnosticSpanForCallNode(node); if ("message" in message) { return createFileDiagnostic(sourceFile, start, length2, message, ...args); } @@ -73471,34 +68120,20 @@ ${lanes.join("\n")} } } function isPromiseResolveArityError(node) { - if (!isCallExpression(node) || !isIdentifier(node.expression)) - return false; - const symbol = resolveName( - node.expression, - node.expression.escapedText, - 111551 /* Value */, - /*nameNotFoundMessage*/ - void 0, - /*nameArg*/ - void 0, - /*isUse*/ - false - ); + if (!isCallExpression(node) || !isIdentifier(node.expression)) return false; + const symbol = resolveName(node.expression, node.expression.escapedText, 111551 /* Value */, /*nameNotFoundMessage*/ + void 0, /*nameArg*/ + void 0, /*isUse*/ + false); const decl = symbol == null ? void 0 : symbol.valueDeclaration; if (!decl || !isParameter(decl) || !isFunctionExpressionOrArrowFunction(decl.parent) || !isNewExpression(decl.parent.parent) || !isIdentifier(decl.parent.parent.expression)) { return false; } - const globalPromiseSymbol = getGlobalPromiseConstructorSymbol( - /*reportErrors*/ - false - ); - if (!globalPromiseSymbol) - return false; - const constructorSymbol = getSymbolAtLocation( - decl.parent.parent.expression, - /*ignoreErrors*/ - true - ); + const globalPromiseSymbol = getGlobalPromiseConstructorSymbol( /*reportErrors*/ + false); + if (!globalPromiseSymbol) return false; + const constructorSymbol = getSymbolAtLocation(decl.parent.parent.expression, /*ignoreErrors*/ + true); return constructorSymbol === globalPromiseSymbol; } function getArgumentArityError(node, signatures, args, headMessage) { @@ -73520,10 +68155,8 @@ ${lanes.join("\n")} 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; @@ -73534,14 +68167,8 @@ ${lanes.join("\n")} const error3 = isDecorator(node) ? hasRestParameter2 ? Diagnostics.The_runtime_will_invoke_the_decorator_with_1_arguments_but_the_decorator_expects_at_least_0 : Diagnostics.The_runtime_will_invoke_the_decorator_with_1_arguments_but_the_decorator_expects_0 : hasRestParameter2 ? Diagnostics.Expected_at_least_0_arguments_but_got_1 : isVoidPromiseError ? Diagnostics.Expected_0_arguments_but_got_1_Did_you_forget_to_include_void_in_your_type_argument_to_Promise : Diagnostics.Expected_0_arguments_but_got_1; if (min2 < args.length && args.length < max) { if (headMessage) { - let chain = chainDiagnosticMessages( - /*details*/ - void 0, - Diagnostics.No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments, - args.length, - maxBelow, - minAbove - ); + let chain = chainDiagnosticMessages( /*details*/ + void 0, Diagnostics.No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments, args.length, maxBelow, minAbove); chain = chainDiagnosticMessages(chain, headMessage); return getDiagnosticForCallNode(node, chain); } @@ -73549,13 +68176,8 @@ ${lanes.join("\n")} } else if (args.length < min2) { let diagnostic; if (headMessage) { - let chain = chainDiagnosticMessages( - /*details*/ - void 0, - error3, - parameterRange, - args.length - ); + let chain = chainDiagnosticMessages( /*details*/ + void 0, error3, parameterRange, args.length); chain = chainDiagnosticMessages(chain, headMessage); diagnostic = getDiagnosticForCallNode(node, chain); } else { @@ -73577,13 +68199,8 @@ ${lanes.join("\n")} } setTextRangePosEnd(errorSpan, pos, end); if (headMessage) { - let chain = chainDiagnosticMessages( - /*details*/ - void 0, - error3, - parameterRange, - args.length - ); + let chain = chainDiagnosticMessages( /*details*/ + void 0, error3, parameterRange, args.length); chain = chainDiagnosticMessages(chain, headMessage); return createDiagnosticForNodeArrayFromMessageChain(getSourceFileOfNode(node), errorSpan, chain); } @@ -73597,13 +68214,8 @@ ${lanes.join("\n")} const min2 = getMinTypeArgumentCount(sig.typeParameters); const max = length(sig.typeParameters); if (headMessage) { - let chain = chainDiagnosticMessages( - /*details*/ - void 0, - Diagnostics.Expected_0_type_arguments_but_got_1, - min2 < max ? min2 + "-" + max : min2, - argCount - ); + let chain = chainDiagnosticMessages( /*details*/ + void 0, Diagnostics.Expected_0_type_arguments_but_got_1, min2 < max ? min2 + "-" + max : min2, argCount); chain = chainDiagnosticMessages(chain, headMessage); return createDiagnosticForNodeArrayFromMessageChain(getSourceFileOfNode(node), typeArguments, chain); } @@ -73622,27 +68234,16 @@ ${lanes.join("\n")} } if (belowArgCount !== -Infinity && aboveArgCount !== Infinity) { if (headMessage) { - let chain = chainDiagnosticMessages( - /*details*/ - void 0, - Diagnostics.No_overload_expects_0_type_arguments_but_overloads_do_exist_that_expect_either_1_or_2_type_arguments, - argCount, - belowArgCount, - aboveArgCount - ); + let chain = chainDiagnosticMessages( /*details*/ + void 0, Diagnostics.No_overload_expects_0_type_arguments_but_overloads_do_exist_that_expect_either_1_or_2_type_arguments, argCount, belowArgCount, aboveArgCount); chain = chainDiagnosticMessages(chain, headMessage); return createDiagnosticForNodeArrayFromMessageChain(getSourceFileOfNode(node), typeArguments, chain); } return createDiagnosticForNodeArray(getSourceFileOfNode(node), typeArguments, Diagnostics.No_overload_expects_0_type_arguments_but_overloads_do_exist_that_expect_either_1_or_2_type_arguments, argCount, belowArgCount, aboveArgCount); } if (headMessage) { - let chain = chainDiagnosticMessages( - /*details*/ - void 0, - Diagnostics.Expected_0_type_arguments_but_got_1, - belowArgCount === -Infinity ? aboveArgCount : belowArgCount, - argCount - ); + let chain = chainDiagnosticMessages( /*details*/ + void 0, Diagnostics.Expected_0_type_arguments_but_got_1, belowArgCount === -Infinity ? aboveArgCount : belowArgCount, argCount); chain = chainDiagnosticMessages(chain, headMessage); return createDiagnosticForNodeArrayFromMessageChain(getSourceFileOfNode(node), typeArguments, chain); } @@ -73698,16 +68299,8 @@ ${lanes.join("\n")} if (headMessage) { chain = chainDiagnosticMessages(chain, headMessage); } - const diags = getSignatureApplicabilityError( - node, - args, - last2, - assignableRelation, - 0 /* Normal */, - /*reportErrors*/ - true, - () => chain - ); + const diags = getSignatureApplicabilityError(node, args, last2, assignableRelation, 0 /* Normal */, /*reportErrors*/ + true, () => chain); if (diags) { for (const d of diags) { if (last2.declaration && candidatesForArgumentError.length > 3) { @@ -73726,24 +68319,10 @@ ${lanes.join("\n")} let minIndex = 0; let i = 0; for (const c of candidatesForArgumentError) { - const chain2 = () => chainDiagnosticMessages( - /*details*/ - void 0, - Diagnostics.Overload_0_of_1_2_gave_the_following_error, - i + 1, - candidates.length, - signatureToString(c) - ); - const diags2 = getSignatureApplicabilityError( - node, - args, - c, - assignableRelation, - 0 /* Normal */, - /*reportErrors*/ - true, - chain2 - ); + const chain2 = () => chainDiagnosticMessages( /*details*/ + void 0, Diagnostics.Overload_0_of_1_2_gave_the_following_error, i + 1, candidates.length, signatureToString(c)); + const diags2 = getSignatureApplicabilityError(node, args, c, assignableRelation, 0 /* Normal */, /*reportErrors*/ + true, chain2); if (diags2) { if (diags2.length <= min2) { min2 = diags2.length; @@ -73758,18 +68337,27 @@ ${lanes.join("\n")} } const diags = max > 1 ? allDiagnostics[minIndex] : flatten(allDiagnostics); Debug.assert(diags.length > 0, "No errors reported for 3 or fewer overload signatures"); - let chain = chainDiagnosticMessages( - map(diags, createDiagnosticMessageChainFromDiagnostic), - Diagnostics.No_overload_matches_this_call - ); + let chain = chainDiagnosticMessages(map(diags, createDiagnosticMessageChainFromDiagnostic), Diagnostics.No_overload_matches_this_call); if (headMessage) { chain = chainDiagnosticMessages(chain, headMessage); } - const related = [...flatMap(diags, (d) => d.relatedInformation)]; + const related = [...flatMap(diags, d => d.relatedInformation)]; let diag2; - if (every(diags, (d) => d.start === diags[0].start && d.length === diags[0].length && d.file === diags[0].file)) { - const { file, start, length: length2 } = diags[0]; - diag2 = { file, start, length: length2, code: chain.code, category: chain.category, messageText: chain, relatedInformation: related }; + if (every(diags, d => d.start === diags[0].start && d.length === diags[0].length && d.file === diags[0].file)) { + const { + file, + start, + length: length2 + } = diags[0]; + diag2 = { + file, + start, + length: length2, + code: chain.code, + category: chain.category, + messageText: chain, + relatedInformation: related + }; } else { diag2 = createDiagnosticForNodeFromMessageChain(getSourceFileOfNode(node), node, chain, related); } @@ -73779,15 +68367,10 @@ ${lanes.join("\n")} } else if (candidateForArgumentArityError) { diagnostics.add(getArgumentArityError(node, [candidateForArgumentArityError], args, headMessage)); } else if (candidateForTypeArgumentError) { - checkTypeArguments( - candidateForTypeArgumentError, - node.typeArguments, - /*reportErrors*/ - true, - headMessage - ); + checkTypeArguments(candidateForTypeArgumentError, node.typeArguments, /*reportErrors*/ + true, headMessage); } else { - const signaturesWithCorrectTypeArgumentArity = filter(signatures, (s) => hasCorrectTypeArgumentArity(s, typeArguments)); + const signaturesWithCorrectTypeArgumentArity = filter(signatures, s => hasCorrectTypeArgumentArity(s, typeArguments)); if (signaturesWithCorrectTypeArgumentArity.length === 0) { diagnostics.add(getTypeArgumentArityError(node, signatures, typeArguments, headMessage)); } else { @@ -73803,7 +68386,7 @@ ${lanes.join("\n")} const oldCandidateForTypeArgumentError = candidateForTypeArgumentError; const failedSignatureDeclarations = ((_b = (_a = failed.declaration) == null ? void 0 : _a.symbol) == null ? void 0 : _b.declarations) || emptyArray; const isOverload = failedSignatureDeclarations.length > 1; - const implDecl = isOverload ? find(failedSignatureDeclarations, (d) => isFunctionLikeDeclaration(d) && nodeIsPresent(d.body)) : void 0; + const implDecl = isOverload ? find(failedSignatureDeclarations, d => isFunctionLikeDeclaration(d) && nodeIsPresent(d.body)) : void 0; if (implDecl) { const candidate = getSignatureFromDeclaration(implDecl); const isSingleNonGenericCandidate2 = !candidate.typeParameters; @@ -73824,17 +68407,9 @@ ${lanes.join("\n")} if (some(typeArguments) || !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma2)) { return void 0; } - if (getSignatureApplicabilityError( - node, - args, - candidate, - relation, - 0 /* Normal */, - /*reportErrors*/ - false, - /*containingMessageChain*/ - void 0 - )) { + if (getSignatureApplicabilityError(node, args, candidate, relation, 0 /* Normal */, /*reportErrors*/ + false, /*containingMessageChain*/ + void 0)) { candidatesForArgumentError = [candidate]; return void 0; } @@ -73850,26 +68425,20 @@ ${lanes.join("\n")} if (candidate.typeParameters) { let typeArgumentTypes; if (some(typeArguments)) { - typeArgumentTypes = checkTypeArguments( - candidate, - typeArguments, - /*reportErrors*/ - false - ); + typeArgumentTypes = checkTypeArguments(candidate, typeArguments, /*reportErrors*/ + false); if (!typeArgumentTypes) { candidateForTypeArgumentError = candidate; continue; } } else { - inferenceContext = createInferenceContext( - candidate.typeParameters, - candidate, - /*flags*/ - isInJSFile(node) ? 2 /* AnyDefault */ : 0 /* None */ - ); + inferenceContext = createInferenceContext(candidate.typeParameters, candidate, /*flags*/ + isInJSFile(node) ? 2 /* AnyDefault */ : 0 /* None */); + typeArgumentTypes = inferTypeArguments(node, candidate, args, argCheckMode | 8 /* SkipGenericFunctions */, inferenceContext); argCheckMode |= inferenceContext.flags & 4 /* SkippedGenericFunction */ ? 8 /* SkipGenericFunctions */ : 0 /* Normal */; } + checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, isInJSFile(candidate.declaration), inferenceContext && inferenceContext.inferredTypeParameters); if (getNonArrayRestType(candidate) && !hasCorrectArity(node, args, checkCandidate, signatureHelpTrailingComma2)) { candidateForArgumentArityError = checkCandidate; @@ -73878,17 +68447,9 @@ ${lanes.join("\n")} } else { checkCandidate = candidate; } - if (getSignatureApplicabilityError( - node, - args, - checkCandidate, - relation, - argCheckMode, - /*reportErrors*/ - false, - /*containingMessageChain*/ - void 0 - )) { + if (getSignatureApplicabilityError(node, args, checkCandidate, relation, argCheckMode, /*reportErrors*/ + false, /*containingMessageChain*/ + void 0)) { (candidatesForArgumentError || (candidatesForArgumentError = [])).push(checkCandidate); continue; } @@ -73902,17 +68463,9 @@ ${lanes.join("\n")} continue; } } - if (getSignatureApplicabilityError( - node, - args, - checkCandidate, - relation, - argCheckMode, - /*reportErrors*/ - false, - /*containingMessageChain*/ - void 0 - )) { + if (getSignatureApplicabilityError(node, args, checkCandidate, relation, argCheckMode, /*reportErrors*/ + false, /*containingMessageChain*/ + void 0)) { (candidatesForArgumentError || (candidatesForArgumentError = [])).push(checkCandidate); continue; } @@ -73926,45 +68479,42 @@ ${lanes.join("\n")} function getCandidateForOverloadFailure(node, candidates, args, hasCandidatesOutArray, checkMode) { Debug.assert(candidates.length > 0); checkNodeDeferred(node); - return hasCandidatesOutArray || candidates.length === 1 || candidates.some((c) => !!c.typeParameters) ? pickLongestCandidateSignature(node, candidates, args, checkMode) : createUnionOfSignaturesForOverloadFailure(candidates); + return hasCandidatesOutArray || candidates.length === 1 || candidates.some(c => !!c.typeParameters) ? pickLongestCandidateSignature(node, candidates, args, checkMode) : createUnionOfSignaturesForOverloadFailure(candidates); } function createUnionOfSignaturesForOverloadFailure(candidates) { - const thisParameters = mapDefined(candidates, (c) => c.thisParameter); + const thisParameters = mapDefined(candidates, c => c.thisParameter); let thisParameter; if (thisParameters.length) { thisParameter = createCombinedSymbolFromTypes(thisParameters, thisParameters.map(getTypeOfParameter)); } - const { min: minArgumentCount, max: maxNonRestParam } = minAndMax(candidates, getNumNonRestParameters); + const { + min: minArgumentCount, + max: maxNonRestParam + } = minAndMax(candidates, getNumNonRestParameters); const parameters = []; for (let i = 0; i < maxNonRestParam; i++) { - const symbols = mapDefined(candidates, (s) => signatureHasRestParameter(s) ? i < s.parameters.length - 1 ? s.parameters[i] : last(s.parameters) : i < s.parameters.length ? s.parameters[i] : void 0); + const symbols = mapDefined(candidates, s => signatureHasRestParameter(s) ? i < s.parameters.length - 1 ? s.parameters[i] : last(s.parameters) : i < s.parameters.length ? s.parameters[i] : void 0); Debug.assert(symbols.length !== 0); - parameters.push(createCombinedSymbolFromTypes(symbols, mapDefined(candidates, (candidate) => tryGetTypeAtPosition(candidate, i)))); + parameters.push(createCombinedSymbolFromTypes(symbols, mapDefined(candidates, candidate => tryGetTypeAtPosition(candidate, i)))); } - const restParameterSymbols = mapDefined(candidates, (c) => signatureHasRestParameter(c) ? last(c.parameters) : void 0); + const restParameterSymbols = mapDefined(candidates, c => signatureHasRestParameter(c) ? last(c.parameters) : void 0); let flags = 128 /* IsSignatureCandidateForOverloadFailure */; if (restParameterSymbols.length !== 0) { const type = createArrayType(getUnionType(mapDefined(candidates, tryGetRestTypeOfSignature), 2 /* Subtype */)); parameters.push(createCombinedSymbolForOverloadFailure(restParameterSymbols, type)); flags |= 1 /* HasRestParameter */; } + if (candidates.some(signatureHasLiteralTypes)) { flags |= 2 /* HasLiteralTypes */; } - return createSignature( - candidates[0].declaration, - /*typeParameters*/ - void 0, - // Before calling this we tested for `!candidates.some(c => !!c.typeParameters)`. - thisParameter, - parameters, - /*resolvedReturnType*/ - getIntersectionType(candidates.map(getReturnTypeOfSignature)), - /*resolvedTypePredicate*/ - void 0, - minArgumentCount, - flags - ); + + return createSignature(candidates[0].declaration, /*typeParameters*/ + void 0, + // Before calling this we tested for `!candidates.some(c => !!c.typeParameters)`. + thisParameter, parameters, /*resolvedReturnType*/ + getIntersectionType(candidates.map(getReturnTypeOfSignature)), /*resolvedTypePredicate*/ + void 0, minArgumentCount, flags); } function getNumNonRestParameters(signature) { const numParams = signature.parameters.length; @@ -73973,13 +68523,16 @@ ${lanes.join("\n")} function createCombinedSymbolFromTypes(sources, types) { return createCombinedSymbolForOverloadFailure(sources, getUnionType(types, 2 /* Subtype */)); } + function createCombinedSymbolForOverloadFailure(sources, type) { return createSymbolWithType(first(sources), type); } function pickLongestCandidateSignature(node, candidates, args, checkMode) { const bestIndex = getLongestCandidateIndex(candidates, apparentArgumentCount === void 0 ? args.length : apparentArgumentCount); const candidate = candidates[bestIndex]; - const { typeParameters } = candidate; + const { + typeParameters + } = candidate; if (!typeParameters) { return candidate; } @@ -73999,12 +68552,9 @@ ${lanes.join("\n")} return typeArguments; } function inferSignatureInstantiationForOverloadFailure(node, typeParameters, candidate, args, checkMode) { - const inferenceContext = createInferenceContext( - typeParameters, - candidate, - /*flags*/ - isInJSFile(node) ? 2 /* AnyDefault */ : 0 /* None */ - ); + const inferenceContext = createInferenceContext(typeParameters, candidate, /*flags*/ + isInJSFile(node) ? 2 /* AnyDefault */ : 0 /* None */); + const typeArgumentTypes = inferTypeArguments(node, candidate, args, checkMode | 4 /* SkipContextSensitive */ | 8 /* SkipGenericFunctions */, inferenceContext); return createSignatureInstantiation(candidate, typeArgumentTypes); } @@ -74040,6 +68590,7 @@ ${lanes.join("\n")} return resolveCall(node, baseConstructors, candidatesOutArray, checkMode, 0 /* None */); } } + return resolveUntypedCall(node); } let callChainFlags; @@ -74051,11 +68602,8 @@ ${lanes.join("\n")} } else { callChainFlags = 0 /* None */; } - funcType = checkNonNullTypeWithReporter( - funcType, - node.expression, - reportCannotInvokePossiblyNullOrUndefinedError - ); + + funcType = checkNonNullTypeWithReporter(funcType, node.expression, reportCannotInvokePossiblyNullOrUndefinedError); if (funcType === silentNeverType) { return silentNeverSignature; } @@ -74078,12 +68626,8 @@ ${lanes.join("\n")} let relatedInformation; if (node.arguments.length === 1) { const text = getSourceFileOfNode(node).text; - if (isLineBreak(text.charCodeAt(skipTrivia( - text, - node.expression.end, - /*stopAfterLineBreak*/ - true - ) - 1))) { + if (isLineBreak(text.charCodeAt(skipTrivia(text, node.expression.end, /*stopAfterLineBreak*/ + true) - 1))) { relatedInformation = createDiagnosticForNode(node.expression, Diagnostics.Are_you_missing_a_semicolon); } } @@ -74095,7 +68639,7 @@ ${lanes.join("\n")} skippedGenericFunction(node, checkMode); return resolvingSignature; } - if (callSignatures.some((sig) => isInJSFile(sig.declaration) && !!getJSDocClassTag(sig.declaration))) { + if (callSignatures.some(sig => isInJSFile(sig.declaration) && !!getJSDocClassTag(sig.declaration))) { error2(node, Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType)); return resolveErrorCall(node); } @@ -74133,7 +68677,7 @@ ${lanes.join("\n")} if (!isConstructorAccessible(node, constructSignatures[0])) { return resolveErrorCall(node); } - if (someSignature(constructSignatures, (signature) => !!(signature.flags & 4 /* Abstract */))) { + if (someSignature(constructSignatures, signature => !!(signature.flags & 4 /* Abstract */))) { error2(node, Diagnostics.Cannot_create_an_instance_of_an_abstract_class); return resolveErrorCall(node); } @@ -74144,6 +68688,7 @@ ${lanes.join("\n")} } return resolveCall(node, constructSignatures, candidatesOutArray, checkMode, 0 /* None */); } + const callSignatures = getSignaturesOfType(expressionType, 0 /* Call */); if (callSignatures.length) { const signature = resolveCall(node, callSignatures, candidatesOutArray, checkMode, 0 /* None */); @@ -74162,7 +68707,7 @@ ${lanes.join("\n")} } function someSignature(signatures, f) { if (isArray(signatures)) { - return some(signatures, (signature) => someSignature(signature, f)); + return some(signatures, signature => someSignature(signature, f)); } return signatures.compositeKind === 1048576 /* Union */ ? some(signatures.compositeSignatures, f) : f(signatures); } @@ -74242,16 +68787,8 @@ ${lanes.join("\n")} } } else { if (!errorInfo) { - errorInfo = chainDiagnosticMessages( - errorInfo, - isCall ? Diagnostics.Type_0_has_no_call_signatures : Diagnostics.Type_0_has_no_construct_signatures, - typeToString(constituent) - ); - errorInfo = chainDiagnosticMessages( - errorInfo, - isCall ? Diagnostics.Not_all_constituents_of_type_0_are_callable : Diagnostics.Not_all_constituents_of_type_0_are_constructable, - typeToString(apparentType) - ); + errorInfo = chainDiagnosticMessages(errorInfo, isCall ? Diagnostics.Type_0_has_no_call_signatures : Diagnostics.Type_0_has_no_construct_signatures, typeToString(constituent)); + errorInfo = chainDiagnosticMessages(errorInfo, isCall ? Diagnostics.Not_all_constituents_of_type_0_are_callable : Diagnostics.Not_all_constituents_of_type_0_are_constructable, typeToString(apparentType)); } if (hasSignatures) { break; @@ -74259,30 +68796,20 @@ ${lanes.join("\n")} } } if (!hasSignatures) { - errorInfo = chainDiagnosticMessages( - /*details*/ - void 0, - isCall ? Diagnostics.No_constituent_of_type_0_is_callable : Diagnostics.No_constituent_of_type_0_is_constructable, - typeToString(apparentType) - ); + errorInfo = chainDiagnosticMessages( /*details*/ + void 0, isCall ? Diagnostics.No_constituent_of_type_0_is_callable : Diagnostics.No_constituent_of_type_0_is_constructable, typeToString(apparentType)); } if (!errorInfo) { - errorInfo = chainDiagnosticMessages( - errorInfo, - isCall ? Diagnostics.Each_member_of_the_union_type_0_has_signatures_but_none_of_those_signatures_are_compatible_with_each_other : Diagnostics.Each_member_of_the_union_type_0_has_construct_signatures_but_none_of_those_signatures_are_compatible_with_each_other, - typeToString(apparentType) - ); + errorInfo = chainDiagnosticMessages(errorInfo, isCall ? Diagnostics.Each_member_of_the_union_type_0_has_signatures_but_none_of_those_signatures_are_compatible_with_each_other : Diagnostics.Each_member_of_the_union_type_0_has_construct_signatures_but_none_of_those_signatures_are_compatible_with_each_other, typeToString(apparentType)); } } else { - errorInfo = chainDiagnosticMessages( - errorInfo, - isCall ? Diagnostics.Type_0_has_no_call_signatures : Diagnostics.Type_0_has_no_construct_signatures, - typeToString(apparentType) - ); + errorInfo = chainDiagnosticMessages(errorInfo, isCall ? Diagnostics.Type_0_has_no_call_signatures : Diagnostics.Type_0_has_no_construct_signatures, typeToString(apparentType)); } let headMessage = isCall ? Diagnostics.This_expression_is_not_callable : Diagnostics.This_expression_is_not_constructable; if (isCallExpression(errorTarget.parent) && errorTarget.parent.arguments.length === 0) { - const { resolvedSymbol } = getNodeLinks(errorTarget); + const { + resolvedSymbol + } = getNodeLinks(errorTarget); if (resolvedSymbol && resolvedSymbol.flags & 32768 /* GetAccessor */) { headMessage = Diagnostics.This_expression_is_not_callable_because_it_is_a_get_accessor_Did_you_mean_to_use_it_without; } @@ -74293,17 +68820,20 @@ ${lanes.join("\n")} }; } function invocationError(errorTarget, apparentType, kind, relatedInformation) { - const { messageChain, relatedMessage: relatedInfo } = invocationErrorDetails(errorTarget, apparentType, kind); + const { + messageChain, + relatedMessage: relatedInfo + } = invocationErrorDetails(errorTarget, apparentType, kind); const diagnostic = createDiagnosticForNodeFromMessageChain(getSourceFileOfNode(errorTarget), errorTarget, messageChain); if (relatedInfo) { addRelatedInfo(diagnostic, createDiagnosticForNode(errorTarget, relatedInfo)); } if (isCallExpression(errorTarget.parent)) { - const { start, length: length2 } = getDiagnosticSpanForCallNode( - errorTarget.parent, - /*doNotIncludeArguments*/ - true - ); + const { + start, + length: length2 + } = getDiagnosticSpanForCallNode(errorTarget.parent, /*doNotIncludeArguments*/ + true); diagnostic.start = start; diagnostic.length = length2; } @@ -74317,8 +68847,7 @@ ${lanes.join("\n")} 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)); } } @@ -74344,6 +68873,7 @@ ${lanes.join("\n")} } return resolveCall(node, callSignatures, candidatesOutArray, checkMode, 0 /* None */); } + function getDiagnosticHeadMessageForDecoratorResolution(node) { switch (node.parent.kind) { case 263 /* ClassDeclaration */: @@ -74373,11 +68903,8 @@ ${lanes.join("\n")} return resolveUntypedCall(node); } if (isPotentiallyUncalledDecorator(node, callSignatures) && !isParenthesizedExpression(node.expression)) { - const nodeStr = getTextOfNode( - node.expression, - /*includeTrivia*/ - false - ); + const nodeStr = getTextOfNode(node.expression, /*includeTrivia*/ + false); error2(node, Diagnostics._0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write_0, nodeStr); return resolveErrorCall(node); } @@ -74400,52 +68927,27 @@ ${lanes.join("\n")} const exports = namespace && getExportsOfSymbol(namespace); const typeSymbol = exports && getSymbol2(exports, JsxNames.Element, 788968 /* Type */); const returnNode = typeSymbol && nodeBuilder.symbolToEntityName(typeSymbol, 788968 /* Type */, node); - const declaration = factory.createFunctionTypeNode( - /*typeParameters*/ - void 0, - [factory.createParameterDeclaration( - /*modifiers*/ - void 0, - /*dotDotDotToken*/ - void 0, - "props", - /*questionToken*/ - void 0, - nodeBuilder.typeToTypeNode(result, node) - )], - returnNode ? factory.createTypeReferenceNode( - returnNode, - /*typeArguments*/ - void 0 - ) : factory.createKeywordTypeNode(133 /* AnyKeyword */) - ); + const declaration = factory.createFunctionTypeNode( /*typeParameters*/ + void 0, [factory.createParameterDeclaration( /*modifiers*/ + void 0, /*dotDotDotToken*/ + void 0, "props", /*questionToken*/ + void 0, nodeBuilder.typeToTypeNode(result, node))], returnNode ? factory.createTypeReferenceNode(returnNode, /*typeArguments*/ + void 0) : factory.createKeywordTypeNode(133 /* AnyKeyword */)); + const parameterSymbol = createSymbol(1 /* FunctionScopedVariable */, "props"); parameterSymbol.links.type = result; - return createSignature( - declaration, - /*typeParameters*/ - void 0, - /*thisParameter*/ - void 0, - [parameterSymbol], - typeSymbol ? getDeclaredTypeOfSymbol(typeSymbol) : errorType, - /*resolvedTypePredicate*/ - void 0, - 1, - 0 /* None */ - ); + return createSignature(declaration, /*typeParameters*/ + void 0, /*thisParameter*/ + void 0, [parameterSymbol], typeSymbol ? getDeclaredTypeOfSymbol(typeSymbol) : errorType, /*resolvedTypePredicate*/ + void 0, 1, 0 /* None */); } + function resolveJsxOpeningLikeElement(node, candidatesOutArray, checkMode) { if (isJsxIntrinsicTagName(node.tagName)) { const result = getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node); const fakeSignature = createSignatureForJSXIntrinsic(node, result); - checkTypeAssignableToAndOptionallyElaborate(checkExpressionWithContextualType( - node.attributes, - getEffectiveFirstArgumentForJsxSignature(fakeSignature, node), - /*inferenceContext*/ - void 0, - 0 /* Normal */ - ), result, node.tagName, node.attributes); + checkTypeAssignableToAndOptionallyElaborate(checkExpressionWithContextualType(node.attributes, getEffectiveFirstArgumentForJsxSignature(fakeSignature, node), /*inferenceContext*/ + void 0, 0 /* Normal */), result, node.tagName, node.attributes); if (length(node.typeArguments)) { forEach(node.typeArguments, checkSourceElement); diagnostics.add(createDiagnosticForNodeArray(getSourceFileOfNode(node), node.typeArguments, Diagnostics.Expected_0_type_arguments_but_got_1, 0, length(node.typeArguments))); @@ -74458,13 +68960,8 @@ ${lanes.join("\n")} return resolveErrorCall(node); } const signatures = getUninstantiatedJsxSignaturesOfType(exprTypes, node); - if (isUntypedFunctionCall( - exprTypes, - apparentType, - signatures.length, - /*constructSignatures*/ - 0 - )) { + if (isUntypedFunctionCall(exprTypes, apparentType, signatures.length, /*constructSignatures*/ + 0)) { return resolveUntypedCall(node); } if (signatures.length === 0) { @@ -74473,6 +68970,7 @@ ${lanes.join("\n")} } return resolveCall(node, signatures, candidatesOutArray, checkMode, 0 /* None */); } + function resolveInstanceofExpression(node, candidatesOutArray, checkMode) { const rightType = checkExpression(node.right); if (!isTypeAny(rightType)) { @@ -74498,7 +68996,7 @@ ${lanes.join("\n")} return anySignature; } function isPotentiallyUncalledDecorator(decorator, signatures) { - return signatures.length && every(signatures, (signature) => signature.minArgumentCount === 0 && !signatureHasRestParameter(signature) && signature.parameters.length < getDecoratorArgumentCount(decorator, signature)); + return signatures.length && every(signatures, signature => signature.minArgumentCount === 0 && !signatureHasRestParameter(signature) && signature.parameters.length < getDecoratorArgumentCount(decorator, signature)); } function resolveSignature(node, candidatesOutArray, checkMode) { switch (node.kind) { @@ -74541,10 +69039,8 @@ ${lanes.join("\n")} } 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); } @@ -74565,7 +69061,7 @@ ${lanes.join("\n")} if ((_b = source.members) == null ? void 0 : _b.size) { mergeSymbolTable(inferred.members, source.members); } - (links.inferredClassSymbol || (links.inferredClassSymbol = /* @__PURE__ */ new Map())).set(getSymbolId(inferred), inferred); + (links.inferredClassSymbol || (links.inferredClassSymbol = /* @__PURE__ */new Map())).set(getSymbolId(inferred), inferred); return inferred; } return links.inferredClassSymbol.get(getSymbolId(target)); @@ -74573,11 +69069,8 @@ ${lanes.join("\n")} } function getAssignedClassSymbol(decl) { var _a; - const assignmentSymbol = decl && getSymbolOfExpando( - decl, - /*allowDeclaration*/ - true - ); + const assignmentSymbol = decl && getSymbolOfExpando(decl, /*allowDeclaration*/ + true); const prototype = (_a = assignmentSymbol == null ? void 0 : assignmentSymbol.exports) == null ? void 0 : _a.get("prototype"); const init = (prototype == null ? void 0 : prototype.valueDeclaration) && getAssignedJSPrototype(prototype.valueDeclaration); return init ? getSymbolOfDeclaration(init) : void 0; @@ -74637,12 +69130,8 @@ ${lanes.join("\n")} function checkCallExpression(node, checkMode) { var _a, _b, _c; checkGrammarTypeArguments(node, node.typeArguments); - const signature = getResolvedSignature( - node, - /*candidatesOutArray*/ - void 0, - checkMode - ); + const signature = getResolvedSignature(node, /*candidatesOutArray*/ + void 0, checkMode); if (signature === resolvingSignature) { return silentNeverType; } @@ -74675,11 +69164,8 @@ ${lanes.join("\n")} } } if (isInJSFile(node)) { - const jsSymbol = getSymbolOfExpando( - node, - /*allowDeclaration*/ - false - ); + const jsSymbol = getSymbolOfExpando(node, /*allowDeclaration*/ + false); if ((_c = jsSymbol == null ? void 0 : jsSymbol.exports) == null ? void 0 : _c.size) { const jsAssignmentType = createAnonymousType(jsSymbol, jsSymbol.exports, emptyArray, emptyArray, emptyArray); jsAssignmentType.objectFlags |= 4096 /* JSLiteral */; @@ -74689,8 +69175,7 @@ ${lanes.join("\n")} 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)); @@ -74721,8 +69206,7 @@ ${lanes.join("\n")} } } 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; @@ -74730,24 +69214,15 @@ ${lanes.join("\n")} if (!isIdentifier(left) || left.escapedText !== "Symbol") { return false; } - const globalESSymbol = getGlobalESSymbolConstructorSymbol( - /*reportErrors*/ - false - ); + const globalESSymbol = getGlobalESSymbolConstructorSymbol( /*reportErrors*/ + false); if (!globalESSymbol) { return false; } - return globalESSymbol === resolveName( - left, - "Symbol", - 111551 /* Value */, - /*nameNotFoundMessage*/ - void 0, - /*nameArg*/ - void 0, - /*isUse*/ - false - ); + return globalESSymbol === resolveName(left, "Symbol", 111551 /* Value */, /*nameNotFoundMessage*/ + void 0, /*nameArg*/ + void 0, /*isUse*/ + false); } function checkImportCallExpression(node) { checkGrammarImportCallExpression(node); @@ -74764,29 +69239,19 @@ ${lanes.join("\n")} error2(specifier, Diagnostics.Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0, typeToString(specifierType)); } if (optionsType) { - const importCallOptionsType = getGlobalImportCallOptionsType( - /*reportErrors*/ - true - ); + const importCallOptionsType = getGlobalImportCallOptionsType( /*reportErrors*/ + true); if (importCallOptionsType !== emptyObjectType) { checkTypeAssignableTo(optionsType, getNullableType(importCallOptionsType, 32768 /* Undefined */), node.arguments[1]); } } const moduleSymbol = resolveExternalModuleName(node, specifier); if (moduleSymbol) { - const esModuleSymbol = resolveESModuleSymbol( - moduleSymbol, - specifier, - /*dontResolveAlias*/ - true, - /*suppressInteropError*/ - false - ); + const esModuleSymbol = resolveESModuleSymbol(moduleSymbol, specifier, /*dontResolveAlias*/ + true, /*suppressInteropError*/ + false); if (esModuleSymbol) { - return createPromiseReturnType( - node, - getTypeWithSyntheticDefaultOnly(getTypeOfSymbol(esModuleSymbol), esModuleSymbol, moduleSymbol, specifier) || getTypeWithSyntheticDefaultImportType(getTypeOfSymbol(esModuleSymbol), esModuleSymbol, moduleSymbol, specifier) - ); + return createPromiseReturnType(node, getTypeWithSyntheticDefaultOnly(getTypeOfSymbol(esModuleSymbol), esModuleSymbol, moduleSymbol, specifier) || getTypeWithSyntheticDefaultImportType(getTypeOfSymbol(esModuleSymbol), esModuleSymbol, moduleSymbol, specifier)); } } return createPromiseReturnType(node, anyType); @@ -74818,26 +69283,15 @@ ${lanes.join("\n")} const synthType = type; if (!synthType.syntheticType) { const file = (_a = originalSymbol.declarations) == null ? void 0 : _a.find(isSourceFile); - const hasSyntheticDefault = canHaveSyntheticDefault( - file, - originalSymbol, - /*dontResolveAlias*/ - false, - moduleSpecifier - ); + const hasSyntheticDefault = canHaveSyntheticDefault(file, originalSymbol, /*dontResolveAlias*/ + false, moduleSpecifier); if (hasSyntheticDefault) { const anonymousSymbol = createSymbol(2048 /* TypeLiteral */, "__type" /* Type */); const defaultContainingObject = createDefaultPropertyWrapperForModule(symbol, originalSymbol, anonymousSymbol); anonymousSymbol.links.type = defaultContainingObject; - synthType.syntheticType = isValidSpreadType(type) ? getSpreadType( - type, - defaultContainingObject, - anonymousSymbol, - /*objectFlags*/ - 0, - /*readonly*/ - false - ) : defaultContainingObject; + synthType.syntheticType = isValidSpreadType(type) ? getSpreadType(type, defaultContainingObject, anonymousSymbol, /*objectFlags*/ + 0, /*readonly*/ + false) : defaultContainingObject; } else { synthType.syntheticType = type; } @@ -74847,26 +69301,15 @@ ${lanes.join("\n")} return type; } function isCommonJsRequire(node) { - if (!isRequireCall( - node, - /*requireStringLiteralLikeArgument*/ - true - )) { + if (!isRequireCall(node, /*requireStringLiteralLikeArgument*/ + true)) { return false; } - if (!isIdentifier(node.expression)) - return Debug.fail(); - const resolvedRequire = resolveName( - node.expression, - node.expression.escapedText, - 111551 /* Value */, - /*nameNotFoundMessage*/ - void 0, - /*nameArg*/ - void 0, - /*isUse*/ - true - ); + if (!isIdentifier(node.expression)) return Debug.fail(); + const resolvedRequire = resolveName(node.expression, node.expression.escapedText, 111551 /* Value */, /*nameNotFoundMessage*/ + void 0, /*nameArg*/ + void 0, /*isUse*/ + true); if (resolvedRequire === requireSymbol) { return true; } @@ -74878,14 +69321,15 @@ ${lanes.join("\n")} const decl = getDeclarationOfKind(resolvedRequire, targetDeclarationKind); return !!decl && !!(decl.flags & 33554432 /* Ambient */); } + return false; } function checkTaggedTemplateExpression(node) { - if (!checkGrammarTaggedTemplateChain(node)) - checkGrammarTypeArguments(node, node.typeArguments); + if (!checkGrammarTaggedTemplateChain(node)) checkGrammarTypeArguments(node, node.typeArguments); if (languageVersion < 2 /* ES2015 */) { checkExternalEmitHelpers(node, 262144 /* MakeTemplateObject */); } + const signature = getResolvedSignature(node); checkDeprecatedSignature(signature, node); return getReturnTypeOfSignature(signature); @@ -74920,18 +69364,18 @@ ${lanes.join("\n")} case 211 /* PropertyAccessExpression */: case 212 /* ElementAccessExpression */: const expr = skipParentheses(node.expression); - const symbol = isEntityNameExpression(expr) ? resolveEntityName( - expr, - 111551 /* Value */, - /*ignoreErrors*/ - true - ) : void 0; + const symbol = isEntityNameExpression(expr) ? resolveEntityName(expr, 111551 /* Value */, /*ignoreErrors*/ + true) : void 0; return !!(symbol && symbol.flags & 384 /* Enum */); } + return false; } function checkAssertionWorker(node, checkMode) { - const { type, expression } = getAssertionTypeAndExpression(node); + const { + type, + expression + } = getAssertionTypeAndExpression(node); const exprType = checkExpression(expression, checkMode); if (isConstTypeReference(type)) { if (!isValidConstAssertionArgument(expression)) { @@ -74959,10 +69403,15 @@ ${lanes.join("\n")} expression = node.expression; break; } - return { type, expression }; + return { + type, + expression + }; } function checkAssertionDeferred(node) { - const { type } = getAssertionTypeAndExpression(node); + const { + type + } = getAssertionTypeAndExpression(node); const errNode = isParenthesizedExpression(node) ? type : node; const links = getNodeLinks(node); Debug.assertIsDefined(links.assertionExpressionType); @@ -75016,7 +69465,8 @@ ${lanes.join("\n")} const result2 = getInstantiatedTypePart(type); hasSomeApplicableSignature || (hasSomeApplicableSignature = hasApplicableSignature); if (hasSignatures && !hasApplicableSignature) { - nonApplicableType ?? (nonApplicableType = type); + var _nonApplicableType; + (_nonApplicableType = nonApplicableType) !== null && _nonApplicableType !== void 0 ? _nonApplicableType : nonApplicableType = type; } return result2; function getInstantiatedTypePart(type2) { @@ -75027,14 +69477,8 @@ ${lanes.join("\n")} hasSignatures || (hasSignatures = resolved.callSignatures.length !== 0 || resolved.constructSignatures.length !== 0); hasApplicableSignature || (hasApplicableSignature = callSignatures.length !== 0 || constructSignatures.length !== 0); if (callSignatures !== resolved.callSignatures || constructSignatures !== resolved.constructSignatures) { - const result3 = createAnonymousType( - /*symbol*/ - void 0, - resolved.members, - callSignatures, - constructSignatures, - resolved.indexInfos - ); + const result3 = createAnonymousType( /*symbol*/ + void 0, resolved.members, callSignatures, constructSignatures, resolved.indexInfos); result3.objectFlags |= 8388608 /* InstantiationExpressionType */; result3.node = node; return result3; @@ -75056,14 +69500,10 @@ ${lanes.join("\n")} } } function getInstantiatedSignatures(signatures) { - const applicableSignatures = filter(signatures, (sig) => !!sig.typeParameters && hasCorrectTypeArgumentArity(sig, typeArguments)); - return sameMap(applicableSignatures, (sig) => { - const typeArgumentTypes = checkTypeArguments( - sig, - typeArguments, - /*reportErrors*/ - true - ); + const applicableSignatures = filter(signatures, sig => !!sig.typeParameters && hasCorrectTypeArgumentArity(sig, typeArguments)); + return sameMap(applicableSignatures, sig => { + const typeArgumentTypes = checkTypeArguments(sig, typeArguments, /*reportErrors*/ + true); return typeArgumentTypes ? getSignatureInstantiation(sig, typeArgumentTypes, isInJSFile(sig.declaration)) : sig; }); } @@ -75078,7 +69518,7 @@ ${lanes.join("\n")} if (isErrorType(targetType)) { return targetType; } - const errorNode = findAncestor(target.parent, (n) => n.kind === 238 /* SatisfiesExpression */ || n.kind === 357 /* JSDocSatisfiesTag */); + const errorNode = findAncestor(target.parent, n => n.kind === 238 /* SatisfiesExpression */ || n.kind === 357 /* JSDocSatisfiesTag */); checkTypeAssignableToAndOptionallyElaborate(exprType, targetType, errorNode, expression, Diagnostics.Type_0_does_not_satisfy_the_expected_type_1); return exprType; } @@ -75130,13 +69570,9 @@ ${lanes.join("\n")} } function getTypeOfParameter(symbol) { const declaration = symbol.valueDeclaration; - return addOptionality( - getTypeOfSymbol(symbol), - /*isProperty*/ - false, - /*isOptional*/ - !!declaration && (hasInitializer(declaration) || isOptionalDeclaration(declaration)) - ); + return addOptionality(getTypeOfSymbol(symbol), /*isProperty*/ + false, /*isOptional*/ + !!declaration && (hasInitializer(declaration) || isOptionalDeclaration(declaration))); } function getTupleElementLabel(d, index, restParameterName = "arg") { if (!d) { @@ -75187,12 +69623,20 @@ ${lanes.join("\n")} const isRestTupleElement = !!(associatedName == null ? void 0 : associatedName.dotDotDotToken); if (associatedName) { Debug.assert(isIdentifier(associatedName.name)); - return { parameter: associatedName.name, parameterName: associatedName.name.escapedText, isRestParameter: isRestTupleElement }; + return { + parameter: associatedName.name, + parameterName: associatedName.name.escapedText, + isRestParameter: isRestTupleElement + }; } return void 0; } if (pos === paramCount) { - return { parameter: restIdent, parameterName: restParameter.escapedName, isRestParameter: true }; + return { + parameter: restIdent, + parameterName: restParameter.escapedName, + isRestParameter: true + }; } return void 0; } @@ -75252,6 +69696,7 @@ ${lanes.join("\n")} types.push(restType); flags.push(8 /* Variadic */); } + names.push(getNameableDeclarationAtPosition(source, i)); } return createTupleType(types, flags, readonly, names); @@ -75274,7 +69719,7 @@ ${lanes.join("\n")} if (signatureHasRestParameter(signature)) { const restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); if (isTupleType(restType)) { - const firstOptionalIndex = findIndex(restType.target.elementFlags, (f) => !(f & 1 /* Required */)); + const firstOptionalIndex = findIndex(restType.target.elementFlags, f => !(f & 1 /* Required */)); const requiredCount = firstOptionalIndex < 0 ? restType.target.fixedLength : firstOptionalIndex; if (requiredCount > 0) { minArgumentCount = signature.parameters.length - 1 + requiredCount; @@ -75336,12 +69781,8 @@ ${lanes.join("\n")} const declaration = signature.parameters[i].valueDeclaration; const typeNode = getEffectiveTypeAnnotationNode(declaration); if (typeNode) { - const source = addOptionality( - getTypeFromTypeNode(typeNode), - /*isProperty*/ - false, - isOptionalDeclaration(declaration) - ); + const source = addOptionality(getTypeFromTypeNode(typeNode), /*isProperty*/ + false, isOptionalDeclaration(declaration)); const target = getTypeAtPosition(context, i); inferTypes(inferenceContext.inferences, source, target); } @@ -75359,11 +69800,8 @@ ${lanes.join("\n")} const parameter = signature.thisParameter; if (!parameter || parameter.valueDeclaration && !parameter.valueDeclaration.type) { if (!parameter) { - signature.thisParameter = createSymbolWithType( - context.thisParameter, - /*type*/ - void 0 - ); + signature.thisParameter = createSymbolWithType(context.thisParameter, /*type*/ + void 0); } assignParameterType(signature.thisParameter, getTypeOfSymbol(context.thisParameter)); } @@ -75396,17 +69834,10 @@ ${lanes.join("\n")} const links = getSymbolLinks(parameter); if (!links.type) { const declaration = parameter.valueDeclaration; - links.type = addOptionality( - contextualType || (declaration ? getWidenedTypeForVariableLikeDeclaration( - declaration, - /*reportErrors*/ - true - ) : getTypeOfSymbol(parameter)), - /*isProperty*/ - false, - /*isOptional*/ - !!declaration && !declaration.initializer && isOptionalDeclaration(declaration) - ); + links.type = addOptionality(contextualType || (declaration ? getWidenedTypeForVariableLikeDeclaration(declaration, /*reportErrors*/ + true) : getTypeOfSymbol(parameter)), /*isProperty*/ + false, /*isOptional*/ + !!declaration && !declaration.initializer && isOptionalDeclaration(declaration)); if (declaration && declaration.name.kind !== 80 /* Identifier */) { if (links.type === unknownType) { links.type = getTypeFromBindingPattern(declaration.name); @@ -75420,12 +69851,8 @@ ${lanes.join("\n")} function assignBindingElementTypes(pattern, parentType) { for (const element of pattern.elements) { if (!isOmittedExpression(element)) { - const type = getBindingElementTypeFromParentType( - element, - parentType, - /*noTupleBoundsCheck*/ - false - ); + const type = getBindingElementTypeFromParentType(element, parentType, /*noTupleBoundsCheck*/ + false); if (element.name.kind === 80 /* Identifier */) { getSymbolLinks(getSymbolOfDeclaration(element)).type = type; } else { @@ -75435,40 +69862,28 @@ ${lanes.join("\n")} } } function createClassDecoratorContextType(classType) { - return tryCreateTypeReference(getGlobalClassDecoratorContextType( - /*reportErrors*/ - true - ), [classType]); + return tryCreateTypeReference(getGlobalClassDecoratorContextType( /*reportErrors*/ + true), [classType]); } function createClassMethodDecoratorContextType(thisType, valueType) { - return tryCreateTypeReference(getGlobalClassMethodDecoratorContextType( - /*reportErrors*/ - true - ), [thisType, valueType]); + return tryCreateTypeReference(getGlobalClassMethodDecoratorContextType( /*reportErrors*/ + true), [thisType, valueType]); } function createClassGetterDecoratorContextType(thisType, valueType) { - return tryCreateTypeReference(getGlobalClassGetterDecoratorContextType( - /*reportErrors*/ - true - ), [thisType, valueType]); + return tryCreateTypeReference(getGlobalClassGetterDecoratorContextType( /*reportErrors*/ + true), [thisType, valueType]); } function createClassSetterDecoratorContextType(thisType, valueType) { - return tryCreateTypeReference(getGlobalClassSetterDecoratorContextType( - /*reportErrors*/ - true - ), [thisType, valueType]); + return tryCreateTypeReference(getGlobalClassSetterDecoratorContextType( /*reportErrors*/ + true), [thisType, valueType]); } function createClassAccessorDecoratorContextType(thisType, valueType) { - return tryCreateTypeReference(getGlobalClassAccessorDecoratorContextType( - /*reportErrors*/ - true - ), [thisType, valueType]); + return tryCreateTypeReference(getGlobalClassAccessorDecoratorContextType( /*reportErrors*/ + true), [thisType, valueType]); } function createClassFieldDecoratorContextType(thisType, valueType) { - return tryCreateTypeReference(getGlobalClassFieldDecoratorContextType( - /*reportErrors*/ - true - ), [thisType, valueType]); + return tryCreateTypeReference(getGlobalClassFieldDecoratorContextType( /*reportErrors*/ + true), [thisType, valueType]); } function getClassMemberDecoratorContextOverrideType(nameType, isPrivate, isStatic2) { const key = `${isPrivate ? "p" : "P"}${isStatic2 ? "s" : "S"}${nameType.id}`; @@ -75478,14 +69893,8 @@ ${lanes.join("\n")} members.set("name", createProperty("name", nameType)); members.set("private", createProperty("private", isPrivate ? trueType : falseType)); members.set("static", createProperty("static", isStatic2 ? trueType : falseType)); - overrideType = createAnonymousType( - /*symbol*/ - void 0, - members, - emptyArray, - emptyArray, - emptyArray - ); + overrideType = createAnonymousType( /*symbol*/ + void 0, members, emptyArray, emptyArray, emptyArray); decoratorContextOverrideTypeCache.set(key, overrideType); } return overrideType; @@ -75499,171 +69908,142 @@ ${lanes.join("\n")} return getIntersectionType([contextType, overrideType]); } function createClassAccessorDecoratorTargetType(thisType, valueType) { - return tryCreateTypeReference(getGlobalClassAccessorDecoratorTargetType( - /*reportErrors*/ - true - ), [thisType, valueType]); + return tryCreateTypeReference(getGlobalClassAccessorDecoratorTargetType( /*reportErrors*/ + true), [thisType, valueType]); } function createClassAccessorDecoratorResultType(thisType, valueType) { - return tryCreateTypeReference(getGlobalClassAccessorDecoratorResultType( - /*reportErrors*/ - true - ), [thisType, valueType]); + return tryCreateTypeReference(getGlobalClassAccessorDecoratorResultType( /*reportErrors*/ + true), [thisType, valueType]); } function createClassFieldDecoratorInitializerMutatorType(thisType, valueType) { const thisParam = createParameter("this", thisType); const valueParam = createParameter("value", valueType); - return createFunctionType( - /*typeParameters*/ - void 0, - thisParam, - [valueParam], - valueType, - /*typePredicate*/ - void 0, - 1 - ); + return createFunctionType( /*typeParameters*/ + void 0, thisParam, [valueParam], valueType, /*typePredicate*/ + void 0, 1); } function createESDecoratorCallSignature(targetType, contextType, nonOptionalReturnType) { const targetParam = createParameter("target", targetType); const contextParam = createParameter("context", contextType); const returnType = getUnionType([nonOptionalReturnType, voidType]); - return createCallSignature( - /*typeParameters*/ - void 0, - /*thisParameter*/ - void 0, - [targetParam, contextParam], - returnType - ); + return createCallSignature( /*typeParameters*/ + void 0, /*thisParameter*/ + void 0, [targetParam, contextParam], returnType); } function getESDecoratorCallSignature(decorator) { - const { parent: parent2 } = decorator; + const { + parent: parent2 + } = decorator; const links = getNodeLinks(parent2); if (!links.decoratorSignature) { links.decoratorSignature = anySignature; switch (parent2.kind) { case 263 /* ClassDeclaration */: - case 231 /* ClassExpression */: { - const node = parent2; - const targetType = getTypeOfSymbol(getSymbolOfDeclaration(node)); - const contextType = createClassDecoratorContextType(targetType); - links.decoratorSignature = createESDecoratorCallSignature(targetType, contextType, targetType); - break; - } + case 231 /* ClassExpression */: + { + const node = parent2; + const targetType = getTypeOfSymbol(getSymbolOfDeclaration(node)); + const contextType = createClassDecoratorContextType(targetType); + links.decoratorSignature = createESDecoratorCallSignature(targetType, contextType, targetType); + break; + } case 174 /* MethodDeclaration */: case 177 /* GetAccessor */: - case 178 /* SetAccessor */: { - const node = parent2; - if (!isClassLike(node.parent)) + case 178 /* SetAccessor */: + { + const node = parent2; + 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; + const contextType = createClassMemberDecoratorContextTypeForNode(node, thisType, valueType); + const returnType = isGetAccessorDeclaration(node) ? createGetterFunctionType(valueType) : isSetAccessorDeclaration(node) ? createSetterFunctionType(valueType) : valueType; + links.decoratorSignature = createESDecoratorCallSignature(targetType, contextType, returnType); 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; - const contextType = createClassMemberDecoratorContextTypeForNode(node, thisType, valueType); - const returnType = isGetAccessorDeclaration(node) ? createGetterFunctionType(valueType) : isSetAccessorDeclaration(node) ? createSetterFunctionType(valueType) : valueType; - links.decoratorSignature = createESDecoratorCallSignature(targetType, contextType, returnType); - break; - } - case 172 /* PropertyDeclaration */: { - const node = parent2; - if (!isClassLike(node.parent)) + } + case 172 /* PropertyDeclaration */: + { + const node = parent2; + 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; + const contextType = createClassMemberDecoratorContextTypeForNode(node, thisType, valueType); + const returnType = hasAccessorModifier(node) ? createClassAccessorDecoratorResultType(thisType, valueType) : createClassFieldDecoratorInitializerMutatorType(thisType, valueType); + links.decoratorSignature = createESDecoratorCallSignature(targetType, contextType, returnType); 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; - const contextType = createClassMemberDecoratorContextTypeForNode(node, thisType, valueType); - const returnType = hasAccessorModifier(node) ? createClassAccessorDecoratorResultType(thisType, valueType) : createClassFieldDecoratorInitializerMutatorType(thisType, valueType); - links.decoratorSignature = createESDecoratorCallSignature(targetType, contextType, returnType); - break; - } + } } } return links.decoratorSignature === anySignature ? void 0 : links.decoratorSignature; } function getLegacyDecoratorCallSignature(decorator) { - const { parent: parent2 } = decorator; + const { + parent: parent2 + } = decorator; const links = getNodeLinks(parent2); if (!links.decoratorSignature) { links.decoratorSignature = anySignature; switch (parent2.kind) { case 263 /* ClassDeclaration */: - case 231 /* ClassExpression */: { - const node = parent2; - const targetType = getTypeOfSymbol(getSymbolOfDeclaration(node)); - const targetParam = createParameter("target", targetType); - links.decoratorSignature = createCallSignature( - /*typeParameters*/ - void 0, - /*thisParameter*/ - void 0, - [targetParam], - getUnionType([targetType, voidType]) - ); - break; - } - case 169 /* Parameter */: { - const node = parent2; - if (!isConstructorDeclaration(node.parent) && !(isMethodDeclaration(node.parent) || isSetAccessorDeclaration(node.parent) && isClassLike(node.parent.parent))) { + case 231 /* ClassExpression */: + { + const node = parent2; + const targetType = getTypeOfSymbol(getSymbolOfDeclaration(node)); + const targetParam = createParameter("target", targetType); + links.decoratorSignature = createCallSignature( /*typeParameters*/ + void 0, /*thisParameter*/ + void 0, [targetParam], getUnionType([targetType, voidType])); break; } - if (getThisParameter(node.parent) === node) { + case 169 /* Parameter */: + { + const node = parent2; + if (!isConstructorDeclaration(node.parent) && !(isMethodDeclaration(node.parent) || isSetAccessorDeclaration(node.parent) && isClassLike(node.parent.parent))) { + break; + } + if (getThisParameter(node.parent) === node) { + break; + } + const index = getThisParameter(node.parent) ? node.parent.parameters.indexOf(node) - 1 : node.parent.parameters.indexOf(node); + Debug.assert(index >= 0); + const targetType = isConstructorDeclaration(node.parent) ? getTypeOfSymbol(getSymbolOfDeclaration(node.parent.parent)) : getParentTypeOfClassElement(node.parent); + const keyType = isConstructorDeclaration(node.parent) ? undefinedType : getClassElementPropertyKeyType(node.parent); + const indexType = getNumberLiteralType(index); + const targetParam = createParameter("target", targetType); + const keyParam = createParameter("propertyKey", keyType); + const indexParam = createParameter("parameterIndex", indexType); + links.decoratorSignature = createCallSignature( /*typeParameters*/ + void 0, /*thisParameter*/ + void 0, [targetParam, keyParam, indexParam], voidType); break; } - const index = getThisParameter(node.parent) ? node.parent.parameters.indexOf(node) - 1 : node.parent.parameters.indexOf(node); - Debug.assert(index >= 0); - const targetType = isConstructorDeclaration(node.parent) ? getTypeOfSymbol(getSymbolOfDeclaration(node.parent.parent)) : getParentTypeOfClassElement(node.parent); - const keyType = isConstructorDeclaration(node.parent) ? undefinedType : getClassElementPropertyKeyType(node.parent); - const indexType = getNumberLiteralType(index); - const targetParam = createParameter("target", targetType); - const keyParam = createParameter("propertyKey", keyType); - const indexParam = createParameter("parameterIndex", indexType); - links.decoratorSignature = createCallSignature( - /*typeParameters*/ - void 0, - /*thisParameter*/ - void 0, - [targetParam, keyParam, indexParam], - voidType - ); - break; - } case 174 /* MethodDeclaration */: case 177 /* GetAccessor */: case 178 /* SetAccessor */: - case 172 /* PropertyDeclaration */: { - const node = parent2; - if (!isClassLike(node.parent)) + case 172 /* PropertyDeclaration */: + { + const node = parent2; + if (!isClassLike(node.parent)) break; + const targetType = getParentTypeOfClassElement(node); + const targetParam = createParameter("target", targetType); + const keyType = getClassElementPropertyKeyType(node); + const keyParam = createParameter("propertyKey", keyType); + const returnType = isPropertyDeclaration(node) ? voidType : createTypedPropertyDescriptorType(getTypeOfNode(node)); + const hasPropDesc = languageVersion !== 0 /* ES3 */ && (!isPropertyDeclaration(parent2) || hasAccessorModifier(parent2)); + if (hasPropDesc) { + const descriptorType = createTypedPropertyDescriptorType(getTypeOfNode(node)); + const descriptorParam = createParameter("descriptor", descriptorType); + links.decoratorSignature = createCallSignature( /*typeParameters*/ + void 0, /*thisParameter*/ + void 0, [targetParam, keyParam, descriptorParam], getUnionType([returnType, voidType])); + } else { + links.decoratorSignature = createCallSignature( /*typeParameters*/ + void 0, /*thisParameter*/ + void 0, [targetParam, keyParam], getUnionType([returnType, voidType])); + } break; - const targetType = getParentTypeOfClassElement(node); - const targetParam = createParameter("target", targetType); - const keyType = getClassElementPropertyKeyType(node); - const keyParam = createParameter("propertyKey", keyType); - const returnType = isPropertyDeclaration(node) ? voidType : createTypedPropertyDescriptorType(getTypeOfNode(node)); - const hasPropDesc = languageVersion !== 0 /* ES3 */ && (!isPropertyDeclaration(parent2) || hasAccessorModifier(parent2)); - if (hasPropDesc) { - const descriptorType = createTypedPropertyDescriptorType(getTypeOfNode(node)); - const descriptorParam = createParameter("descriptor", descriptorType); - links.decoratorSignature = createCallSignature( - /*typeParameters*/ - void 0, - /*thisParameter*/ - void 0, - [targetParam, keyParam, descriptorParam], - getUnionType([returnType, voidType]) - ); - } else { - links.decoratorSignature = createCallSignature( - /*typeParameters*/ - void 0, - /*thisParameter*/ - void 0, - [targetParam, keyParam], - getUnionType([returnType, voidType]) - ); } - break; - } } } return links.decoratorSignature === anySignature ? void 0 : links.decoratorSignature; @@ -75672,10 +70052,8 @@ ${lanes.join("\n")} return legacyDecorators ? getLegacyDecoratorCallSignature(decorator) : getESDecoratorCallSignature(decorator); } function createPromiseType(promisedType) { - const globalPromiseType = getGlobalPromiseType( - /*reportErrors*/ - true - ); + const globalPromiseType = getGlobalPromiseType( /*reportErrors*/ + true); if (globalPromiseType !== emptyGenericType) { promisedType = getAwaitedTypeNoAlias(unwrapAwaitedType(promisedType)) || unknownType; return createTypeReference(globalPromiseType, [promisedType]); @@ -75683,10 +70061,8 @@ ${lanes.join("\n")} return unknownType; } function createPromiseLikeType(promisedType) { - const globalPromiseLikeType = getGlobalPromiseLikeType( - /*reportErrors*/ - true - ); + const globalPromiseLikeType = getGlobalPromiseLikeType( /*reportErrors*/ + true); if (globalPromiseLikeType !== emptyGenericType) { promisedType = getAwaitedTypeNoAlias(unwrapAwaitedType(promisedType)) || unknownType; return createTypeReference(globalPromiseLikeType, [promisedType]); @@ -75696,19 +70072,11 @@ ${lanes.join("\n")} function createPromiseReturnType(func, promisedType) { const promiseType = createPromiseType(promisedType); if (promiseType === unknownType) { - error2( - func, - isImportCall(func) ? Diagnostics.A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option : Diagnostics.An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option - ); + error2(func, isImportCall(func) ? Diagnostics.A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option : Diagnostics.An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option); return errorType; - } else if (!getGlobalPromiseConstructorSymbol( - /*reportErrors*/ - true - )) { - error2( - func, - isImportCall(func) ? Diagnostics.A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option : Diagnostics.An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option - ); + } else if (!getGlobalPromiseConstructorSymbol( /*reportErrors*/ + true)) { + error2(func, isImportCall(func) ? Diagnostics.A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option : Diagnostics.An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option); } return promiseType; } @@ -75735,14 +70103,9 @@ ${lanes.join("\n")} if (func.body.kind !== 241 /* Block */) { returnType = checkExpressionCached(func.body, checkMode && checkMode & ~8 /* SkipGenericFunctions */); if (isAsync) { - returnType = unwrapAwaitedType(checkAwaitedType( - returnType, - /*withAlias*/ - false, - /*errorNode*/ - func, - Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member - )); + returnType = unwrapAwaitedType(checkAwaitedType(returnType, /*withAlias*/ + false, /*errorNode*/ + func, Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member)); } } else if (isGenerator) { const returnTypes = checkAndAggregateReturnExpressionTypes(func, checkMode); @@ -75751,7 +70114,11 @@ ${lanes.join("\n")} } else if (returnTypes.length > 0) { returnType = getUnionType(returnTypes, 2 /* Subtype */); } - const { yieldTypes, nextTypes } = checkAndAggregateYieldOperandTypes(func, checkMode); + + const { + yieldTypes, + nextTypes + } = checkAndAggregateYieldOperandTypes(func, checkMode); yieldType = some(yieldTypes) ? getUnionType(yieldTypes, 2 /* Subtype */) : void 0; nextType = some(nextTypes) ? getIntersectionType(nextTypes) : void 0; } else { @@ -75760,34 +70127,24 @@ ${lanes.join("\n")} return functionFlags & 2 /* Async */ ? createPromiseReturnType(func, neverType) : neverType; } if (types.length === 0) { - const contextualReturnType = getContextualReturnType( - func, - /*contextFlags*/ - void 0 - ); + const contextualReturnType = getContextualReturnType(func, /*contextFlags*/ + void 0); const returnType2 = contextualReturnType && (unwrapReturnType(contextualReturnType, functionFlags) || voidType).flags & 32768 /* Undefined */ ? undefinedType : voidType; - return functionFlags & 2 /* Async */ ? createPromiseReturnType(func, returnType2) : ( - // Async function - returnType2 - ); + return functionFlags & 2 /* Async */ ? createPromiseReturnType(func, returnType2) : + // Async function + returnType2; } 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( - getReturnTypeOfSignature(contextualSignature), - func, - /*contextFlags*/ - void 0 - ); + const contextualType = !contextualSignature ? void 0 : contextualSignature === getSignatureFromDeclaration(func) ? isGenerator ? void 0 : returnType : instantiateContextualType(getReturnTypeOfSignature(contextualSignature), func, /*contextFlags*/ + void 0); if (isGenerator) { yieldType = getWidenedLiteralLikeTypeForContextualIterationTypeIfNeeded(yieldType, contextualType, 0 /* Yield */, isAsync); returnType = getWidenedLiteralLikeTypeForContextualIterationTypeIfNeeded(returnType, contextualType, 1 /* Return */, isAsync); @@ -75796,50 +70153,29 @@ ${lanes.join("\n")} 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( - yieldType || neverType, - returnType || fallbackReturnType, - nextType || getContextualIterationType(2 /* Next */, func) || unknownType, - isAsync - ); + return createGeneratorReturnType(yieldType || neverType, returnType || fallbackReturnType, nextType || getContextualIterationType(2 /* Next */, func) || unknownType, isAsync); } else { return isAsync ? createPromiseType(returnType || fallbackReturnType) : returnType || fallbackReturnType; } } function createGeneratorReturnType(yieldType, returnType, nextType, isAsyncGenerator) { const resolver = isAsyncGenerator ? asyncIterationTypesResolver : syncIterationTypesResolver; - const globalGeneratorType = resolver.getGlobalGeneratorType( - /*reportErrors*/ - false - ); - yieldType = resolver.resolveIterationType( - yieldType, - /*errorNode*/ - void 0 - ) || unknownType; - returnType = resolver.resolveIterationType( - returnType, - /*errorNode*/ - void 0 - ) || unknownType; - nextType = resolver.resolveIterationType( - nextType, - /*errorNode*/ - void 0 - ) || unknownType; + const globalGeneratorType = resolver.getGlobalGeneratorType( /*reportErrors*/ + false); + yieldType = resolver.resolveIterationType(yieldType, /*errorNode*/ + void 0) || unknownType; + returnType = resolver.resolveIterationType(returnType, /*errorNode*/ + void 0) || unknownType; + nextType = resolver.resolveIterationType(nextType, /*errorNode*/ + void 0) || unknownType; if (globalGeneratorType === emptyGenericType) { - const globalType = resolver.getGlobalIterableIteratorType( - /*reportErrors*/ - false - ); + const globalType = resolver.getGlobalIterableIteratorType( /*reportErrors*/ + false); const iterationTypes = globalType !== emptyGenericType ? getIterationTypesOfGlobalIterableType(globalType, resolver) : void 0; const iterableIteratorReturnType = iterationTypes ? iterationTypes.returnType : anyType; const iterableIteratorNextType = iterationTypes ? iterationTypes.nextType : undefinedType; @@ -75847,16 +70183,12 @@ ${lanes.join("\n")} if (globalType !== emptyGenericType) { return createTypeFromGenericGlobalType(globalType, [yieldType]); } - resolver.getGlobalIterableIteratorType( - /*reportErrors*/ - true - ); + resolver.getGlobalIterableIteratorType( /*reportErrors*/ + true); return emptyObjectType; } - resolver.getGlobalGeneratorType( - /*reportErrors*/ - true - ); + resolver.getGlobalGeneratorType( /*reportErrors*/ + true); return emptyObjectType; } return createTypeFromGenericGlobalType(globalGeneratorType, [yieldType, returnType, nextType]); @@ -75865,37 +70197,28 @@ ${lanes.join("\n")} const yieldTypes = []; const nextTypes = []; const isAsync = (getFunctionFlags(func) & 2 /* Async */) !== 0; - forEachYieldExpression(func.body, (yieldExpression) => { + forEachYieldExpression(func.body, yieldExpression => { const yieldExpressionType = yieldExpression.expression ? checkExpression(yieldExpression.expression, checkMode) : undefinedWideningType; pushIfUnique(yieldTypes, getYieldedTypeOfYieldExpression(yieldExpression, yieldExpressionType, anyType, isAsync)); let nextType; if (yieldExpression.asteriskToken) { - const iterationTypes = getIterationTypesOfIterable( - yieldExpressionType, - isAsync ? 19 /* AsyncYieldStar */ : 17 /* YieldStar */, - yieldExpression.expression - ); + const iterationTypes = getIterationTypesOfIterable(yieldExpressionType, isAsync ? 19 /* AsyncYieldStar */ : 17 /* YieldStar */, yieldExpression.expression); nextType = iterationTypes && iterationTypes.nextType; } else { - nextType = getContextualType2( - yieldExpression, - /*contextFlags*/ - void 0 - ); + nextType = getContextualType2(yieldExpression, /*contextFlags*/ + void 0); } - if (nextType) - pushIfUnique(nextTypes, nextType); + if (nextType) pushIfUnique(nextTypes, nextType); }); - return { yieldTypes, nextTypes }; + return { + yieldTypes, + nextTypes + }; } function getYieldedTypeOfYieldExpression(node, expressionType, sentType, isAsync) { const errorNode = node.expression || node; const yieldedType = node.asteriskToken ? checkIteratedTypeOrElementType(isAsync ? 19 /* AsyncYieldStar */ : 17 /* YieldStar */, expressionType, sentType, errorNode) : expressionType; - return !isAsync ? yieldedType : getAwaitedType( - yieldedType, - errorNode, - node.asteriskToken ? Diagnostics.Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member : Diagnostics.Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member - ); + return !isAsync ? yieldedType : getAwaitedType(yieldedType, errorNode, node.asteriskToken ? Diagnostics.Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member : Diagnostics.Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); } function getNotEqualFactsFromTypeofSwitch(start, end, witnesses) { let facts = 0 /* None */; @@ -75929,7 +70252,8 @@ ${lanes.join("\n")} if (operandConstraint.flags & 3 /* AnyOrUnknown */) { return (556800 /* AllTypeofNE */ & notEqualFacts) === 556800 /* AllTypeofNE */; } - return !someType(operandConstraint, (t) => getTypeFacts(t, notEqualFacts) === notEqualFacts); + + return !someType(operandConstraint, t => getTypeFacts(t, notEqualFacts) === notEqualFacts); } const type = checkExpressionCached(node.expression); if (!isLiteralType(type)) { @@ -75949,20 +70273,14 @@ ${lanes.join("\n")} const aggregatedTypes = []; let hasReturnWithNoExpression = functionHasImplicitReturn(func); let hasReturnOfTypeNever = false; - forEachReturnStatement(func.body, (returnStatement) => { + forEachReturnStatement(func.body, returnStatement => { let expr = returnStatement.expression; if (expr) { - expr = skipParentheses( - expr, - /*excludeJSDocTypeAssertions*/ - true - ); + expr = skipParentheses(expr, /*excludeJSDocTypeAssertions*/ + true); if (functionFlags & 2 /* Async */ && expr.kind === 223 /* AwaitExpression */) { - expr = skipParentheses( - expr.expression, - /*excludeJSDocTypeAssertions*/ - true - ); + expr = skipParentheses(expr.expression, /*excludeJSDocTypeAssertions*/ + true); } if (expr.kind === 213 /* CallExpression */ && expr.expression.kind === 80 /* Identifier */ && checkExpressionCached(expr.expression).symbol === func.symbol) { hasReturnOfTypeNever = true; @@ -75970,13 +70288,8 @@ ${lanes.join("\n")} } let type = checkExpressionCached(expr, checkMode && checkMode & ~8 /* SkipGenericFunctions */); if (functionFlags & 2 /* Async */) { - type = unwrapAwaitedType(checkAwaitedType( - type, - /*withAlias*/ - false, - func, - Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member - )); + type = unwrapAwaitedType(checkAwaitedType(type, /*withAlias*/ + false, func, Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member)); } if (type.flags & 131072 /* Never */) { hasReturnOfTypeNever = true; @@ -75989,7 +70302,7 @@ ${lanes.join("\n")} if (aggregatedTypes.length === 0 && !hasReturnWithNoExpression && (hasReturnOfTypeNever || mayReturnNever(func))) { return void 0; } - if (strictNullChecks && aggregatedTypes.length && hasReturnWithNoExpression && !(isJSConstructor(func) && aggregatedTypes.some((t) => t.symbol === func.symbol))) { + if (strictNullChecks && aggregatedTypes.length && hasReturnWithNoExpression && !(isJSConstructor(func) && aggregatedTypes.some(t => t.symbol === func.symbol))) { pushIfUnique(aggregatedTypes, undefinedType); } return aggregatedTypes; @@ -76054,20 +70367,12 @@ ${lanes.join("\n")} return links.contextFreeType; } const returnType = getReturnTypeFromBody(node, checkMode); - const returnOnlySignature = createSignature( - /*declaration*/ - void 0, - /*typeParameters*/ - void 0, - /*thisParameter*/ - void 0, - emptyArray, - returnType, - /*resolvedTypePredicate*/ - void 0, - 0, - 64 /* IsNonInferrable */ - ); + const returnOnlySignature = createSignature( /*declaration*/ + void 0, /*typeParameters*/ + void 0, /*thisParameter*/ + void 0, emptyArray, returnType, /*resolvedTypePredicate*/ + void 0, 0, 64 /* IsNonInferrable */); + const returnOnlyType = createAnonymousType(node.symbol, emptySymbols, [returnOnlySignature], emptyArray, emptyArray); returnOnlyType.objectFlags |= 262144 /* NonInferrableType */; return links.contextFreeType = returnOnlyType; @@ -76140,13 +70445,8 @@ ${lanes.join("\n")} const returnOrPromisedType = returnType && unwrapReturnType(returnType, functionFlags); if (returnOrPromisedType) { if ((functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */) { - const awaitedType = checkAwaitedType( - exprType, - /*withAlias*/ - false, - node.body, - Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member - ); + const awaitedType = checkAwaitedType(exprType, /*withAlias*/ + false, node.body, Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); checkTypeAssignableToAndOptionallyElaborate(awaitedType, returnOrPromisedType, node.body, node.body); } else { checkTypeAssignableToAndOptionallyElaborate(exprType, returnOrPromisedType, node.body, node.body); @@ -76158,11 +70458,7 @@ ${lanes.join("\n")} function checkArithmeticOperandType(operand, type, diagnostic, isAwaitValid = false) { if (!isTypeAssignableTo(type, numberOrBigIntType)) { const awaitedType = isAwaitValid && getAwaitedTypeOfPromise(type); - errorAndMaybeSuggestAwait( - operand, - !!awaitedType && isTypeAssignableTo(awaitedType, numberOrBigIntType), - diagnostic - ); + errorAndMaybeSuggestAwait(operand, !!awaitedType && isTypeAssignableTo(awaitedType, numberOrBigIntType), diagnostic); return false; } return true; @@ -76230,6 +70526,7 @@ ${lanes.join("\n")} } } } + return false; } function checkReferenceExpression(expr, invalidReferenceMessage, invalidOptionalChainMessage) { @@ -76280,6 +70577,7 @@ ${lanes.join("\n")} return undefinedWideningType; } function checkAwaitGrammar(node) { + var _span3; let hasError = false; const container = getContainingFunctionOrClassStaticBlock(node); if (container && isClassStaticBlockDeclaration(container)) { @@ -76292,7 +70590,8 @@ ${lanes.join("\n")} if (!hasParseDiagnostics(sourceFile)) { let span; if (!isEffectiveExternalModule(sourceFile, compilerOptions)) { - span ?? (span = getSpanOfTokenAtPosition(sourceFile, node.pos)); + var _span; + (_span = span) !== null && _span !== void 0 ? _span : span = getSpanOfTokenAtPosition(sourceFile, node.pos); const message = isAwaitExpression(node) ? Diagnostics.await_expressions_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module : Diagnostics.await_using_statements_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module; const diagnostic = createFileDiagnostic(sourceFile, span.start, span.length, message); diagnostics.add(diagnostic); @@ -76302,10 +70601,9 @@ ${lanes.join("\n")} case 100 /* Node16 */: case 199 /* NodeNext */: if (sourceFile.impliedNodeFormat === 1 /* CommonJS */) { - span ?? (span = getSpanOfTokenAtPosition(sourceFile, node.pos)); - diagnostics.add( - createFileDiagnostic(sourceFile, span.start, span.length, Diagnostics.The_current_file_is_a_CommonJS_module_and_cannot_use_await_at_the_top_level) - ); + var _span2; + (_span2 = span) !== null && _span2 !== void 0 ? _span2 : span = getSpanOfTokenAtPosition(sourceFile, node.pos); + diagnostics.add(createFileDiagnostic(sourceFile, span.start, span.length, Diagnostics.The_current_file_is_a_CommonJS_module_and_cannot_use_await_at_the_top_level)); hasError = true; break; } @@ -76316,7 +70614,7 @@ ${lanes.join("\n")} break; } default: - span ?? (span = getSpanOfTokenAtPosition(sourceFile, node.pos)); + (_span3 = span) !== null && _span3 !== void 0 ? _span3 : span = getSpanOfTokenAtPosition(sourceFile, node.pos); const message = isAwaitExpression(node) ? Diagnostics.Top_level_await_expressions_are_only_allowed_when_the_module_option_is_set_to_es2022_esnext_system_node16_or_nodenext_and_the_target_option_is_set_to_es2017_or_higher : Diagnostics.Top_level_await_using_statements_are_only_allowed_when_the_module_option_is_set_to_es2022_esnext_system_node16_or_nodenext_and_the_target_option_is_set_to_es2017_or_higher; diagnostics.add(createFileDiagnostic(sourceFile, span.start, span.length, message)); hasError = true; @@ -76347,19 +70645,11 @@ ${lanes.join("\n")} function checkAwaitExpression(node) { addLazyDiagnostic(() => checkAwaitGrammar(node)); const operandType = checkExpression(node.expression); - const awaitedType = checkAwaitedType( - operandType, - /*withAlias*/ - true, - node, - Diagnostics.Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member - ); + const awaitedType = checkAwaitedType(operandType, /*withAlias*/ + true, node, Diagnostics.Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); if (awaitedType === operandType && !isErrorType(awaitedType) && !(operandType.flags & 3 /* AnyOrUnknown */)) { - addErrorOrSuggestion( - /*isError*/ - false, - createDiagnosticForNode(node, Diagnostics.await_has_no_effect_on_the_type_of_this_expression) - ); + addErrorOrSuggestion( /*isError*/ + false, createDiagnosticForNode(node, Diagnostics.await_has_no_effect_on_the_type_of_this_expression)); } return awaitedType; } @@ -76408,11 +70698,7 @@ ${lanes.join("\n")} case 47 /* MinusMinusToken */: const ok = checkArithmeticOperandType(node.operand, checkNonNullType(operandType, node.operand), Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_bigint_or_an_enum_type); if (ok) { - checkReferenceExpression( - node.operand, - Diagnostics.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access, - Diagnostics.The_operand_of_an_increment_or_decrement_operator_may_not_be_an_optional_property_access - ); + checkReferenceExpression(node.operand, Diagnostics.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access, Diagnostics.The_operand_of_an_increment_or_decrement_operator_may_not_be_an_optional_property_access); } return getUnaryResultType(operandType); } @@ -76423,17 +70709,9 @@ ${lanes.join("\n")} if (operandType === silentNeverType) { return silentNeverType; } - const ok = checkArithmeticOperandType( - node.operand, - checkNonNullType(operandType, node.operand), - Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_bigint_or_an_enum_type - ); + const ok = checkArithmeticOperandType(node.operand, checkNonNullType(operandType, node.operand), Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_bigint_or_an_enum_type); if (ok) { - checkReferenceExpression( - node.operand, - Diagnostics.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access, - Diagnostics.The_operand_of_an_increment_or_decrement_operator_may_not_be_an_optional_property_access - ); + checkReferenceExpression(node.operand, Diagnostics.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access, Diagnostics.The_operand_of_an_increment_or_decrement_operator_may_not_be_an_optional_property_access); } return getUnaryResultType(operandType); } @@ -76474,7 +70752,7 @@ ${lanes.join("\n")} return !!(kind & 296 /* NumberLike */) && isTypeAssignableTo(source, numberType) || !!(kind & 2112 /* BigIntLike */) && isTypeAssignableTo(source, bigintType) || !!(kind & 402653316 /* StringLike */) && isTypeAssignableTo(source, stringType) || !!(kind & 528 /* BooleanLike */) && isTypeAssignableTo(source, booleanType) || !!(kind & 16384 /* Void */) && isTypeAssignableTo(source, voidType) || !!(kind & 131072 /* Never */) && isTypeAssignableTo(source, neverType) || !!(kind & 65536 /* Null */) && isTypeAssignableTo(source, nullType) || !!(kind & 32768 /* Undefined */) && isTypeAssignableTo(source, undefinedType) || !!(kind & 4096 /* ESSymbol */) && isTypeAssignableTo(source, esSymbolType) || !!(kind & 67108864 /* NonPrimitive */) && isTypeAssignableTo(source, nonPrimitiveType); } function allTypesAssignableToKind(source, kind, strict) { - return source.flags & 1048576 /* Union */ ? every(source.types, (subType) => allTypesAssignableToKind(subType, kind, strict)) : isTypeAssignableToKind(source, kind, strict); + return source.flags & 1048576 /* Union */ ? every(source.types, subType => allTypesAssignableToKind(subType, kind, strict)) : isTypeAssignableToKind(source, kind, strict); } function isConstEnumObjectType(type) { return !!(getObjectFlags(type) & 16 /* Anonymous */) && !!type.symbol && isConstEnumSymbol(type.symbol); @@ -76500,12 +70778,8 @@ ${lanes.join("\n")} error2(left, Diagnostics.The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter); } Debug.assert(isInstanceOfExpression(left.parent)); - const signature = getResolvedSignature( - left.parent, - /*candidatesOutArray*/ - void 0, - checkMode - ); + const signature = getResolvedSignature(left.parent, /*candidatesOutArray*/ + void 0, checkMode); if (signature === resolvingSignature) { return silentNeverType; } @@ -76514,7 +70788,7 @@ ${lanes.join("\n")} return booleanType; } function hasEmptyObjectIntersection(type) { - return someType(type, (t) => t === unknownEmptyObjectType || !!(t.flags & 2097152 /* Intersection */) && isEmptyAnonymousObjectType(getBaseConstraintOrType(t))); + return someType(type, t => t === unknownEmptyObjectType || !!(t.flags & 2097152 /* Intersection */) && isEmptyAnonymousObjectType(getBaseConstraintOrType(t))); } function checkInExpression(left, right, leftType, rightType) { if (leftType === silentNeverType || rightType === silentNeverType) { @@ -76524,13 +70798,10 @@ ${lanes.join("\n")} if (languageVersion < 99 /* ESNext */) { checkExternalEmitHelpers(left, 2097152 /* ClassPrivateFieldIn */); } + if (!getNodeLinks(left).resolvedSymbol && getContainingClass(left)) { - const isUncheckedJS = isUncheckedJSSuggestion( - left, - rightType.symbol, - /*excludeClasses*/ - true - ); + const isUncheckedJS = isUncheckedJSSuggestion(left, rightType.symbol, /*excludeClasses*/ + true); reportNonexistentProperty(left, rightType, isUncheckedJS); } } else { @@ -76564,15 +70835,9 @@ ${lanes.join("\n")} const prop = getPropertyOfType(objectLiteralType, text); if (prop) { markPropertyAsReferenced(prop, property, rightIsThis); - checkPropertyAccessibility( - property, - /*isSuper*/ - false, - /*writing*/ - true, - objectLiteralType, - prop - ); + checkPropertyAccessibility(property, /*isSuper*/ + false, /*writing*/ + true, objectLiteralType, prop); } } const elementType = getIndexedAccessType(objectLiteralType, exprType, 32 /* ExpressionPosition */, name); @@ -76585,6 +70850,7 @@ ${lanes.join("\n")} if (languageVersion < 99 /* ESNext */) { checkExternalEmitHelpers(property, 4 /* Rest */); } + const nonRestNames = []; if (allProperties) { for (const otherProperty of allProperties) { @@ -76606,12 +70872,14 @@ ${lanes.join("\n")} if (languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) { checkExternalEmitHelpers(node, 512 /* Read */); } + const possiblyOutOfBoundsType = checkIteratedTypeOrElementType(65 /* Destructuring */ | 128 /* PossiblyOutOfBounds */, sourceType, undefinedType, node) || errorType; let inBoundsType = compilerOptions.noUncheckedIndexedAccess ? void 0 : possiblyOutOfBoundsType; for (let i = 0; i < elements.length; i++) { let type = possiblyOutOfBoundsType; if (node.elements[i].kind === 230 /* SpreadElement */) { - type = inBoundsType = inBoundsType ?? (checkIteratedTypeOrElementType(65 /* Destructuring */, sourceType, undefinedType, node) || errorType); + var _inBoundsType; + type = inBoundsType = (_inBoundsType = inBoundsType) !== null && _inBoundsType !== void 0 ? _inBoundsType : checkIteratedTypeOrElementType(65 /* Destructuring */, sourceType, undefinedType, node) || errorType; } checkArrayLiteralDestructuringElementAssignment(node, sourceType, i, type, checkMode); } @@ -76640,7 +70908,7 @@ ${lanes.join("\n")} error2(restExpression.operatorToken, Diagnostics.A_rest_element_cannot_have_an_initializer); } else { checkGrammarForDisallowedTrailingComma(node.elements, Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma); - const type = everyType(sourceType, isTupleType) ? mapType(sourceType, (t) => sliceTupleType(t, elementIndex)) : createArrayType(elementType); + const type = everyType(sourceType, isTupleType) ? mapType(sourceType, t => sliceTupleType(t, elementIndex)) : createArrayType(elementType); return checkDestructuringAssignment(restExpression, type, checkMode); } } @@ -76655,6 +70923,7 @@ ${lanes.join("\n")} if (strictNullChecks && !hasTypeFacts(checkExpression(prop.objectAssignmentInitializer), 16777216 /* IsUndefined */)) { sourceType = getTypeWithFacts(sourceType, 524288 /* NEUndefined */); } + checkBinaryLikeExpression(prop.name, prop.equalsToken, prop.objectAssignmentInitializer, checkMode); } target = exprOrAssignment.name; @@ -76668,6 +70937,7 @@ ${lanes.join("\n")} sourceType = getTypeWithFacts(sourceType, 524288 /* NEUndefined */); } } + if (target.kind === 210 /* ObjectLiteralExpression */) { return checkObjectLiteralAssignment(target, sourceType, rightIsThis); } @@ -76686,6 +70956,7 @@ ${lanes.join("\n")} if (isPrivateIdentifierPropertyAccessExpression(target)) { checkExternalEmitHelpers(target.parent, 1048576 /* ClassPrivateFieldSet */); } + return sourceType; } function isSideEffectFree(node) { @@ -76751,16 +71022,10 @@ ${lanes.join("\n")} if (state) { state.stackIndex++; state.skip = false; - setLeftType( - state, - /*type*/ - void 0 - ); - setLastResult( - state, - /*type*/ - void 0 - ); + setLeftType(state, /*type*/ + void 0); + setLastResult(state, /*type*/ + void 0); } else { state = { checkMode, @@ -76793,11 +71058,8 @@ ${lanes.join("\n")} const leftType = getLastResult(state); Debug.assertIsDefined(leftType); setLeftType(state, leftType); - setLastResult( - state, - /*type*/ - void 0 - ); + setLastResult(state, /*type*/ + void 0); const operator = operatorToken.kind; if (isLogicalOrCoalescingBinaryOperator(operator)) { let parent2 = node.parent; @@ -76828,16 +71090,10 @@ ${lanes.join("\n")} result = checkBinaryLikeExpressionWorker(node.left, node.operatorToken, node.right, leftType, rightType, state.checkMode, node); } state.skip = false; - setLeftType( - state, - /*type*/ - void 0 - ); - setLastResult( - state, - /*type*/ - void 0 - ); + setLeftType(state, /*type*/ + void 0); + setLastResult(state, /*type*/ + void 0); state.stackIndex--; return result; } @@ -76865,7 +71121,11 @@ ${lanes.join("\n")} } } function checkGrammarNullishCoalesceWithLogicalExpression(node) { - const { left, operatorToken, right } = node; + const { + left, + operatorToken, + right + } = node; if (operatorToken.kind === 61 /* QuestionQuestionToken */) { if (isBinaryExpression(left) && (left.operatorToken.kind === 57 /* BarBarToken */ || left.operatorToken.kind === 56 /* AmpersandAmpersandToken */)) { grammarErrorOnNode(left, Diagnostics._0_and_1_operations_cannot_be_mixed_without_parentheses, tokenToString(left.operatorToken.kind), tokenToString(operatorToken.kind)); @@ -76880,6 +71140,7 @@ ${lanes.join("\n")} if (operator === 64 /* EqualsToken */ && (left.kind === 210 /* ObjectLiteralExpression */ || left.kind === 209 /* ArrayLiteralExpression */)) { return checkDestructuringAssignment(left, checkExpression(right, checkMode), checkMode, right.kind === 110 /* ThisKeyword */); } + let leftType; if (isLogicalOrCoalescingBinaryOperator(operator)) { leftType = checkTruthinessExpression(left, checkMode); @@ -76924,22 +71185,13 @@ ${lanes.join("\n")} error2(errorNode || operatorToken, Diagnostics.The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead, tokenToString(operatorToken.kind), tokenToString(suggestedOperator)); return numberType; } else { - const leftOk = checkArithmeticOperandType( - left, - leftType, - Diagnostics.The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type, - /*isAwaitValid*/ - true - ); - const rightOk = checkArithmeticOperandType( - right, - rightType, - Diagnostics.The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type, - /*isAwaitValid*/ - true - ); + const leftOk = checkArithmeticOperandType(left, leftType, Diagnostics.The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type, /*isAwaitValid*/ + true); + const rightOk = checkArithmeticOperandType(right, rightType, Diagnostics.The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type, /*isAwaitValid*/ + true); let resultType2; - if (isTypeAssignableToKind(leftType, 3 /* AnyOrUnknown */) && isTypeAssignableToKind(rightType, 3 /* AnyOrUnknown */) || // Or, if neither could be bigint, implicit coercion results in a number result + if (isTypeAssignableToKind(leftType, 3 /* AnyOrUnknown */) && isTypeAssignableToKind(rightType, 3 /* AnyOrUnknown */) || + // Or, if neither could be bigint, implicit coercion results in a number result !(maybeTypeOfKind(leftType, 2112 /* BigIntLike */) || maybeTypeOfKind(rightType, 2112 /* BigIntLike */))) { resultType2 = numberType; } else if (bothAreBigIntLike(leftType, rightType)) { @@ -76974,41 +71226,17 @@ ${lanes.join("\n")} rightType = checkNonNullType(rightType, right); } let resultType; - if (isTypeAssignableToKind( - leftType, - 296 /* NumberLike */, - /*strict*/ - true - ) && isTypeAssignableToKind( - rightType, - 296 /* NumberLike */, - /*strict*/ - true - )) { + if (isTypeAssignableToKind(leftType, 296 /* NumberLike */, /*strict*/ + true) && isTypeAssignableToKind(rightType, 296 /* NumberLike */, /*strict*/ + true)) { resultType = numberType; - } else if (isTypeAssignableToKind( - leftType, - 2112 /* BigIntLike */, - /*strict*/ - true - ) && isTypeAssignableToKind( - rightType, - 2112 /* BigIntLike */, - /*strict*/ - true - )) { + } else if (isTypeAssignableToKind(leftType, 2112 /* BigIntLike */, /*strict*/ + true) && isTypeAssignableToKind(rightType, 2112 /* BigIntLike */, /*strict*/ + true)) { resultType = bigintType; - } else if (isTypeAssignableToKind( - leftType, - 402653316 /* StringLike */, - /*strict*/ - true - ) || isTypeAssignableToKind( - rightType, - 402653316 /* StringLike */, - /*strict*/ - true - )) { + } else if (isTypeAssignableToKind(leftType, 402653316 /* StringLike */, /*strict*/ + true) || isTypeAssignableToKind(rightType, 402653316 /* StringLike */, /*strict*/ + true)) { resultType = stringType; } else if (isTypeAny(leftType) || isTypeAny(rightType)) { resultType = isErrorType(leftType) || isErrorType(rightType) ? errorType : anyType; @@ -77018,9 +71246,7 @@ ${lanes.join("\n")} } if (!resultType) { const closeEnoughKind = 296 /* NumberLike */ | 2112 /* BigIntLike */ | 402653316 /* StringLike */ | 3 /* AnyOrUnknown */; - reportOperatorError( - (left2, right2) => isTypeAssignableToKind(left2, closeEnoughKind) && isTypeAssignableToKind(right2, closeEnoughKind) - ); + reportOperatorError((left2, right2) => isTypeAssignableToKind(left2, closeEnoughKind) && isTypeAssignableToKind(right2, closeEnoughKind)); return anyType; } if (operator === 65 /* PlusEqualsToken */) { @@ -77049,8 +71275,9 @@ ${lanes.join("\n")} case 37 /* EqualsEqualsEqualsToken */: case 38 /* ExclamationEqualsEqualsToken */: if (!(checkMode && checkMode & 64 /* TypeOnly */)) { - if ((isLiteralExpressionOfObject(left) || isLiteralExpressionOfObject(right)) && // only report for === and !== in JS, not == or != - (!isInJSFile(left) || (operator === 37 /* EqualsEqualsEqualsToken */ || operator === 38 /* ExclamationEqualsEqualsToken */))) { + if ((isLiteralExpressionOfObject(left) || isLiteralExpressionOfObject(right)) && ( + // only report for === and !== in JS, not == or != + !isInJSFile(left) || operator === 37 /* EqualsEqualsEqualsToken */ || operator === 38 /* ExclamationEqualsEqualsToken */)) { const eqType = operator === 35 /* EqualsEqualsToken */ || operator === 37 /* EqualsEqualsEqualsToken */; error2(errorNode, Diagnostics.This_condition_will_always_return_0_since_JavaScript_compares_objects_by_reference_not_value, eqType ? "false" : "true"); } @@ -77063,29 +71290,32 @@ ${lanes.join("\n")} case 103 /* InKeyword */: return checkInExpression(left, right, leftType, rightType); case 56 /* AmpersandAmpersandToken */: - case 77 /* AmpersandAmpersandEqualsToken */: { - const resultType2 = hasTypeFacts(leftType, 4194304 /* Truthy */) ? getUnionType([extractDefinitelyFalsyTypes(strictNullChecks ? leftType : getBaseTypeOfLiteralType(rightType)), rightType]) : leftType; - if (operator === 77 /* AmpersandAmpersandEqualsToken */) { - checkAssignmentOperator(rightType); + case 77 /* AmpersandAmpersandEqualsToken */: + { + const resultType2 = hasTypeFacts(leftType, 4194304 /* Truthy */) ? getUnionType([extractDefinitelyFalsyTypes(strictNullChecks ? leftType : getBaseTypeOfLiteralType(rightType)), rightType]) : leftType; + if (operator === 77 /* AmpersandAmpersandEqualsToken */) { + checkAssignmentOperator(rightType); + } + return resultType2; } - return resultType2; - } case 57 /* BarBarToken */: - case 76 /* BarBarEqualsToken */: { - const resultType2 = hasTypeFacts(leftType, 8388608 /* Falsy */) ? getUnionType([getNonNullableType(removeDefinitelyFalsyTypes(leftType)), rightType], 2 /* Subtype */) : leftType; - if (operator === 76 /* BarBarEqualsToken */) { - checkAssignmentOperator(rightType); + case 76 /* BarBarEqualsToken */: + { + const resultType2 = hasTypeFacts(leftType, 8388608 /* Falsy */) ? getUnionType([getNonNullableType(removeDefinitelyFalsyTypes(leftType)), rightType], 2 /* Subtype */) : leftType; + if (operator === 76 /* BarBarEqualsToken */) { + checkAssignmentOperator(rightType); + } + return resultType2; } - return resultType2; - } case 61 /* QuestionQuestionToken */: - case 78 /* QuestionQuestionEqualsToken */: { - const resultType2 = hasTypeFacts(leftType, 262144 /* EQUndefinedOrNull */) ? getUnionType([getNonNullableType(leftType), rightType], 2 /* Subtype */) : leftType; - if (operator === 78 /* QuestionQuestionEqualsToken */) { - checkAssignmentOperator(rightType); + case 78 /* QuestionQuestionEqualsToken */: + { + const resultType2 = hasTypeFacts(leftType, 262144 /* EQUndefinedOrNull */) ? getUnionType([getNonNullableType(leftType), rightType], 2 /* Subtype */) : leftType; + if (operator === 78 /* QuestionQuestionEqualsToken */) { + checkAssignmentOperator(rightType); + } + return resultType2; } - return resultType2; - } case 64 /* EqualsToken */: const declKind = isBinaryExpression(left.parent) ? getAssignmentDeclarationKind(left.parent) : 0 /* None */; checkAssignmentDeclaration(declKind, rightType); @@ -77103,13 +71333,11 @@ ${lanes.join("\n")} const sf = getSourceFileOfNode(left); 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; + const isInDiag2657 = sf.parseDiagnostics.some(diag2 => { + 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: @@ -77118,22 +71346,16 @@ ${lanes.join("\n")} function bothAreBigIntLike(left2, right2) { return isTypeAssignableToKind(left2, 2112 /* BigIntLike */) && isTypeAssignableToKind(right2, 2112 /* BigIntLike */); } + function checkAssignmentDeclaration(kind, rightType2) { if (kind === 2 /* ModuleExports */) { for (const prop of getPropertiesOfObjectType(rightType2)) { const propType = getTypeOfSymbol(prop); if (propType.symbol && propType.symbol.flags & 32 /* Class */) { const name = prop.escapedName; - const symbol = resolveName( - prop.valueDeclaration, - name, - 788968 /* Type */, - /*nameNotFoundMessage*/ - void 0, - name, - /*isUse*/ - false - ); + const symbol = resolveName(prop.valueDeclaration, name, 788968 /* Type */, /*nameNotFoundMessage*/ + void 0, name, /*isUse*/ + false); if ((symbol == null ? void 0 : symbol.declarations) && symbol.declarations.some(isJSDocTypedefTag)) { addDuplicateDeclarationErrorsForSymbols(symbol, Diagnostics.Duplicate_identifier_0, unescapeLeadingUnderscores(name), prop); addDuplicateDeclarationErrorsForSymbols(prop, Diagnostics.Duplicate_identifier_0, unescapeLeadingUnderscores(name), symbol); @@ -77143,8 +71365,9 @@ ${lanes.join("\n")} } } function isIndirectCall(node) { - return node.parent.kind === 217 /* ParenthesizedExpression */ && isNumericLiteral(node.left) && node.left.text === "0" && (isCallExpression(node.parent.parent) && node.parent.parent.expression === node.parent || node.parent.parent.kind === 215 /* TaggedTemplateExpression */) && // special-case for "eval" because it's the only non-access case where an indirect call actually affects behavior. - (isAccessExpression(node.right) || isIdentifier(node.right) && node.right.escapedText === "eval"); + return node.parent.kind === 217 /* ParenthesizedExpression */ && isNumericLiteral(node.left) && node.left.text === "0" && (isCallExpression(node.parent.parent) && node.parent.parent.expression === node.parent || node.parent.parent.kind === 215 /* TaggedTemplateExpression */) && ( + // special-case for "eval" because it's the only non-access case where an indirect call actually affects behavior. + isAccessExpression(node.right) || isIdentifier(node.right) && node.right.escapedText === "eval"); } function checkForDisallowedESSymbolOperand(operator2) { const offendingSymbolOperand = maybeTypeOfKindConsideringBaseConstraint(leftType, 12288 /* ESSymbolLike */) ? left : maybeTypeOfKindConsideringBaseConstraint(rightType, 12288 /* ESSymbolLike */) ? right : void 0; @@ -77176,13 +71399,9 @@ ${lanes.join("\n")} function checkAssignmentOperatorWorker() { let assigneeType = leftType; if (isCompoundAssignment(operatorToken.kind) && left.kind === 211 /* PropertyAccessExpression */) { - assigneeType = checkPropertyAccessExpression( - left, - /*checkMode*/ - void 0, - /*writeOnly*/ - true - ); + assigneeType = checkPropertyAccessExpression(left, /*checkMode*/ + void 0, /*writeOnly*/ + true); } if (checkReferenceExpression(left, Diagnostics.The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access, Diagnostics.The_left_hand_side_of_an_assignment_expression_may_not_be_an_optional_property_access)) { let headMessage; @@ -77235,14 +71454,7 @@ ${lanes.join("\n")} } const [leftStr, rightStr] = getTypeNamesForErrorDisplay(effectiveLeft, effectiveRight); if (!tryGiveBetterPrimaryError(errNode, wouldWorkWithAwait, leftStr, rightStr)) { - errorAndMaybeSuggestAwait( - errNode, - wouldWorkWithAwait, - Diagnostics.Operator_0_cannot_be_applied_to_types_1_and_2, - tokenToString(operatorToken.kind), - leftStr, - rightStr - ); + errorAndMaybeSuggestAwait(errNode, wouldWorkWithAwait, Diagnostics.Operator_0_cannot_be_applied_to_types_1_and_2, tokenToString(operatorToken.kind), leftStr, rightStr); } } function tryGiveBetterPrimaryError(errNode, maybeMissingAwait, leftStr, rightStr) { @@ -77251,13 +71463,7 @@ ${lanes.join("\n")} case 35 /* EqualsEqualsToken */: case 38 /* ExclamationEqualsEqualsToken */: case 36 /* ExclamationEqualsToken */: - return errorAndMaybeSuggestAwait( - errNode, - maybeMissingAwait, - Diagnostics.This_comparison_appears_to_be_unintentional_because_the_types_0_and_1_have_no_overlap, - leftStr, - rightStr - ); + return errorAndMaybeSuggestAwait(errNode, maybeMissingAwait, Diagnostics.This_comparison_appears_to_be_unintentional_because_the_types_0_and_1_have_no_overlap, leftStr, rightStr); default: return void 0; } @@ -77267,8 +71473,7 @@ ${lanes.join("\n")} 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); @@ -77297,8 +71502,7 @@ ${lanes.join("\n")} 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; @@ -77308,18 +71512,16 @@ ${lanes.join("\n")} if (isAsync && languageVersion < 99 /* ESNext */) { checkExternalEmitHelpers(node, 26624 /* AsyncDelegatorIncludes */); } + if (!isAsync && languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) { checkExternalEmitHelpers(node, 256 /* Values */); } } + let returnType = getReturnTypeFromAnnotation(func); if (returnType && returnType.flags & 1048576 /* Union */) { - returnType = filterType(returnType, (t) => checkGeneratorInstantiationAssignabilityToReturnType( - t, - functionFlags, - /*errorNode*/ - void 0 - )); + returnType = filterType(returnType, t => checkGeneratorInstantiationAssignabilityToReturnType(t, functionFlags, /*errorNode*/ + void 0)); } const iterationTypes = returnType && getIterationTypesOfGeneratorFunctionReturnType(returnType, isAsync); const signatureYieldType = iterationTypes && iterationTypes.yieldType || anyType; @@ -77341,11 +71543,8 @@ ${lanes.join("\n")} type = anyType; addLazyDiagnostic(() => { if (noImplicitAny && !expressionResultIsUnused(node)) { - const contextualType = getContextualType2( - node, - /*contextFlags*/ - void 0 - ); + const contextualType = getContextualType2(node, /*contextFlags*/ + void 0); if (!contextualType || isTypeAny(contextualType)) { error2(node, Diagnostics.yield_expression_implicitly_results_in_an_any_type_because_its_containing_generator_lacks_a_return_type_annotation); } @@ -77369,6 +71568,7 @@ ${lanes.join("\n")} const type2 = checkExpression(node.whenFalse, checkMode); return getUnionType([type1, type2], 2 /* Subtype */); } + function isTemplateLiteralContext(node) { const parent2 = node.parent; return isParenthesizedExpression(parent2) && isTemplateLiteralContext(parent2) || isElementAccessExpression(parent2) && parent2.argumentExpression === node; @@ -77384,11 +71584,8 @@ ${lanes.join("\n")} texts.push(span.literal.text); types.push(isTypeAssignableTo(type, templateConstraintType) ? type : stringType); } - if (isConstContext(node) || isTemplateLiteralContext(node) || someType(getContextualType2( - node, - /*contextFlags*/ - void 0 - ) || unknownType, isTemplateLiteralContextualType)) { + if (isConstContext(node) || isTemplateLiteralContext(node) || someType(getContextualType2(node, /*contextFlags*/ + void 0) || unknownType, isTemplateLiteralContextualType)) { return getTemplateLiteralType(texts, types); } const evaluated = node.parent.kind !== 215 /* TaggedTemplateExpression */ && evaluateTemplateExpression(node); @@ -77397,6 +71594,7 @@ ${lanes.join("\n")} function isTemplateLiteralContextualType(type) { return !!(type.flags & (128 /* StringLiteral */ | 134217728 /* TemplateLiteral */) || type.flags & 58982400 /* InstantiableNonPrimitive */ && maybeTypeOfKind(getBaseConstraintOfType(type) || unknownType, 402653316 /* StringLike */)); } + function getContextNode2(node) { if (isJsxAttributes(node) && !isJsxSelfClosingElement(node.parent)) { return node.parent.parent; @@ -77405,23 +71603,15 @@ ${lanes.join("\n")} } function checkExpressionWithContextualType(node, contextualType, inferenceContext, checkMode) { const contextNode = getContextNode2(node); - pushContextualType( - contextNode, - contextualType, - /*isCache*/ - false - ); + pushContextualType(contextNode, contextualType, /*isCache*/ + false); pushInferenceContext(contextNode, inferenceContext); const type = checkExpression(node, checkMode | 1 /* Contextual */ | (inferenceContext ? 2 /* Inferential */ : 0)); if (inferenceContext && inferenceContext.intraExpressionInferenceSites) { inferenceContext.intraExpressionInferenceSites = void 0; } - const result = maybeTypeOfKind(type, 2944 /* Literal */) && isLiteralOfContextualType(type, instantiateContextualType( - contextualType, - node, - /*contextFlags*/ - void 0 - )) ? getRegularTypeOfLiteralType(type) : type; + const result = maybeTypeOfKind(type, 2944 /* Literal */) && isLiteralOfContextualType(type, instantiateContextualType(contextualType, node, /*contextFlags*/ + void 0)) ? getRegularTypeOfLiteralType(type) : type; popInferenceContext(); popContextualType(); return result; @@ -77443,11 +71633,8 @@ ${lanes.join("\n")} return links.resolvedType; } function isTypeAssertion(node) { - node = skipParentheses( - node, - /*excludeJSDocTypeAssertions*/ - true - ); + node = skipParentheses(node, /*excludeJSDocTypeAssertions*/ + true); return node.kind === 216 /* TypeAssertionExpression */ || node.kind === 234 /* AsExpression */ || isJSDocTypeAssertion(node); } function checkDeclarationInitializer(declaration, checkMode, contextualType) { @@ -77458,13 +71645,8 @@ ${lanes.join("\n")} return checkSatisfiesExpressionWorker(initializer, typeNode, checkMode); } } - const type = getQuickTypeOfExpression(initializer) || (contextualType ? checkExpressionWithContextualType( - initializer, - contextualType, - /*inferenceContext*/ - void 0, - checkMode || 0 /* Normal */ - ) : checkExpressionCached(initializer, checkMode)); + const type = getQuickTypeOfExpression(initializer) || (contextualType ? checkExpressionWithContextualType(initializer, contextualType, /*inferenceContext*/ + void 0, checkMode || 0 /* Normal */) : checkExpressionCached(initializer, checkMode)); return isParameter(declaration) && declaration.name.kind === 207 /* ArrayBindingPattern */ && isTupleType(type) && !type.target.hasRestElement && getTypeReferenceArity(type) < declaration.name.elements.length ? padTupleType(type, declaration.name) : type; } function padTupleType(type, pattern) { @@ -77474,13 +71656,9 @@ ${lanes.join("\n")} for (let i = getTypeReferenceArity(type); i < patternElements.length; i++) { const e = patternElements[i]; if (i < patternElements.length - 1 || !(e.kind === 208 /* BindingElement */ && e.dotDotDotToken)) { - elementTypes.push(!isOmittedExpression(e) && hasDefaultValue(e) ? getTypeFromBindingElement( - e, - /*includePatternInType*/ - false, - /*reportErrors*/ - false - ) : anyType); + elementTypes.push(!isOmittedExpression(e) && hasDefaultValue(e) ? getTypeFromBindingElement(e, /*includePatternInType*/ + false, /*reportErrors*/ + false) : anyType); elementFlags.push(2 /* Optional */); if (!isOmittedExpression(e) && !hasDefaultValue(e)) { reportImplicitAny(e, anyType); @@ -77506,7 +71684,7 @@ ${lanes.join("\n")} if (contextualType) { if (contextualType.flags & 3145728 /* UnionOrIntersection */) { const types = contextualType.types; - return some(types, (t) => isLiteralOfContextualType(candidateType, t)); + return some(types, t => isLiteralOfContextualType(candidateType, t)); } if (contextualType.flags & 58982400 /* InstantiableNonPrimitive */) { const constraint = getBaseConstraintOfType(contextualType) || unknownType; @@ -77514,6 +71692,7 @@ ${lanes.join("\n")} } return !!(contextualType.flags & (128 /* StringLiteral */ | 4194304 /* Index */ | 134217728 /* TemplateLiteral */ | 268435456 /* StringMapping */) && maybeTypeOfKind(candidateType, 128 /* StringLiteral */) || contextualType.flags & 256 /* NumberLiteral */ && maybeTypeOfKind(candidateType, 256 /* NumberLiteral */) || contextualType.flags & 2048 /* BigIntLiteral */ && maybeTypeOfKind(candidateType, 2048 /* BigIntLiteral */) || contextualType.flags & 512 /* BooleanLiteral */ && maybeTypeOfKind(candidateType, 512 /* BooleanLiteral */) || contextualType.flags & 8192 /* UniqueESSymbol */ && maybeTypeOfKind(candidateType, 8192 /* UniqueESSymbol */)); } + return false; } function isConstContext(node) { @@ -77522,16 +71701,9 @@ ${lanes.join("\n")} } function checkExpressionForMutableLocation(node, checkMode, forceTuple) { const type = checkExpression(node, checkMode, forceTuple); - return isConstContext(node) || isCommonJsExportedExpression(node) ? getRegularTypeOfLiteralType(type) : isTypeAssertion(node) ? type : getWidenedLiteralLikeTypeForContextualType(type, instantiateContextualType( - getContextualType2( - node, - /*contextFlags*/ - void 0 - ), - node, - /*contextFlags*/ - void 0 - )); + return isConstContext(node) || isCommonJsExportedExpression(node) ? getRegularTypeOfLiteralType(type) : isTypeAssertion(node) ? type : getWidenedLiteralLikeTypeForContextualType(type, instantiateContextualType(getContextualType2(node, /*contextFlags*/ + void 0), node, /*contextFlags*/ + void 0)); } function checkPropertyAssignment(node, checkMode) { if (node.name.kind === 167 /* ComputedPropertyName */) { @@ -77549,28 +71721,16 @@ ${lanes.join("\n")} } function instantiateTypeWithSingleGenericCallSignature(node, type, checkMode) { if (checkMode && checkMode & (2 /* Inferential */ | 8 /* SkipGenericFunctions */)) { - const callSignature = getSingleSignature( - type, - 0 /* Call */, - /*allowMembers*/ - true - ); - const constructSignature = getSingleSignature( - type, - 1 /* Construct */, - /*allowMembers*/ - true - ); + const callSignature = getSingleSignature(type, 0 /* Call */, /*allowMembers*/ + true); + const constructSignature = getSingleSignature(type, 1 /* Construct */, /*allowMembers*/ + true); const signature = callSignature || constructSignature; if (signature && signature.typeParameters) { const contextualType = getApparentTypeOfContextualType(node, 2 /* NoConstraints */); if (contextualType) { - const contextualSignature = getSingleSignature( - getNonNullableType(contextualType), - callSignature ? 0 /* Call */ : 1 /* Construct */, - /*allowMembers*/ - false - ); + const contextualSignature = getSingleSignature(getNonNullableType(contextualType), callSignature ? 0 /* Call */ : 1 /* Construct */, /*allowMembers*/ + false); if (contextualSignature && !contextualSignature.typeParameters) { if (checkMode & 8 /* SkipGenericFunctions */) { skippedGenericFunction(node, checkMode); @@ -77582,17 +71742,11 @@ ${lanes.join("\n")} if (returnSignature && !returnSignature.typeParameters && !every(context.inferences, hasInferenceCandidates)) { const uniqueTypeParameters = getUniqueTypeParameters(context, signature.typeParameters); const instantiatedSignature = getSignatureInstantiationWithoutFillingInTypeArguments(signature, uniqueTypeParameters); - const inferences = map(context.inferences, (info) => createInferenceInfo(info.typeParameter)); + const inferences = map(context.inferences, info => createInferenceInfo(info.typeParameter)); applyToParameterTypes(instantiatedSignature, contextualSignature, (source, target) => { - inferTypes( - inferences, - source, - target, - /*priority*/ - 0, - /*contravariant*/ - true - ); + inferTypes(inferences, source, target, /*priority*/ + 0, /*contravariant*/ + true); }); if (some(inferences, hasInferenceCandidates)) { applyToReturnTypes(instantiatedSignature, contextualSignature, (source, target) => { @@ -77618,6 +71772,7 @@ ${lanes.join("\n")} context.flags |= 4 /* SkippedGenericFunction */; } } + function hasInferenceCandidates(info) { return !!(info.candidates || info.contraCandidates); } @@ -77666,12 +71821,11 @@ ${lanes.join("\n")} return result; } function hasTypeParameterByName(typeParameters, name) { - return some(typeParameters, (tp) => tp.symbol.escapedName === name); + return some(typeParameters, tp => tp.symbol.escapedName === name); } 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; @@ -77710,14 +71864,12 @@ ${lanes.join("\n")} cache[getNodeId(node)] = type; setNodeFlags(node, node.flags | 268435456 /* TypeCached */); } + return type; } function getQuickTypeOfExpression(node) { - let expr = skipParentheses( - node, - /*excludeJSDocTypeAssertions*/ - true - ); + let expr = skipParentheses(node, /*excludeJSDocTypeAssertions*/ + true); if (isJSDocTypeAssertion(expr)) { const type = getJSDocTypeAssertionType(expr); if (!isConstTypeReference(type)) { @@ -77729,11 +71881,8 @@ ${lanes.join("\n")} const type = getQuickTypeOfExpression(expr.expression); return type ? getAwaitedType(type) : void 0; } - if (isCallExpression(expr) && expr.expression.kind !== 108 /* SuperKeyword */ && !isRequireCall( - expr, - /*requireStringLiteralLikeArgument*/ - true - ) && !isSymbolOrSymbolForCall(expr)) { + if (isCallExpression(expr) && expr.expression.kind !== 108 /* SuperKeyword */ && !isRequireCall(expr, /*requireStringLiteralLikeArgument*/ + true) && !isSymbolOrSymbolForCall(expr)) { return isCallChain(expr) ? getReturnTypeOfSingleNonGenericSignatureOfCallChain(expr) : getReturnTypeOfSingleNonGenericCallSignature(checkNonNullExpression(expr.expression)); } else if (isAssertionExpression(expr) && !isConstTypeReference(expr.type)) { return getTypeFromTypeNode(expr.type); @@ -77747,19 +71896,20 @@ ${lanes.join("\n")} if (links.contextFreeType) { return links.contextFreeType; } - pushContextualType( - node, - anyType, - /*isCache*/ - false - ); + pushContextualType(node, anyType, /*isCache*/ + false); const type = links.contextFreeType = checkExpression(node, 4 /* SkipContextSensitive */); popContextualType(); return type; } function checkExpression(node, checkMode, forceTuple) { var _a, _b; - (_a = tracing) == null ? void 0 : _a.push(tracing.Phase.Check, "checkExpression", { kind: node.kind, pos: node.pos, end: node.end, path: node.tracingPath }); + (_a = tracing) == null ? void 0 : _a.push(tracing.Phase.Check, "checkExpression", { + kind: node.kind, + pos: node.pos, + end: node.end, + path: node.tracingPath + }); const saveCurrentNode = currentNode; currentNode = node; instantiationCount = 0; @@ -77773,7 +71923,7 @@ ${lanes.join("\n")} return type; } function checkConstEnumAccess(node, type) { - const ok = node.parent.kind === 211 /* PropertyAccessExpression */ && node.parent.expression === node || node.parent.kind === 212 /* ElementAccessExpression */ && node.parent.expression === node || ((node.kind === 80 /* Identifier */ || node.kind === 166 /* QualifiedName */) && isInRightSideOfImportOrExportAssignment(node) || node.parent.kind === 186 /* TypeQuery */ && node.parent.exprName === node) || node.parent.kind === 281 /* ExportSpecifier */; + const ok = node.parent.kind === 211 /* PropertyAccessExpression */ && node.parent.expression === node || node.parent.kind === 212 /* ElementAccessExpression */ && node.parent.expression === node || (node.kind === 80 /* Identifier */ || node.kind === 166 /* QualifiedName */) && isInRightSideOfImportOrExportAssignment(node) || node.parent.kind === 186 /* TypeQuery */ && node.parent.exprName === node || node.parent.kind === 281 /* ExportSpecifier */; if (!ok) { error2(node, Diagnostics.const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment_or_type_query); } @@ -77942,7 +72092,10 @@ ${lanes.join("\n")} if (isTypeAliasDeclaration(node.parent) && !(getObjectFlags(getDeclaredTypeOfSymbol(symbol)) & (16 /* Anonymous */ | 32 /* Mapped */))) { error2(node, Diagnostics.Variance_annotations_are_only_supported_in_type_aliases_for_object_function_constructor_and_mapped_types); } else if (modifiers === 8192 /* In */ || modifiers === 16384 /* Out */) { - (_a = tracing) == null ? void 0 : _a.push(tracing.Phase.CheckTypes, "checkTypeParameterDeferred", { parent: getTypeId(getDeclaredTypeOfSymbol(symbol)), id: getTypeId(typeParameter) }); + (_a = tracing) == null ? void 0 : _a.push(tracing.Phase.CheckTypes, "checkTypeParameterDeferred", { + parent: getTypeId(getDeclaredTypeOfSymbol(symbol)), + id: getTypeId(typeParameter) + }); const source = createMarkerType(symbol, typeParameter, modifiers === 16384 /* Out */ ? markerSubTypeForCheck : markerSuperTypeForCheck); const target = createMarkerType(symbol, typeParameter, modifiers === 16384 /* Out */ ? markerSuperTypeForCheck : markerSubTypeForCheck); const saveVarianceTypeParameter = typeParameter; @@ -77999,7 +72152,9 @@ ${lanes.join("\n")} return; } checkSourceElement(node.type); - const { parameterName } = node; + const { + parameterName + } = node; if (typePredicate.kind === 0 /* This */ || typePredicate.kind === 2 /* AssertsThis */) { getTypeFromThisTypeNode(parameterName); } else { @@ -78008,24 +72163,17 @@ ${lanes.join("\n")} error2(parameterName, Diagnostics.A_type_predicate_cannot_reference_a_rest_parameter); } else { if (typePredicate.type) { - const leadingError = () => chainDiagnosticMessages( - /*details*/ - void 0, - Diagnostics.A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type - ); - checkTypeAssignableTo( - typePredicate.type, - getTypeOfSymbol(signature.parameters[typePredicate.parameterIndex]), - node.type, - /*headMessage*/ - void 0, - leadingError - ); + const leadingError = () => chainDiagnosticMessages( /*details*/ + void 0, Diagnostics.A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type); + checkTypeAssignableTo(typePredicate.type, getTypeOfSymbol(signature.parameters[typePredicate.parameterIndex]), node.type, /*headMessage*/ + void 0, leadingError); } } } else if (parameterName) { let hasReportedError = false; - for (const { name } of parent2.parameters) { + for (const { + name + } of parent2.parameters) { if (isBindingPattern(name) && checkIfTypePredicateVariableIsDeclaredInBindingPattern(name, parameterName, typePredicate.parameterName)) { hasReportedError = true; break; @@ -78062,11 +72210,7 @@ ${lanes.join("\n")} error2(predicateVariableNode, Diagnostics.A_type_predicate_cannot_reference_element_0_in_a_binding_pattern, predicateVariableName); return true; } else if (name.kind === 207 /* ArrayBindingPattern */ || name.kind === 206 /* ObjectBindingPattern */) { - if (checkIfTypePredicateVariableIsDeclaredInBindingPattern( - name, - predicateVariableNode, - predicateVariableName - )) { + if (checkIfTypePredicateVariableIsDeclaredInBindingPattern(name, predicateVariableNode, predicateVariableName)) { return true; } } @@ -78083,13 +72227,16 @@ ${lanes.join("\n")} if ((functionFlags & 3 /* AsyncGenerator */) === 3 /* AsyncGenerator */ && languageVersion < 99 /* ESNext */) { checkExternalEmitHelpers(node, 6144 /* AsyncGeneratorIncludes */); } + if ((functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */ && languageVersion < 4 /* ES2017 */) { checkExternalEmitHelpers(node, 64 /* Awaiter */); } + if ((functionFlags & 3 /* AsyncGenerator */) !== 0 /* Normal */ && languageVersion < 2 /* ES2015 */) { checkExternalEmitHelpers(node, 128 /* Generator */); } } + checkTypeParameters(getEffectiveTypeParameterDeclarations(node)); checkUnmatchedJSDocParameters(node); forEach(node.parameters, checkParameter); @@ -78147,9 +72294,9 @@ ${lanes.join("\n")} return checkTypeAssignableTo(generatorInstantiation, returnType, errorNode); } function checkClassForDuplicateDeclarations(node) { - const instanceNames = /* @__PURE__ */ new Map(); - const staticNames = /* @__PURE__ */ new Map(); - const privateIdentifiers = /* @__PURE__ */ new Map(); + const instanceNames = /* @__PURE__ */new Map(); + const staticNames = /* @__PURE__ */new Map(); + const privateIdentifiers = /* @__PURE__ */new Map(); for (const member of node.members) { if (member.kind === 176 /* Constructor */) { for (const param of member.parameters) { @@ -78232,7 +72379,7 @@ ${lanes.join("\n")} } } function checkObjectTypeForDuplicateDeclarations(node) { - const names = /* @__PURE__ */ new Map(); + const names = /* @__PURE__ */new Map(); for (const member of node.members) { if (member.kind === 171 /* PropertySignature */) { let memberName; @@ -78266,20 +72413,23 @@ ${lanes.join("\n")} } const indexSymbol = getIndexSymbol(getSymbolOfDeclaration(node)); if (indexSymbol == null ? void 0 : indexSymbol.declarations) { - const indexSignatureMap = /* @__PURE__ */ new Map(); + const indexSignatureMap = /* @__PURE__ */new Map(); for (const declaration of indexSymbol.declarations) { if (declaration.parameters.length === 1 && declaration.parameters[0].type) { - forEachType(getTypeFromTypeNode(declaration.parameters[0].type), (type) => { + forEachType(getTypeFromTypeNode(declaration.parameters[0].type), type => { const entry = indexSignatureMap.get(getTypeId(type)); if (entry) { entry.declarations.push(declaration); } else { - indexSignatureMap.set(getTypeId(type), { type, declarations: [declaration] }); + indexSignatureMap.set(getTypeId(type), { + type, + declarations: [declaration] + }); } }); } } - indexSignatureMap.forEach((entry) => { + indexSignatureMap.forEach(entry => { if (entry.declarations.length > 1) { for (const declaration of entry.declarations) { error2(declaration, Diagnostics.Duplicate_index_signature_for_type_0, typeToString(entry.type)); @@ -78289,8 +72439,7 @@ ${lanes.join("\n")} } } 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) { @@ -78304,8 +72453,7 @@ ${lanes.join("\n")} 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); } @@ -78323,6 +72471,7 @@ ${lanes.join("\n")} for (let lexicalScope = getEnclosingBlockScopeContainer(node); !!lexicalScope; lexicalScope = getEnclosingBlockScopeContainer(lexicalScope)) { getNodeLinks(lexicalScope).flags |= 1048576 /* ContainsClassWithPrivateIdentifiers */; } + if (isClassExpression(node.parent)) { const enclosingIterationStatement = getEnclosingIterationStatement(node.parent); if (enclosingIterationStatement) { @@ -78332,14 +72481,14 @@ ${lanes.join("\n")} } } } + function checkClassStaticBlockDeclaration(node) { checkGrammarModifiers(node); forEachChild(node, checkSourceElement); } 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); @@ -78367,7 +72516,7 @@ ${lanes.join("\n")} if (classExtendsNull) { error2(superCall, Diagnostics.A_constructor_cannot_contain_a_super_call_when_its_class_extends_null); } - const superCallShouldBeRootLevel = !emitStandardClassFields && (some(node.parent.members, isInstancePropertyWithInitializerOrPrivateIdentifierProperty) || some(node.parameters, (p) => hasSyntacticModifier(p, 31 /* ParameterPropertyModifier */))); + const superCallShouldBeRootLevel = !emitStandardClassFields && (some(node.parent.members, isInstancePropertyWithInitializerOrPrivateIdentifierProperty) || some(node.parameters, p => hasSyntacticModifier(p, 31 /* ParameterPropertyModifier */))); if (superCallShouldBeRootLevel) { if (!superCallIsRootLevelInConstructor(superCall, node.body)) { error2(superCall, Diagnostics.A_super_call_must_be_a_root_level_statement_within_a_constructor_of_a_derived_class_that_contains_initialized_properties_parameter_properties_or_private_identifiers); @@ -78414,8 +72563,7 @@ ${lanes.join("\n")} 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 */) { @@ -78475,12 +72623,7 @@ ${lanes.join("\n")} typeArguments = getEffectiveTypeArguments2(node, typeParameters); mapper = createTypeMapper(typeParameters, typeArguments); } - result = result && checkTypeAssignableTo( - typeArguments[i], - instantiateType(constraint, mapper), - node.typeArguments[i], - Diagnostics.Type_0_does_not_satisfy_the_constraint_1 - ); + result = result && checkTypeAssignableTo(typeArguments[i], instantiateType(constraint, mapper), node.typeArguments[i], Diagnostics.Type_0_does_not_satisfy_the_constraint_1); } } return result; @@ -78525,23 +72668,17 @@ ${lanes.join("\n")} } const symbol = getNodeLinks(node).resolvedSymbol; if (symbol) { - if (some(symbol.declarations, (d) => isTypeDeclaration(d) && !!(d.flags & 536870912 /* Deprecated */))) { - addDeprecatedSuggestion( - getDeprecatedSuggestionNode(node), - symbol.declarations, - symbol.escapedName - ); + if (some(symbol.declarations, d => isTypeDeclaration(d) && !!(d.flags & 536870912 /* Deprecated */))) { + addDeprecatedSuggestion(getDeprecatedSuggestionNode(node), symbol.declarations, symbol.escapedName); } } } } 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))); } @@ -78619,7 +72756,7 @@ ${lanes.join("\n")} if (isGenericObjectType(objectType)) { const propertyName = getPropertyNameFromIndex(indexType, accessNode); if (propertyName) { - const propertySymbol = forEachType(apparentObjectType, (t) => getPropertyOfType(t, propertyName)); + const propertySymbol = forEachType(apparentObjectType, t => getPropertyOfType(t, propertyName)); if (propertySymbol && getDeclarationModifierFlagsFromSymbol(propertySymbol) & 6 /* NonPublicAccessibilityModifier */) { error2(accessNode, Diagnostics.Private_or_protected_member_0_cannot_be_accessed_on_a_type_parameter, unescapeLeadingUnderscores(propertyName)); return errorType; @@ -78668,7 +72805,7 @@ ${lanes.join("\n")} forEachChild(node, checkSourceElement); } function checkInferType(node) { - if (!findAncestor(node, (n) => n.parent && n.parent.kind === 194 /* ConditionalType */ && n.parent.extendsType === n)) { + if (!findAncestor(node, n => n.parent && n.parent.kind === 194 /* ConditionalType */ && n.parent.extendsType === n)) { grammarErrorOnNode(node, Diagnostics.infer_declarations_are_only_permitted_in_the_extends_clause_of_a_conditional_type); } checkSourceElement(node.typeParameter); @@ -78679,7 +72816,7 @@ ${lanes.join("\n")} links.typeParametersChecked = true; const typeParameter = getDeclaredTypeOfTypeParameter(symbol); const declarations = getDeclarationsOfKind(symbol, 168 /* TypeParameter */); - if (!areTypeParametersIdentical(declarations, [typeParameter], (decl) => [decl])) { + if (!areTypeParametersIdentical(declarations, [typeParameter], decl => [decl])) { const name = symbolToString(symbol); for (const declaration of declarations) { error2(declaration.name, Diagnostics.All_declarations_of_0_must_have_identical_constraints, name); @@ -78720,6 +72857,7 @@ ${lanes.join("\n")} function isPrivateWithinAmbient(node) { return (hasEffectiveModifier(node, 2 /* Private */) || isPrivateIdentifierClassElementDeclaration(node)) && !!(node.flags & 33554432 /* Ambient */); } + function getEffectiveDeclarationFlags(n, flagsToCheck) { let flags = getCombinedModifierFlagsCached(n); if (n.parent.kind !== 264 /* InterfaceDeclaration */ && n.parent.kind !== 263 /* ClassDeclaration */ && n.parent.kind !== 231 /* ClassExpression */ && n.flags & 33554432 /* Ambient */) { @@ -78727,8 +72865,10 @@ ${lanes.join("\n")} if (container && container.flags & 128 /* ExportContext */ && !(flags & 128 /* Ambient */) && !(isModuleBlock(n.parent) && isModuleDeclaration(n.parent.parent) && isGlobalScopeAugmentation(n.parent.parent))) { flags |= 32 /* Export */; } + flags |= 128 /* Ambient */; } + return flags & flagsToCheck; } function checkFunctionOrConstructorSymbol(symbol) { @@ -78743,7 +72883,7 @@ ${lanes.join("\n")} const someButNotAllOverloadFlags = someOverloadFlags ^ allOverloadFlags; if (someButNotAllOverloadFlags !== 0) { const canonicalFlags = getEffectiveDeclarationFlags(getCanonicalOverload(overloads, implementation), flagsToCheck2); - forEach(overloads, (o) => { + forEach(overloads, o => { const deviation = getEffectiveDeclarationFlags(o, flagsToCheck2) ^ canonicalFlags; if (deviation & 32 /* Export */) { error2(getNameOfDeclaration(o), Diagnostics.Overload_signatures_must_all_be_exported_or_non_exported); @@ -78760,7 +72900,7 @@ ${lanes.join("\n")} function checkQuestionTokenAgreementBetweenOverloads(overloads, implementation, someHaveQuestionToken2, allHaveQuestionToken2) { if (someHaveQuestionToken2 !== allHaveQuestionToken2) { const canonicalHasQuestionToken = hasQuestionToken(getCanonicalOverload(overloads, implementation)); - forEach(overloads, (o) => { + forEach(overloads, o => { const deviation = hasQuestionToken(o) !== canonicalHasQuestionToken; if (deviation) { error2(getNameOfDeclaration(o), Diagnostics.Overload_signatures_must_all_be_optional_or_required); @@ -78784,7 +72924,7 @@ ${lanes.join("\n")} return; } let seen = false; - const subsequentNode = forEachChild(node.parent, (c) => { + const subsequentNode = forEachChild(node.parent, c => { if (seen) { return c; } else { @@ -78795,9 +72935,12 @@ ${lanes.join("\n")} if (subsequentNode.kind === node.kind) { const errorNode2 = subsequentNode.name || subsequentNode; const subsequentName = subsequentNode.name; - if (node.name && subsequentName && // both are private identifiers - (isPrivateIdentifier(node.name) && isPrivateIdentifier(subsequentName) && node.name.escapedText === subsequentName.escapedText || // Both are computed property names - isComputedPropertyName(node.name) && isComputedPropertyName(subsequentName) && isTypeIdenticalTo(checkComputedPropertyName(node.name), checkComputedPropertyName(subsequentName)) || // Both are literal property names that are the same. + if (node.name && subsequentName && ( + // both are private identifiers + isPrivateIdentifier(node.name) && isPrivateIdentifier(subsequentName) && node.name.escapedText === subsequentName.escapedText || + // Both are computed property names + isComputedPropertyName(node.name) && isComputedPropertyName(subsequentName) && isTypeIdenticalTo(checkComputedPropertyName(node.name), checkComputedPropertyName(subsequentName)) || + // Both are literal property names that are the same. isPropertyNameLiteral(node.name) && isPropertyNameLiteral(subsequentName) && getEscapedTextOfIdentifierOrLiteral(node.name) === getEscapedTextOfIdentifierOrLiteral(subsequentName))) { const reportError = (node.kind === 174 /* MethodDeclaration */ || node.kind === 173 /* MethodSignature */) && isStatic(node) !== isStatic(subsequentNode); if (reportError) { @@ -78881,24 +73024,21 @@ ${lanes.join("\n")} } } if (multipleConstructorImplementation) { - forEach(functionDeclarations, (declaration) => { + forEach(functionDeclarations, declaration => { error2(declaration, Diagnostics.Multiple_constructor_implementations_are_not_allowed); }); } if (duplicateFunctionDeclaration) { - forEach(functionDeclarations, (declaration) => { + forEach(functionDeclarations, declaration => { error2(getNameOfDeclaration(declaration) || declaration, Diagnostics.Duplicate_function_implementation); }); } if (hasNonAmbientClass && !isConstructor && symbol.flags & 16 /* Function */ && declarations) { - const relatedDiagnostics = filter(declarations, (d) => d.kind === 263 /* ClassDeclaration */).map((d) => createDiagnosticForNode(d, Diagnostics.Consider_adding_a_declare_modifier_to_this_class)); - forEach(declarations, (declaration) => { + const relatedDiagnostics = filter(declarations, d => d.kind === 263 /* ClassDeclaration */).map(d => createDiagnosticForNode(d, Diagnostics.Consider_adding_a_declare_modifier_to_this_class)); + forEach(declarations, declaration => { const diagnostic = declaration.kind === 263 /* ClassDeclaration */ ? Diagnostics.Class_declaration_cannot_implement_overload_list_for_0 : declaration.kind === 262 /* FunctionDeclaration */ ? Diagnostics.Function_with_bodies_can_only_merge_with_classes_that_are_ambient : void 0; if (diagnostic) { - addRelatedInfo( - error2(getNameOfDeclaration(declaration) || declaration, diagnostic, symbolName(symbol)), - ...relatedDiagnostics - ); + addRelatedInfo(error2(getNameOfDeclaration(declaration) || declaration, diagnostic, symbolName(symbol)), ...relatedDiagnostics); } }); } @@ -78916,10 +73056,7 @@ ${lanes.join("\n")} for (const signature of signatures) { if (!isImplementationCompatibleWithOverload(bodySignature, signature)) { const errorNode = signature.declaration && isJSDocSignature(signature.declaration) ? signature.declaration.parent.tagName : signature.declaration; - addRelatedInfo( - error2(errorNode, Diagnostics.This_overload_signature_is_not_compatible_with_its_implementation_signature), - createDiagnosticForNode(bodyDeclaration, Diagnostics.The_implementation_signature_is_declared_here) - ); + addRelatedInfo(error2(errorNode, Diagnostics.This_overload_signature_is_not_compatible_with_its_implementation_signature), createDiagnosticForNode(bodyDeclaration, Diagnostics.The_implementation_signature_is_declared_here)); break; } } @@ -78994,13 +73131,14 @@ ${lanes.join("\n")} if (!isEntityNameExpression(expression)) { return 1 /* ExportValue */; } + d = expression; case 271 /* ImportEqualsDeclaration */: case 274 /* NamespaceImport */: case 273 /* ImportClause */: let result = 0 /* None */; const target = resolveAlias(getSymbolOfDeclaration(d)); - forEach(target.declarations, (d2) => { + forEach(target.declarations, d2 => { result |= getDeclarationSpaces(d2); }); return result; @@ -79030,10 +73168,8 @@ ${lanes.join("\n")} if (typeAsPromise.promisedTypeOfPromise) { return typeAsPromise.promisedTypeOfPromise; } - if (isReferenceToType2(type, getGlobalPromiseType( - /*reportErrors*/ - false - ))) { + if (isReferenceToType2(type, getGlobalPromiseType( /*reportErrors*/ + false))) { return typeAsPromise.promisedTypeOfPromise = getTypeArguments(type)[0]; } if (allTypesAssignableToKind(getBaseConstraintOrType(type), 402784252 /* Primitive */ | 131072 /* Never */)) { @@ -79083,6 +73219,7 @@ ${lanes.join("\n")} } return typeAsPromise.promisedTypeOfPromise = getUnionType(map(onfulfilledParameterSignatures, getTypeOfFirstParameterOfSignature), 2 /* Subtype */); } + function checkAwaitedType(type, withAlias, errorNode, diagnosticMessage, ...args) { const awaitedType = withAlias ? getAwaitedType(type, errorNode, diagnosticMessage, ...args) : getAwaitedTypeNoAlias(type, errorNode, diagnosticMessage, ...args); return awaitedType || errorType; @@ -79097,10 +73234,8 @@ ${lanes.join("\n")} function isAwaitedTypeInstantiation(type) { var _a; if (type.flags & 16777216 /* Conditional */) { - const awaitedSymbol = getGlobalAwaitedSymbol( - /*reportErrors*/ - false - ); + const awaitedSymbol = getGlobalAwaitedSymbol( /*reportErrors*/ + false); return !!awaitedSymbol && type.aliasSymbol === awaitedSymbol && ((_a = type.aliasTypeArguments) == null ? void 0 : _a.length) === 1; } return false; @@ -79121,10 +73256,8 @@ ${lanes.join("\n")} return false; } function tryCreateAwaitedType(type) { - const awaitedSymbol = getGlobalAwaitedSymbol( - /*reportErrors*/ - true - ); + const awaitedSymbol = getGlobalAwaitedSymbol( /*reportErrors*/ + true); if (awaitedSymbol) { return getTypeAliasInstantiation(awaitedSymbol, [unwrapAwaitedType(type)]); } @@ -79162,7 +73295,7 @@ ${lanes.join("\n")} } return void 0; } - const mapper = errorNode ? (constituentType) => getAwaitedTypeNoAlias(constituentType, errorNode, diagnosticMessage, ...args) : getAwaitedTypeNoAlias; + const mapper = errorNode ? constituentType => getAwaitedTypeNoAlias(constituentType, errorNode, diagnosticMessage, ...args) : getAwaitedTypeNoAlias; awaitedTypeStack.push(type.id); const mapped = mapType(type, mapper); awaitedTypeStack.pop(); @@ -79171,13 +73304,11 @@ ${lanes.join("\n")} if (isAwaitedTypeNeeded(type)) { return typeAsAwaitable.awaitedTypeOfType = type; } - const thisTypeForErrorOut = { value: void 0 }; - const promisedType = getPromisedTypeOfPromise( - type, - /*errorNode*/ - void 0, - thisTypeForErrorOut - ); + const thisTypeForErrorOut = { + value: void 0 + }; + const promisedType = getPromisedTypeOfPromise(type, /*errorNode*/ + void 0, thisTypeForErrorOut); if (promisedType) { if (type.id === promisedType.id || awaitedTypeStack.lastIndexOf(promisedType.id) >= 0) { if (errorNode) { @@ -79213,10 +73344,8 @@ ${lanes.join("\n")} if (isErrorType(returnType)) { return; } - const globalPromiseType = getGlobalPromiseType( - /*reportErrors*/ - true - ); + const globalPromiseType = getGlobalPromiseType( /*reportErrors*/ + true); if (globalPromiseType !== emptyGenericType && !isReferenceToType2(returnType, globalPromiseType)) { reportErrorForInvalidReturnType(Diagnostics.The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_Did_you_mean_to_write_Promise_0, returnTypeNode, returnTypeErrorLocation, typeToString(getAwaitedTypeNoAlias(returnType) || voidType)); return; @@ -79231,38 +73360,27 @@ ${lanes.join("\n")} reportErrorForInvalidReturnType(Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, returnTypeNode, returnTypeErrorLocation, typeToString(returnType)); return; } - const promiseConstructorSymbol = resolveEntityName( - promiseConstructorName, - 111551 /* Value */, - /*ignoreErrors*/ - true - ); + const promiseConstructorSymbol = resolveEntityName(promiseConstructorName, 111551 /* Value */, /*ignoreErrors*/ + true); const promiseConstructorType = promiseConstructorSymbol ? getTypeOfSymbol(promiseConstructorSymbol) : errorType; if (isErrorType(promiseConstructorType)) { - if (promiseConstructorName.kind === 80 /* Identifier */ && promiseConstructorName.escapedText === "Promise" && getTargetType(returnType) === getGlobalPromiseType( - /*reportErrors*/ - false - )) { + if (promiseConstructorName.kind === 80 /* Identifier */ && promiseConstructorName.escapedText === "Promise" && getTargetType(returnType) === getGlobalPromiseType( /*reportErrors*/ + false)) { error2(returnTypeErrorLocation, Diagnostics.An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option); } else { reportErrorForInvalidReturnType(Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, returnTypeNode, returnTypeErrorLocation, entityNameToString(promiseConstructorName)); } return; } - const globalPromiseConstructorLikeType = getGlobalPromiseConstructorLikeType( - /*reportErrors*/ - true - ); + const globalPromiseConstructorLikeType = getGlobalPromiseConstructorLikeType( /*reportErrors*/ + true); if (globalPromiseConstructorLikeType === emptyObjectType) { reportErrorForInvalidReturnType(Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, returnTypeNode, returnTypeErrorLocation, entityNameToString(promiseConstructorName)); return; } const headMessage = Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value; - const errorInfo = () => returnTypeNode === returnTypeErrorLocation ? void 0 : chainDiagnosticMessages( - /*details*/ - void 0, - Diagnostics.The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type - ); + const errorInfo = () => returnTypeNode === returnTypeErrorLocation ? void 0 : chainDiagnosticMessages( /*details*/ + void 0, Diagnostics.The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type); if (!checkTypeAssignableTo(promiseConstructorType, globalPromiseConstructorLikeType, returnTypeErrorLocation, headMessage, errorInfo)) { return; } @@ -79273,13 +73391,8 @@ ${lanes.join("\n")} return; } } - checkAwaitedType( - returnType, - /*withAlias*/ - false, - node, - Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member - ); + checkAwaitedType(returnType, /*withAlias*/ + false, node, Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); function reportErrorForInvalidReturnType(message, returnTypeNode2, returnTypeErrorLocation2, typeName) { if (returnTypeNode2 === returnTypeErrorLocation2) { error2(returnTypeErrorLocation2, message, typeName); @@ -79297,8 +73410,7 @@ ${lanes.join("\n")} 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) { @@ -79325,12 +73437,9 @@ ${lanes.join("\n")} checkTypeAssignableTo(returnType, expectedReturnType, node.expression, headMessage); } function createCallSignature(typeParameters, thisParameter, parameters, returnType, typePredicate, minArgumentCount = parameters.length, flags = 0 /* None */) { - const decl = factory.createFunctionTypeNode( - /*typeParameters*/ - void 0, - emptyArray, - factory.createKeywordTypeNode(133 /* AnyKeyword */) - ); + const decl = factory.createFunctionTypeNode( /*typeParameters*/ + void 0, emptyArray, factory.createKeywordTypeNode(133 /* AnyKeyword */)); + return createSignature(decl, typeParameters, thisParameter, parameters, returnType, typePredicate, minArgumentCount, flags); } function createFunctionType(typeParameters, thisParameter, parameters, returnType, typePredicate, minArgumentCount, flags) { @@ -79338,49 +73447,28 @@ ${lanes.join("\n")} return getOrCreateTypeFromSignature(signature); } function createGetterFunctionType(type) { - return createFunctionType( - /*typeParameters*/ - void 0, - /*thisParameter*/ - void 0, - emptyArray, - type - ); + return createFunctionType( /*typeParameters*/ + void 0, /*thisParameter*/ + void 0, emptyArray, type); } function createSetterFunctionType(type) { const valueParam = createParameter("value", type); - return createFunctionType( - /*typeParameters*/ - void 0, - /*thisParameter*/ - void 0, - [valueParam], - voidType - ); + return createFunctionType( /*typeParameters*/ + void 0, /*thisParameter*/ + void 0, [valueParam], voidType); } function markTypeNodeAsReferenced(node) { - markEntityNameOrEntityExpressionAsReference( - node && getEntityNameFromTypeNode(node), - /*forDecoratorMetadata*/ - false - ); + markEntityNameOrEntityExpressionAsReference(node && getEntityNameFromTypeNode(node), /*forDecoratorMetadata*/ + false); } function markEntityNameOrEntityExpressionAsReference(typeName, forDecoratorMetadata) { - if (!typeName) - return; + 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, - /*nameArg*/ - void 0, - /*isUse*/ - true - ); + const rootSymbol = resolveName(rootName, rootName.escapedText, meaning, /*nameNotFoundMessage*/ + void 0, /*nameArg*/ + void 0, /*isUse*/ + true); if (rootSymbol && rootSymbol.flags & 2097152 /* Alias */) { if (canCollectSymbolAliasAccessabilityData && symbolIsValue(rootSymbol) && !isConstEnumOrConstEnumOnlyModule(resolveAlias(rootSymbol)) && !getTypeOnlyAliasDeclaration(rootSymbol)) { markAliasSymbolAsReferenced(rootSymbol); @@ -79396,11 +73484,8 @@ ${lanes.join("\n")} function markDecoratorMedataDataTypeNodeAsReferenced(node) { const entityName = getEntityNameForDecoratorMetadata(node); if (entityName && isEntityName(entityName)) { - markEntityNameOrEntityExpressionAsReference( - entityName, - /*forDecoratorMetadata*/ - true - ); + markEntityNameOrEntityExpressionAsReference(entityName, /*forDecoratorMetadata*/ + true); } } function getEntityNameForDecoratorMetadata(node) { @@ -79477,11 +73562,13 @@ ${lanes.join("\n")} if (isPrivateIdentifier(node.name) && (isMethodDeclaration(node) || isAccessor(node) || isAutoAccessorPropertyDeclaration(node))) { checkExternalEmitHelpers(firstDecorator, 8388608 /* SetFunctionName */); } + if (isComputedPropertyName(node.name)) { checkExternalEmitHelpers(firstDecorator, 16777216 /* PropKey */); } } } + if (compilerOptions.emitDecoratorMetadata) { checkExternalEmitHelpers(firstDecorator, 16 /* Metadata */); switch (node.kind) { @@ -79566,11 +73653,8 @@ ${lanes.join("\n")} } function checkJSDocLinkLikeTag(node) { if (node.name) { - resolveJSDocMemberName( - node.name, - /*ignoreErrors*/ - true - ); + resolveJSDocMemberName(node.name, /*ignoreErrors*/ + true); } } function checkJSDocParameterTag(node) { @@ -79648,9 +73732,9 @@ ${lanes.join("\n")} const symbol = getSymbolOfDeclaration(node); const localSymbol = node.localSymbol || symbol; const firstDeclaration = (_a = localSymbol.declarations) == null ? void 0 : _a.find( - // Get first non javascript function declaration - (declaration) => declaration.kind === node.kind && !(declaration.flags & 524288 /* JavaScriptFile */) - ); + // Get first non javascript function declaration + declaration => declaration.kind === node.kind && !(declaration.flags & 524288 /* JavaScriptFile */)); + if (node === firstDeclaration) { checkFunctionOrConstructorSymbol(localSymbol); } @@ -79745,6 +73829,7 @@ ${lanes.join("\n")} function isIdentifierThatStartsWithUnderscore(node) { return isIdentifier(node) && idText(node).charCodeAt(0) === 95 /* _ */; } + function checkUnusedClassMembers(node, addDiagnostic) { for (const member of node.members) { switch (member.kind) { @@ -79777,22 +73862,24 @@ ${lanes.join("\n")} } } function checkUnusedInferTypeParameter(node, addDiagnostic) { - const { typeParameter } = node; + const { + typeParameter + } = node; if (isTypeParameterUnused(typeParameter)) { addDiagnostic(node, 1 /* Parameter */, createDiagnosticForNode(node, Diagnostics._0_is_declared_but_its_value_is_never_read, idText(typeParameter.name))); } } function checkUnusedTypeParameters(node, addDiagnostic) { 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(); + 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; + const { + parent: parent2 + } = typeParameter; if (parent2.kind !== 195 /* InferType */ && parent2.typeParameters.every(isTypeParameterUnused)) { if (tryAddToSet(seenParentsWithEveryUnused, parent2)) { const sourceFile = getSourceFileOfNode(parent2); @@ -79831,10 +73918,10 @@ ${lanes.join("\n")} return isAmbientModule(declaration) || (isVariableDeclaration(declaration) && isForInOrOfStatement(declaration.parent.parent) || isImportedDeclaration(declaration)) && isIdentifierThatStartsWithUnderscore(declaration.name); } function checkUnusedLocalsAndParameters(nodeWithLocals, addDiagnostic) { - const unusedImports = /* @__PURE__ */ new Map(); - const unusedDestructures = /* @__PURE__ */ new Map(); - const unusedVariables = /* @__PURE__ */ new Map(); - nodeWithLocals.locals.forEach((local) => { + const unusedImports = /* @__PURE__ */new Map(); + const unusedDestructures = /* @__PURE__ */new Map(); + const unusedVariables = /* @__PURE__ */new Map(); + nodeWithLocals.locals.forEach(local => { if (local.flags & 262144 /* TypeParameter */ ? !(local.flags & 3 /* Variable */ && !(local.isReferenced & 3 /* Variable */)) : local.isReferenced || local.exportSymbol) { return; } @@ -79878,14 +73965,9 @@ ${lanes.join("\n")} const importDecl = importClause.parent; const nDeclarations = (importClause.name ? 1 : 0) + (importClause.namedBindings ? importClause.namedBindings.kind === 274 /* NamespaceImport */ ? 1 : importClause.namedBindings.elements.length : 0); if (nDeclarations === unuseds.length) { - addDiagnostic( - importDecl, - 0 /* Local */, - unuseds.length === 1 ? createDiagnosticForNode(importDecl, Diagnostics._0_is_declared_but_its_value_is_never_read, idText(first(unuseds).name)) : createDiagnosticForNode(importDecl, Diagnostics.All_imports_in_import_declaration_are_unused) - ); + addDiagnostic(importDecl, 0 /* Local */, unuseds.length === 1 ? createDiagnosticForNode(importDecl, Diagnostics._0_is_declared_but_its_value_is_never_read, idText(first(unuseds).name)) : createDiagnosticForNode(importDecl, Diagnostics.All_imports_in_import_declaration_are_unused)); } else { - for (const unused of unuseds) - errorUnusedLocal(unused, idText(unused.name), addDiagnostic); + for (const unused of unuseds) errorUnusedLocal(unused, idText(unused.name), addDiagnostic); } }); unusedDestructures.forEach(([bindingPattern, bindingElements]) => { @@ -79894,11 +73976,7 @@ ${lanes.join("\n")} if (bindingElements.length === 1 && bindingPattern.parent.kind === 260 /* VariableDeclaration */ && bindingPattern.parent.parent.kind === 261 /* VariableDeclarationList */) { addToGroup(unusedVariables, bindingPattern.parent.parent, bindingPattern.parent, getNodeId); } else { - addDiagnostic( - bindingPattern, - kind, - bindingElements.length === 1 ? createDiagnosticForNode(bindingPattern, Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(first(bindingElements).name)) : createDiagnosticForNode(bindingPattern, Diagnostics.All_destructured_elements_are_unused) - ); + addDiagnostic(bindingPattern, kind, bindingElements.length === 1 ? createDiagnosticForNode(bindingPattern, Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(first(bindingElements).name)) : createDiagnosticForNode(bindingPattern, Diagnostics.All_destructured_elements_are_unused)); } } else { for (const e of bindingElements) { @@ -79908,11 +73986,7 @@ ${lanes.join("\n")} }); unusedVariables.forEach(([declarationList, declarations]) => { if (declarationList.declarations.length === declarations.length) { - addDiagnostic( - declarationList, - 0 /* Local */, - declarations.length === 1 ? createDiagnosticForNode(first(declarations).name, Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(first(declarations).name)) : createDiagnosticForNode(declarationList.parent.kind === 243 /* VariableStatement */ ? declarationList.parent : declarationList, Diagnostics.All_variables_are_unused) - ); + addDiagnostic(declarationList, 0 /* Local */, declarations.length === 1 ? createDiagnosticForNode(first(declarations).name, Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(first(declarations).name)) : createDiagnosticForNode(declarationList.parent.kind === 243 /* VariableStatement */ ? declarationList.parent : declarationList, Diagnostics.All_variables_are_unused)); } else { for (const decl of declarations) { addDiagnostic(decl, 0 /* Local */, createDiagnosticForNode(decl, Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(decl.name))); @@ -79928,10 +74002,7 @@ ${lanes.join("\n")} Debug.assert(isParameterDeclaration(wrappingDeclaration), "Only parameter declaration should be checked here"); const diagnostic = createDiagnosticForNode(node.name, Diagnostics._0_is_an_unused_renaming_of_1_Did_you_intend_to_use_it_as_a_type_annotation, declarationNameToString(node.name), declarationNameToString(node.propertyName)); if (!wrappingDeclaration.type) { - addRelatedInfo( - diagnostic, - createFileDiagnostic(getSourceFileOfNode(wrappingDeclaration), wrappingDeclaration.end, 1, Diagnostics.We_can_only_write_a_type_for_0_by_adding_a_type_for_the_entire_parameter_here, declarationNameToString(node.propertyName)) - ); + addRelatedInfo(diagnostic, createFileDiagnostic(getSourceFileOfNode(wrappingDeclaration), wrappingDeclaration.end, 1, Diagnostics.We_can_only_write_a_type_for_0_by_adding_a_type_for_the_entire_parameter_here, declarationNameToString(node.propertyName))); } diagnostics.add(diagnostic); } @@ -79951,6 +74022,7 @@ ${lanes.join("\n")} function isImportedDeclaration(node) { return node.kind === 273 /* ImportClause */ || node.kind === 276 /* ImportSpecifier */ || node.kind === 274 /* NamespaceImport */; } + function importClauseFromImported(decl) { return decl.kind === 273 /* ImportClause */ ? decl : decl.kind === 274 /* NamespaceImport */ ? decl.parent : decl.parent.parent; } @@ -79973,7 +74045,7 @@ ${lanes.join("\n")} if (languageVersion >= 2 /* ES2015 */ || !hasRestParameter(node) || node.flags & 33554432 /* Ambient */ || nodeIsMissing(node.body)) { return; } - forEach(node.parameters, (p) => { + forEach(node.parameters, p => { if (p.name && !isBindingPattern(p.name) && p.name.escapedText === argumentsSymbol.escapedName) { errorSkippedOn("noEmit", p, Diagnostics.Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters); } @@ -80001,7 +74073,7 @@ ${lanes.join("\n")} return true; } function checkIfThisIsCapturedInEnclosingScope(node) { - findAncestor(node, (current) => { + findAncestor(node, current => { if (getNodeCheckFlags(current) & 4 /* CaptureThis */) { const isDeclaration2 = node.kind !== 80 /* Identifier */; if (isDeclaration2) { @@ -80015,7 +74087,7 @@ ${lanes.join("\n")} }); } function checkIfNewTargetIsCapturedInEnclosingScope(node) { - findAncestor(node, (current) => { + findAncestor(node, current => { if (getNodeCheckFlags(current) & 8 /* CaptureNewTarget */) { const isDeclaration2 = node.kind !== 80 /* Identifier */; if (isDeclaration2) { @@ -80097,8 +74169,7 @@ ${lanes.join("\n")} } } function checkCollisionsForDeclarationName(node, name) { - if (!name) - return; + if (!name) return; checkCollisionWithRequireExportsInGeneratedCode(node, name); checkCollisionWithGlobalPromiseInGeneratedCode(node, name); recordPotentialCollisionWithWeakMapSetInGeneratedCode(node, name); @@ -80118,19 +74189,11 @@ ${lanes.join("\n")} } const symbol = getSymbolOfDeclaration(node); if (symbol.flags & 1 /* FunctionScopedVariable */) { - if (!isIdentifier(node.name)) - return Debug.fail(); - const localDeclarationSymbol = resolveName( - node, - node.name.escapedText, - 3 /* Variable */, - /*nameNotFoundMessage*/ - void 0, - /*nameArg*/ - void 0, - /*isUse*/ - false - ); + if (!isIdentifier(node.name)) return Debug.fail(); + const localDeclarationSymbol = resolveName(node, node.name.escapedText, 3 /* Variable */, /*nameNotFoundMessage*/ + void 0, /*nameArg*/ + void 0, /*isUse*/ + false); if (localDeclarationSymbol && localDeclarationSymbol !== symbol && localDeclarationSymbol.flags & 2 /* BlockScopedVariable */) { if (getDeclarationNodeFlagsFromSymbol(localDeclarationSymbol) & 7 /* BlockScoped */) { const varDeclList = getAncestor(localDeclarationSymbol.valueDeclaration, 261 /* VariableDeclarationList */); @@ -80170,6 +74233,7 @@ ${lanes.join("\n")} if (isObjectBindingPattern(node.parent) && node.dotDotDotToken && languageVersion < 5 /* ES2018 */) { checkExternalEmitHelpers(node, 4 /* Rest */); } + if (node.propertyName && node.propertyName.kind === 167 /* ComputedPropertyName */) { checkComputedPropertyName(node.propertyName); } @@ -80183,21 +74247,11 @@ ${lanes.join("\n")} const nameText = getPropertyNameFromType(exprType); const property = getPropertyOfType(parentType, nameText); if (property) { - markPropertyAsReferenced( - property, - /*nodeForCheckWriteOnly*/ - void 0, - /*isSelfTypeAccess*/ - false - ); - checkPropertyAccessibility( - node, - !!parent2.initializer && parent2.initializer.kind === 108 /* SuperKeyword */, - /*writing*/ - false, - parentType, - property - ); + markPropertyAsReferenced(property, /*nodeForCheckWriteOnly*/ + void 0, /*isSelfTypeAccess*/ + false); + checkPropertyAccessibility(node, !!parent2.initializer && parent2.initializer.kind === 108 /* SuperKeyword */, /*writing*/ + false, parentType, property); } } } @@ -80206,6 +74260,7 @@ ${lanes.join("\n")} if (node.name.kind === 207 /* ArrayBindingPattern */ && languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) { checkExternalEmitHelpers(node, 512 /* Read */); } + forEach(node.name.elements, checkSourceElement); } if (node.initializer && isParameterDeclaration(node) && nodeIsMissing(getContainingFunction(node).body)) { @@ -80250,33 +74305,21 @@ ${lanes.join("\n")} const isJSObjectLiteralInitializer = isInJSFile(node) && isObjectLiteralExpression(initializer) && (initializer.properties.length === 0 || isPrototypeAccess(node.name)) && !!((_a = symbol.exports) == null ? void 0 : _a.size); if (!isJSObjectLiteralInitializer && node.parent.parent.kind !== 249 /* ForInStatement */) { const initializerType = checkExpressionCached(initializer); - checkTypeAssignableToAndOptionallyElaborate( - initializerType, - type, - node, - initializer, - /*headMessage*/ - void 0 - ); + checkTypeAssignableToAndOptionallyElaborate(initializerType, type, node, initializer, /*headMessage*/ + void 0); const blockScopeKind = getCombinedNodeFlagsCached(node) & 7 /* BlockScoped */; if (blockScopeKind === 6 /* AwaitUsing */) { - const globalAsyncDisposableType = getGlobalAsyncDisposableType( - /*reportErrors*/ - true - ); - const globalDisposableType = getGlobalDisposableType( - /*reportErrors*/ - true - ); + const globalAsyncDisposableType = getGlobalAsyncDisposableType( /*reportErrors*/ + true); + const globalDisposableType = getGlobalDisposableType( /*reportErrors*/ + true); if (globalAsyncDisposableType !== emptyObjectType && globalDisposableType !== emptyObjectType) { const optionalDisposableType = getUnionType([globalAsyncDisposableType, globalDisposableType, nullType, undefinedType]); checkTypeAssignableTo(initializerType, optionalDisposableType, initializer, Diagnostics.The_initializer_of_an_await_using_declaration_must_be_either_an_object_with_a_Symbol_asyncDispose_or_Symbol_dispose_method_or_be_null_or_undefined); } } else if (blockScopeKind === 4 /* Using */) { - const globalDisposableType = getGlobalDisposableType( - /*reportErrors*/ - true - ); + const globalDisposableType = getGlobalDisposableType( /*reportErrors*/ + true); if (globalDisposableType !== emptyObjectType) { const optionalDisposableType = getUnionType([globalDisposableType, nullType, undefinedType]); checkTypeAssignableTo(initializerType, optionalDisposableType, initializer, Diagnostics.The_initializer_of_a_using_declaration_must_be_either_an_object_with_a_Symbol_dispose_method_or_be_null_or_undefined); @@ -80285,7 +74328,7 @@ ${lanes.join("\n")} } } if (symbol.declarations && symbol.declarations.length > 1) { - if (some(symbol.declarations, (d) => d !== node && isVariableLike(d) && !areDeclarationFlagsIdentical(d, node))) { + if (some(symbol.declarations, d => d !== node && isVariableLike(d) && !areDeclarationFlagsIdentical(d, node))) { error2(node.name, Diagnostics.All_declarations_of_0_must_have_identical_modifiers, declarationNameToString(node.name)); } } @@ -80295,14 +74338,8 @@ ${lanes.join("\n")} errorNextVariableOrPropertyDeclarationMustHaveSameType(symbol.valueDeclaration, type, node, declarationType); } if (hasOnlyExpressionInitializer(node) && node.initializer) { - checkTypeAssignableToAndOptionallyElaborate( - checkExpressionCached(node.initializer), - declarationType, - node, - node.initializer, - /*headMessage*/ - void 0 - ); + checkTypeAssignableToAndOptionallyElaborate(checkExpressionCached(node.initializer), declarationType, node, node.initializer, /*headMessage*/ + void 0); } if (symbol.valueDeclaration && !areDeclarationFlagsIdentical(node, symbol.valueDeclaration)) { error2(node.name, Diagnostics.All_declarations_of_0_must_have_identical_modifiers, declarationNameToString(node.name)); @@ -80320,13 +74357,7 @@ ${lanes.join("\n")} const nextDeclarationName = getNameOfDeclaration(nextDeclaration); const message = nextDeclaration.kind === 172 /* PropertyDeclaration */ || nextDeclaration.kind === 171 /* PropertySignature */ ? Diagnostics.Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_type_2 : Diagnostics.Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2; const declName = declarationNameToString(nextDeclarationName); - const err = error2( - nextDeclarationName, - message, - declName, - typeToString(firstType), - typeToString(nextType) - ); + const err = error2(nextDeclarationName, message, declName, typeToString(firstType), typeToString(nextType)); if (firstDeclaration) { addRelatedInfo(err, createDiagnosticForNode(firstDeclaration, Diagnostics._0_was_also_declared_here, declName)); } @@ -80343,7 +74374,12 @@ ${lanes.join("\n")} } function checkVariableDeclaration(node) { var _a, _b; - (_a = tracing) == null ? void 0 : _a.push(tracing.Phase.Check, "checkVariableDeclaration", { kind: node.kind, pos: node.pos, end: node.end, path: node.tracingPath }); + (_a = tracing) == null ? void 0 : _a.push(tracing.Phase.Check, "checkVariableDeclaration", { + kind: node.kind, + pos: node.pos, + end: node.end, + path: node.tracingPath + }); checkGrammarVariableDeclaration(node); checkVariableLikeDeclaration(node); (_b = tracing) == null ? void 0 : _b.pop(); @@ -80357,11 +74393,11 @@ ${lanes.join("\n")} if (blockScopeKind === 4 /* Using */ || blockScopeKind === 6 /* AwaitUsing */) { checkExternalEmitHelpers(node, 33554432 /* AddDisposableResourceAndDisposeResources */); } + 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) { @@ -80379,8 +74415,7 @@ ${lanes.join("\n")} checkSourceElement(node.elseStatement); } function checkTestingKnownTruthyCallableOrAwaitableType(condExpr, condType, body) { - if (!strictNullChecks) - return; + if (!strictNullChecks) return; bothHelper(condExpr, body); function bothHelper(condExpr2, body2) { condExpr2 = skipParentheses(condExpr2); @@ -80401,8 +74436,7 @@ ${lanes.join("\n")} } const type = location === condExpr2 ? condType : checkTruthinessExpression(location); 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) { @@ -80416,13 +74450,8 @@ ${lanes.join("\n")} const isUsed = testedSymbol && isBinaryExpression(condExpr2.parent) && isSymbolUsedInBinaryExpressionChain(condExpr2.parent, testedSymbol) || testedSymbol && body2 && isSymbolUsedInConditionBody(condExpr2, body2, testedNode, testedSymbol); if (!isUsed) { if (isPromise) { - errorAndMaybeSuggestAwait( - location, - /*maybeMissingAwait*/ - true, - Diagnostics.This_condition_will_always_return_true_since_this_0_is_always_defined, - getTypeNameForErrorDisplay(type) - ); + errorAndMaybeSuggestAwait(location, /*maybeMissingAwait*/ + true, Diagnostics.This_condition_will_always_return_true_since_this_0_is_always_defined, getTypeNameForErrorDisplay(type)); } else { error2(location, Diagnostics.This_condition_will_always_return_true_since_this_function_is_always_defined_Did_you_mean_to_call_it_instead); } @@ -80510,10 +74539,8 @@ ${lanes.join("\n")} 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); @@ -80534,6 +74561,7 @@ ${lanes.join("\n")} } else if (compilerOptions.downlevelIteration && languageVersion < 2 /* ES2015 */) { checkExternalEmitHelpers(node, 256 /* ForOfIncludes */); } + if (node.initializer.kind === 261 /* VariableDeclarationList */) { checkVariableDeclarationList(node.initializer); } else { @@ -80543,11 +74571,7 @@ ${lanes.join("\n")} checkDestructuringAssignment(varExpr, iteratedType || errorType); } else { const leftType = checkExpression(varExpr); - checkReferenceExpression( - varExpr, - Diagnostics.The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access, - Diagnostics.The_left_hand_side_of_a_for_of_statement_may_not_be_an_optional_property_access - ); + checkReferenceExpression(varExpr, Diagnostics.The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access, Diagnostics.The_left_hand_side_of_a_for_of_statement_may_not_be_an_optional_property_access); if (iteratedType) { checkTypeAssignableToAndOptionallyElaborate(iteratedType, leftType, varExpr, node.expression); } @@ -80575,11 +74599,7 @@ ${lanes.join("\n")} } else if (!isTypeAssignableTo(getIndexTypeOrString(rightType), leftType)) { error2(varExpr, Diagnostics.The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any); } else { - checkReferenceExpression( - varExpr, - Diagnostics.The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access, - Diagnostics.The_left_hand_side_of_a_for_in_statement_may_not_be_an_optional_property_access - ); + checkReferenceExpression(varExpr, Diagnostics.The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access, Diagnostics.The_left_hand_side_of_a_for_in_statement_may_not_be_an_optional_property_access); } } if (rightType === neverType || !isTypeAssignableToKind(rightType, 67108864 /* NonPrimitive */ | 58982400 /* InstantiableNonPrimitive */)) { @@ -80598,14 +74618,8 @@ ${lanes.join("\n")} if (isTypeAny(inputType)) { return inputType; } - return getIteratedTypeOrElementType( - use, - inputType, - sentType, - errorNode, - /*checkAssignability*/ - true - ) || anyType; + return getIteratedTypeOrElementType(use, inputType, sentType, errorNode, /*checkAssignability*/ + true) || anyType; } function getIteratedTypeOrElementType(use, inputType, sentType, errorNode, checkAssignability) { const allowAsyncIterables = (use & 2 /* AllowsAsyncIterablesFlag */) !== 0; @@ -80636,7 +74650,7 @@ ${lanes.join("\n")} if (use & 4 /* AllowsStringInputFlag */) { if (arrayType.flags & 1048576 /* Union */) { const arrayTypes = inputType.types; - const filteredTypes = filter(arrayTypes, (t) => !(t.flags & 402653316 /* StringLike */)); + const filteredTypes = filter(arrayTypes, t => !(t.flags & 402653316 /* StringLike */)); if (filteredTypes !== arrayTypes) { arrayType = getUnionType(filteredTypes, 2 /* Subtype */); } @@ -80660,12 +74674,7 @@ ${lanes.join("\n")} if (errorNode && !reportedError) { const allowsStrings = !!(use & 4 /* AllowsStringInputFlag */) && !hasStringConstituent; const [defaultDiagnostic, maybeMissingAwait] = getIterationDiagnosticDetails(allowsStrings, downlevelIteration); - errorAndMaybeSuggestAwait( - errorNode, - maybeMissingAwait && !!getAwaitedTypeOfPromise(arrayType), - defaultDiagnostic, - typeToString(arrayType) - ); + errorAndMaybeSuggestAwait(errorNode, maybeMissingAwait && !!getAwaitedTypeOfPromise(arrayType), defaultDiagnostic, typeToString(arrayType)); } return hasStringConstituent ? possibleOutOfBounds ? includeUndefinedInIndexSignature(stringType) : stringType : void 0; } @@ -80676,19 +74685,15 @@ ${lanes.join("\n")} } return getUnionType(possibleOutOfBounds ? [arrayElementType, stringType, undefinedType] : [arrayElementType, stringType], 2 /* Subtype */); } + return use & 128 /* PossiblyOutOfBounds */ ? includeUndefinedInIndexSignature(arrayElementType) : arrayElementType; function getIterationDiagnosticDetails(allowsStrings, downlevelIteration2) { var _a; if (downlevelIteration2) { return allowsStrings ? [Diagnostics.Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator, true] : [Diagnostics.Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator, true]; } - const yieldType = getIterationTypeOfIterable( - use, - 0 /* Yield */, - inputType, - /*errorNode*/ - void 0 - ); + const yieldType = getIterationTypeOfIterable(use, 0 /* Yield */, inputType, /*errorNode*/ + void 0); if (yieldType) { return [Diagnostics.Type_0_can_only_be_iterated_through_when_using_the_downlevelIteration_flag_or_with_a_target_of_es2015_or_higher, false]; } @@ -80726,12 +74731,20 @@ ${lanes.join("\n")} const id = getTypeListId([yieldType, returnType, nextType]); let iterationTypes = iterationTypesCache.get(id); if (!iterationTypes) { - iterationTypes = { yieldType, returnType, nextType }; + iterationTypes = { + yieldType, + returnType, + nextType + }; iterationTypesCache.set(id, iterationTypes); } return iterationTypes; } - return { yieldType, returnType, nextType }; + return { + yieldType, + returnType, + nextType + }; } function combineIterationTypes(array) { let yieldTypes; @@ -80749,11 +74762,7 @@ ${lanes.join("\n")} nextTypes = append(nextTypes, iterationTypes.nextType); } if (yieldTypes || returnTypes || nextTypes) { - return createIterationTypes( - yieldTypes && getUnionType(yieldTypes), - returnTypes && getUnionType(returnTypes), - nextTypes && getIntersectionType(nextTypes) - ); + return createIterationTypes(yieldTypes && getUnionType(yieldTypes), returnTypes && getUnionType(returnTypes), nextTypes && getIntersectionType(nextTypes)); } return noIterationTypes; } @@ -80769,7 +74778,9 @@ ${lanes.join("\n")} return anyIterationTypes; } if (!(type.flags & 1048576 /* Union */)) { - const errorOutputContainer = errorNode ? { errors: void 0 } : void 0; + const errorOutputContainer = errorNode ? { + errors: void 0 + } : void 0; const iterationTypes2 = getIterationTypesOfIterableWorker(type, use, errorNode, errorOutputContainer); if (iterationTypes2 === noIterationTypes) { if (errorNode) { @@ -80788,11 +74799,12 @@ ${lanes.join("\n")} } 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; + const errorOutputContainer = errorNode ? { + errors: void 0 + } : void 0; const iterationTypes2 = getIterationTypesOfIterableWorker(constituent, use, errorNode, errorOutputContainer); if (iterationTypes2 === noIterationTypes) { if (errorNode) { @@ -80815,22 +74827,18 @@ ${lanes.join("\n")} return iterationTypes === noIterationTypes ? void 0 : iterationTypes; } function getAsyncFromSyncIterationTypes(iterationTypes, errorNode) { - if (iterationTypes === noIterationTypes) - return noIterationTypes; - if (iterationTypes === anyIterationTypes) - return anyIterationTypes; - const { yieldType, returnType, nextType } = iterationTypes; - if (errorNode) { - getGlobalAwaitedSymbol( - /*reportErrors*/ - true - ); - } - return createIterationTypes( - getAwaitedType(yieldType, errorNode) || anyType, - getAwaitedType(returnType, errorNode) || anyType, + if (iterationTypes === noIterationTypes) return noIterationTypes; + if (iterationTypes === anyIterationTypes) return anyIterationTypes; + const { + yieldType, + returnType, nextType - ); + } = iterationTypes; + if (errorNode) { + getGlobalAwaitedSymbol( /*reportErrors*/ + true); + } + return createIterationTypes(getAwaitedType(yieldType, errorNode) || anyType, getAwaitedType(returnType, errorNode) || anyType, nextType); } function getIterationTypesOfIterableWorker(type, use, errorNode, errorOutputContainer) { if (isTypeAny(type)) { @@ -80887,64 +74895,42 @@ ${lanes.join("\n")} return getCachedIterationTypes(type, resolver.iterableCacheKey); } function getIterationTypesOfGlobalIterableType(globalType, resolver) { - const globalIterationTypes = getIterationTypesOfIterableCached(globalType, resolver) || getIterationTypesOfIterableSlow( - globalType, - resolver, - /*errorNode*/ - void 0, - /*errorOutputContainer*/ - void 0, - /*noCache*/ - false - ); + const globalIterationTypes = getIterationTypesOfIterableCached(globalType, resolver) || getIterationTypesOfIterableSlow(globalType, resolver, /*errorNode*/ + void 0, /*errorOutputContainer*/ + void 0, /*noCache*/ + false); return globalIterationTypes === noIterationTypes ? defaultIterationTypes : globalIterationTypes; } function getIterationTypesOfIterableFast(type, resolver) { let globalType; - if (isReferenceToType2(type, globalType = resolver.getGlobalIterableType( - /*reportErrors*/ - false - )) || isReferenceToType2(type, globalType = resolver.getGlobalIterableIteratorType( - /*reportErrors*/ - false - ))) { + if (isReferenceToType2(type, globalType = resolver.getGlobalIterableType( /*reportErrors*/ + false)) || isReferenceToType2(type, globalType = resolver.getGlobalIterableIteratorType( /*reportErrors*/ + false))) { const [yieldType] = getTypeArguments(type); - const { returnType, nextType } = getIterationTypesOfGlobalIterableType(globalType, resolver); - return setCachedIterationTypes(type, resolver.iterableCacheKey, createIterationTypes(resolver.resolveIterationType( - yieldType, - /*errorNode*/ - void 0 - ) || yieldType, resolver.resolveIterationType( + const { returnType, - /*errorNode*/ - void 0 - ) || returnType, nextType)); + nextType + } = getIterationTypesOfGlobalIterableType(globalType, resolver); + return setCachedIterationTypes(type, resolver.iterableCacheKey, createIterationTypes(resolver.resolveIterationType(yieldType, /*errorNode*/ + void 0) || yieldType, resolver.resolveIterationType(returnType, /*errorNode*/ + void 0) || returnType, nextType)); } - if (isReferenceToType2(type, resolver.getGlobalGeneratorType( - /*reportErrors*/ - false - ))) { + if (isReferenceToType2(type, resolver.getGlobalGeneratorType( /*reportErrors*/ + false))) { const [yieldType, returnType, nextType] = getTypeArguments(type); - return setCachedIterationTypes(type, resolver.iterableCacheKey, createIterationTypes(resolver.resolveIterationType( - yieldType, - /*errorNode*/ - void 0 - ) || yieldType, resolver.resolveIterationType( - returnType, - /*errorNode*/ - void 0 - ) || returnType, nextType)); + return setCachedIterationTypes(type, resolver.iterableCacheKey, createIterationTypes(resolver.resolveIterationType(yieldType, /*errorNode*/ + void 0) || yieldType, resolver.resolveIterationType(returnType, /*errorNode*/ + void 0) || returnType, nextType)); } } function getPropertyNameForKnownSymbolName(symbolName2) { - const ctorType = getGlobalESSymbolConstructorSymbol( - /*reportErrors*/ - false - ); + const ctorType = getGlobalESSymbolConstructorSymbol( /*reportErrors*/ + false); const uniqueType = ctorType && getTypeOfPropertyOfType(getTypeOfSymbol(ctorType), escapeLeadingUnderscores(symbolName2)); return uniqueType && isTypeUsableAsPropertyName(uniqueType) ? getPropertyNameFromType(uniqueType) : `__@${symbolName2}`; } function getIterationTypesOfIterableSlow(type, resolver, errorNode, errorOutputContainer, noCache) { + var _getIterationTypesOfI; const method = getPropertyOfType(type, getPropertyNameForKnownSymbolName(resolver.iteratorSymbolName)); const methodType = method && !(method.flags & 16777216 /* Optional */) ? getTypeOfSymbol(method) : void 0; if (isTypeAny(methodType)) { @@ -80955,34 +74941,24 @@ ${lanes.join("\n")} return noCache ? noIterationTypes : setCachedIterationTypes(type, resolver.iterableCacheKey, noIterationTypes); } const iteratorType = getIntersectionType(map(signatures, getReturnTypeOfSignature)); - const iterationTypes = getIterationTypesOfIteratorWorker(iteratorType, resolver, errorNode, errorOutputContainer, noCache) ?? noIterationTypes; + const iterationTypes = (_getIterationTypesOfI = getIterationTypesOfIteratorWorker(iteratorType, resolver, errorNode, errorOutputContainer, noCache)) !== null && _getIterationTypesOfI !== void 0 ? _getIterationTypesOfI : noIterationTypes; return noCache ? iterationTypes : setCachedIterationTypes(type, resolver.iterableCacheKey, iterationTypes); } function reportTypeNotIterableError(errorNode, type, allowAsyncIterables) { const message = allowAsyncIterables ? Diagnostics.Type_0_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator : Diagnostics.Type_0_must_have_a_Symbol_iterator_method_that_returns_an_iterator; - const suggestAwait = ( - // for (const x of Promise<...>) or [...Promise<...>] - !!getAwaitedTypeOfPromise(type) || !allowAsyncIterables && isForOfStatement(errorNode.parent) && errorNode.parent.expression === errorNode && getGlobalAsyncIterableType( - /*reportErrors*/ - false - ) !== emptyGenericType && isTypeAssignableTo(type, getGlobalAsyncIterableType( - /*reportErrors*/ - false - )) - ); + const suggestAwait = + // for (const x of Promise<...>) or [...Promise<...>] + !!getAwaitedTypeOfPromise(type) || !allowAsyncIterables && isForOfStatement(errorNode.parent) && errorNode.parent.expression === errorNode && getGlobalAsyncIterableType( /*reportErrors*/ + false) !== emptyGenericType && isTypeAssignableTo(type, getGlobalAsyncIterableType( /*reportErrors*/ + false)); return errorAndMaybeSuggestAwait(errorNode, suggestAwait, message, typeToString(type)); } function getIterationTypesOfIterator(type, resolver, errorNode, errorOutputContainer) { - return getIterationTypesOfIteratorWorker( - type, - resolver, - errorNode, - errorOutputContainer, - /*noCache*/ - false - ); + return getIterationTypesOfIteratorWorker(type, resolver, errorNode, errorOutputContainer, /*noCache*/ + false); } function getIterationTypesOfIteratorWorker(type, resolver, errorNode, errorOutputContainer, noCache) { + var _iterationTypes; if (isTypeAny(type)) { return anyIterationTypes; } @@ -80991,39 +74967,30 @@ ${lanes.join("\n")} iterationTypes = void 0; noCache = true; } - iterationTypes ?? (iterationTypes = getIterationTypesOfIteratorSlow(type, resolver, errorNode, errorOutputContainer, noCache)); + (_iterationTypes = iterationTypes) !== null && _iterationTypes !== void 0 ? _iterationTypes : iterationTypes = getIterationTypesOfIteratorSlow(type, resolver, errorNode, errorOutputContainer, noCache); return iterationTypes === noIterationTypes ? void 0 : iterationTypes; } function getIterationTypesOfIteratorCached(type, resolver) { return getCachedIterationTypes(type, resolver.iteratorCacheKey); } function getIterationTypesOfIteratorFast(type, resolver) { - const globalType = resolver.getGlobalIterableIteratorType( - /*reportErrors*/ - false - ); + const globalType = resolver.getGlobalIterableIteratorType( /*reportErrors*/ + false); if (isReferenceToType2(type, globalType)) { const [yieldType] = getTypeArguments(type); - const globalIterationTypes = getIterationTypesOfIteratorCached(globalType, resolver) || getIterationTypesOfIteratorSlow( - globalType, - resolver, - /*errorNode*/ - void 0, - /*errorOutputContainer*/ - void 0, - /*noCache*/ - false - ); - const { returnType, nextType } = globalIterationTypes === noIterationTypes ? defaultIterationTypes : globalIterationTypes; + const globalIterationTypes = getIterationTypesOfIteratorCached(globalType, resolver) || getIterationTypesOfIteratorSlow(globalType, resolver, /*errorNode*/ + void 0, /*errorOutputContainer*/ + void 0, /*noCache*/ + false); + const { + returnType, + nextType + } = globalIterationTypes === noIterationTypes ? defaultIterationTypes : globalIterationTypes; return setCachedIterationTypes(type, resolver.iteratorCacheKey, createIterationTypes(yieldType, returnType, nextType)); } - if (isReferenceToType2(type, resolver.getGlobalIteratorType( - /*reportErrors*/ - false - )) || isReferenceToType2(type, resolver.getGlobalGeneratorType( - /*reportErrors*/ - false - ))) { + if (isReferenceToType2(type, resolver.getGlobalIteratorType( /*reportErrors*/ + false)) || isReferenceToType2(type, resolver.getGlobalGeneratorType( /*reportErrors*/ + false))) { const [yieldType, returnType, nextType] = getTypeArguments(type); return setCachedIterationTypes(type, resolver.iteratorCacheKey, createIterationTypes(yieldType, returnType, nextType)); } @@ -81035,9 +75002,11 @@ ${lanes.join("\n")} function isYieldIteratorResult(type) { return isIteratorResult(type, 0 /* Yield */); } + function isReturnIteratorResult(type) { return isIteratorResult(type, 1 /* Return */); } + function getIterationTypesOfIteratorResult(type) { if (isTypeAny(type)) { return anyIterationTypes; @@ -81046,31 +75015,19 @@ ${lanes.join("\n")} if (cachedTypes2) { return cachedTypes2; } - if (isReferenceToType2(type, getGlobalIteratorYieldResultType( - /*reportErrors*/ - false - ))) { + if (isReferenceToType2(type, getGlobalIteratorYieldResultType( /*reportErrors*/ + false))) { const yieldType2 = getTypeArguments(type)[0]; - return setCachedIterationTypes(type, "iterationTypesOfIteratorResult", createIterationTypes( - yieldType2, - /*returnType*/ - void 0, - /*nextType*/ - void 0 - )); + return setCachedIterationTypes(type, "iterationTypesOfIteratorResult", createIterationTypes(yieldType2, /*returnType*/ + void 0, /*nextType*/ + void 0)); } - if (isReferenceToType2(type, getGlobalIteratorReturnResultType( - /*reportErrors*/ - false - ))) { + if (isReferenceToType2(type, getGlobalIteratorReturnResultType( /*reportErrors*/ + false))) { const returnType2 = getTypeArguments(type)[0]; - return setCachedIterationTypes(type, "iterationTypesOfIteratorResult", createIterationTypes( - /*yieldType*/ - void 0, - returnType2, - /*nextType*/ - void 0 - )); + return setCachedIterationTypes(type, "iterationTypesOfIteratorResult", createIterationTypes( /*yieldType*/ + void 0, returnType2, /*nextType*/ + void 0)); } const yieldIteratorResult = filterType(type, isYieldIteratorResult); const yieldType = yieldIteratorResult !== neverType ? getTypeOfPropertyOfType(yieldIteratorResult, "value") : void 0; @@ -81079,12 +75036,8 @@ ${lanes.join("\n")} if (!yieldType && !returnType) { return setCachedIterationTypes(type, "iterationTypesOfIteratorResult", noIterationTypes); } - return setCachedIterationTypes(type, "iterationTypesOfIteratorResult", createIterationTypes( - yieldType, - returnType || voidType, - /*nextType*/ - void 0 - )); + return setCachedIterationTypes(type, "iterationTypesOfIteratorResult", createIterationTypes(yieldType, returnType || voidType, /*nextType*/ + void 0)); } function getIterationTypesOfMethod(type, resolver, methodName, errorNode, errorOutputContainer) { var _a, _b, _c, _d; @@ -81101,7 +75054,8 @@ ${lanes.join("\n")} if (errorNode) { const diagnostic = methodName === "next" ? resolver.mustHaveANextMethodDiagnostic : resolver.mustBeAMethodDiagnostic; if (errorOutputContainer) { - errorOutputContainer.errors ?? (errorOutputContainer.errors = []); + var _errorOutputContainer; + (_errorOutputContainer = errorOutputContainer.errors) !== null && _errorOutputContainer !== void 0 ? _errorOutputContainer : errorOutputContainer.errors = []; errorOutputContainer.errors.push(createDiagnosticForNode(errorNode, diagnostic, methodName)); } else { error2(errorNode, diagnostic, methodName); @@ -81110,24 +75064,18 @@ ${lanes.join("\n")} return methodName === "next" ? noIterationTypes : void 0; } if ((methodType == null ? void 0 : methodType.symbol) && methodSignatures.length === 1) { - const globalGeneratorType = resolver.getGlobalGeneratorType( - /*reportErrors*/ - false - ); - const globalIteratorType = resolver.getGlobalIteratorType( - /*reportErrors*/ - false - ); + const globalGeneratorType = resolver.getGlobalGeneratorType( /*reportErrors*/ + false); + const globalIteratorType = resolver.getGlobalIteratorType( /*reportErrors*/ + false); const isGeneratorMethod = ((_b = (_a = globalGeneratorType.symbol) == null ? void 0 : _a.members) == null ? void 0 : _b.get(methodName)) === methodType.symbol; const isIteratorMethod = !isGeneratorMethod && ((_d = (_c = globalIteratorType.symbol) == null ? void 0 : _c.members) == null ? void 0 : _d.get(methodName)) === methodType.symbol; if (isGeneratorMethod || isIteratorMethod) { const globalType = isGeneratorMethod ? globalGeneratorType : globalIteratorType; - const { mapper } = methodType; - return createIterationTypes( - getMappedType(globalType.typeParameters[0], mapper), - getMappedType(globalType.typeParameters[1], mapper), - methodName === "next" ? getMappedType(globalType.typeParameters[2], mapper) : void 0 - ); + const { + mapper + } = methodType; + return createIterationTypes(getMappedType(globalType.typeParameters[0], mapper), getMappedType(globalType.typeParameters[1], mapper), methodName === "next" ? getMappedType(globalType.typeParameters[2], mapper) : void 0); } } let methodParameterTypes; @@ -81156,7 +75104,8 @@ ${lanes.join("\n")} if (iterationTypes === noIterationTypes) { if (errorNode) { if (errorOutputContainer) { - errorOutputContainer.errors ?? (errorOutputContainer.errors = []); + var _errorOutputContainer2; + (_errorOutputContainer2 = errorOutputContainer.errors) !== null && _errorOutputContainer2 !== void 0 ? _errorOutputContainer2 : errorOutputContainer.errors = []; errorOutputContainer.errors.push(createDiagnosticForNode(errorNode, resolver.mustHaveAValueDiagnostic, methodName)); } else { error2(errorNode, resolver.mustHaveAValueDiagnostic, methodName); @@ -81171,11 +75120,7 @@ ${lanes.join("\n")} return createIterationTypes(yieldType, getUnionType(returnTypes), nextType); } function getIterationTypesOfIteratorSlow(type, resolver, errorNode, errorOutputContainer, noCache) { - const iterationTypes = combineIterationTypes([ - getIterationTypesOfMethod(type, resolver, "next", errorNode, errorOutputContainer), - getIterationTypesOfMethod(type, resolver, "return", errorNode, errorOutputContainer), - getIterationTypesOfMethod(type, resolver, "throw", errorNode, errorOutputContainer) - ]); + const iterationTypes = combineIterationTypes([getIterationTypesOfMethod(type, resolver, "next", errorNode, errorOutputContainer), getIterationTypesOfMethod(type, resolver, "return", errorNode, errorOutputContainer), getIterationTypesOfMethod(type, resolver, "throw", errorNode, errorOutputContainer)]); return noCache ? iterationTypes : setCachedIterationTypes(type, resolver.iteratorCacheKey, iterationTypes); } function getIterationTypeOfGeneratorFunctionReturnType(kind, returnType, isAsyncGenerator) { @@ -81191,23 +75136,13 @@ ${lanes.join("\n")} } const use = isAsyncGenerator ? 2 /* AsyncGeneratorReturnType */ : 1 /* GeneratorReturnType */; const resolver = isAsyncGenerator ? asyncIterationTypesResolver : syncIterationTypesResolver; - return getIterationTypesOfIterable( - type, - use, - /*errorNode*/ - void 0 - ) || getIterationTypesOfIterator( - type, - resolver, - /*errorNode*/ - void 0, - /*errorOutputContainer*/ - void 0 - ); + return getIterationTypesOfIterable(type, use, /*errorNode*/ + void 0) || getIterationTypesOfIterator(type, resolver, /*errorNode*/ + void 0, /*errorOutputContainer*/ + void 0); } function checkBreakOrContinueStatement(node) { - if (!checkGrammarStatementInAmbientContext(node)) - checkGrammarBreakOrContinueStatement(node); + if (!checkGrammarStatementInAmbientContext(node)) checkGrammarBreakOrContinueStatement(node); } function unwrapReturnType(returnType, functionFlags) { const isGenerator = !!(functionFlags & 1 /* Generator */); @@ -81225,6 +75160,7 @@ ${lanes.join("\n")} const type = unwrapReturnType(returnType, getFunctionFlags(func)); return !!(type && (maybeTypeOfKind(type, 16384 /* Void */) || type.flags & (1 /* Any */ | 32768 /* Undefined */))); } + function checkReturnStatement(node) { if (checkGrammarStatementInAmbientContext(node)) { return; @@ -81252,14 +75188,10 @@ ${lanes.join("\n")} error2(node, Diagnostics.Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class); } } else if (getReturnTypeFromAnnotation(container)) { - const unwrappedReturnType = unwrapReturnType(returnType, functionFlags) ?? returnType; - const unwrappedExprType = functionFlags & 2 /* Async */ ? checkAwaitedType( - exprType, - /*withAlias*/ - false, - node, - Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member - ) : exprType; + var _unwrapReturnType; + const unwrappedReturnType = (_unwrapReturnType = unwrapReturnType(returnType, functionFlags)) !== null && _unwrapReturnType !== void 0 ? _unwrapReturnType : returnType; + const unwrappedExprType = functionFlags & 2 /* Async */ ? checkAwaitedType(exprType, /*withAlias*/ + false, node, Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member) : exprType; if (unwrappedReturnType) { checkTypeAssignableToAndOptionallyElaborate(unwrappedExprType, unwrappedReturnType, node, node.expression); } @@ -81287,7 +75219,7 @@ ${lanes.join("\n")} let firstDefaultClause; let hasDuplicateDefaultClause = false; const expressionType = checkExpression(node.expression); - forEach(node.caseBlock.clauses, (clause) => { + forEach(node.caseBlock.clauses, clause => { if (clause.kind === 297 /* DefaultClause */ && !hasDuplicateDefaultClause) { if (firstDefaultClause === void 0) { firstDefaultClause = clause; @@ -81307,13 +75239,8 @@ ${lanes.join("\n")} return () => { const caseType = checkExpression(clause2.expression); if (!isTypeEqualityComparableTo(expressionType, caseType)) { - checkTypeComparableTo( - caseType, - expressionType, - clause2.expression, - /*headMessage*/ - void 0 - ); + checkTypeComparableTo(caseType, expressionType, clause2.expression, /*headMessage*/ + void 0); } }; } @@ -81324,7 +75251,7 @@ ${lanes.join("\n")} } function checkLabeledStatement(node) { if (!checkGrammarStatementInAmbientContext(node)) { - findAncestor(node.parent, (current) => { + findAncestor(node.parent, current => { if (isFunctionLike(current)) { return "quit"; } @@ -81366,7 +75293,7 @@ ${lanes.join("\n")} } else { const blockLocals = catchClause.block.locals; if (blockLocals) { - forEachKey(catchClause.locals, (caughtName) => { + forEachKey(catchClause.locals, caughtName => { const blockLocal = blockLocals.get(caughtName); if ((blockLocal == null ? void 0 : blockLocal.valueDeclaration) && (blockLocal.flags & 2 /* BlockScopedVariable */) !== 0) { grammarErrorOnNode(blockLocal.valueDeclaration, Diagnostics.Cannot_redeclare_identifier_0_in_catch_clause, unescapeLeadingUnderscores(caughtName)); @@ -81388,12 +75315,8 @@ ${lanes.join("\n")} } for (const prop of getPropertiesOfObjectType(type)) { if (!(isStaticIndex && prop.flags & 4194304 /* Prototype */)) { - checkIndexConstraintForProperty(type, prop, getLiteralTypeFromProperty( - prop, - 8576 /* StringOrNumberLiteralOrUnique */, - /*includeNonPublic*/ - true - ), getNonMissingTypeOfSymbol(prop)); + checkIndexConstraintForProperty(type, prop, getLiteralTypeFromProperty(prop, 8576 /* StringOrNumberLiteralOrUnique */, /*includeNonPublic*/ + true), getNonMissingTypeOfSymbol(prop)); } } const typeDeclaration = symbol.valueDeclaration; @@ -81423,7 +75346,7 @@ ${lanes.join("\n")} const localPropDeclaration = getParentOfSymbol(prop) === type.symbol ? declaration : void 0; for (const info of indexInfos) { const localIndexDeclaration = info.declaration && getParentOfSymbol(getSymbolOfDeclaration(info.declaration)) === type.symbol ? info.declaration : void 0; - const errorNode = localPropDeclaration || localIndexDeclaration || (interfaceDeclaration && !some(getBaseTypes(type), (base) => !!getPropertyOfObjectType(base, prop.escapedName) && !!getIndexTypeOfType(base, info.keyType)) ? interfaceDeclaration : void 0); + const errorNode = localPropDeclaration || localIndexDeclaration || (interfaceDeclaration && !some(getBaseTypes(type), base => !!getPropertyOfObjectType(base, prop.escapedName) && !!getIndexTypeOfType(base, info.keyType)) ? interfaceDeclaration : void 0); if (errorNode && !isTypeAssignableTo(propType, info.type)) { const diagnostic = createError(errorNode, Diagnostics.Property_0_of_type_1_is_not_assignable_to_2_index_type_3, symbolToString(prop), typeToString(propType), typeToString(info.keyType), typeToString(info.type)); if (propDeclaration && errorNode !== propDeclaration) { @@ -81439,10 +75362,9 @@ ${lanes.join("\n")} 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); + 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)) { error2(errorNode, Diagnostics._0_index_type_1_is_not_assignable_to_2_index_type_3, typeToString(checkInfo.keyType), typeToString(checkInfo.type), typeToString(info.keyType), typeToString(info.type)); } @@ -81470,12 +75392,13 @@ ${lanes.join("\n")} } 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(); - forEach(node.parameters, ({ name }, index) => { + const parameters = /* @__PURE__ */new Set(); + const excludedParameters = /* @__PURE__ */new Set(); + forEach(node.parameters, ({ + name + }, index) => { if (isIdentifier(name)) { parameters.add(name.escapedText); } @@ -81491,7 +75414,10 @@ ${lanes.join("\n")} error2(lastJSDocParam.name, Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_had_an_array_type, idText(lastJSDocParam.name)); } } else { - forEach(jsdocParameters, ({ name, isNameFirst }, index) => { + forEach(jsdocParameters, ({ + name, + isNameFirst + }, index) => { if (excludedParameters.has(index) || isIdentifier(name) && parameters.has(name.escapedText)) { return; } @@ -81599,22 +75525,16 @@ ${lanes.join("\n")} return true; } function getFirstTransformableStaticClassElement(node) { - const willTransformStaticElementsOfDecoratedClass = !legacyDecorators && languageVersion < 99 /* ESNext */ && classOrConstructorParameterIsDecorated( - /*useLegacyDecorators*/ - false, - node - ); + const willTransformStaticElementsOfDecoratedClass = !legacyDecorators && languageVersion < 99 /* ESNext */ && classOrConstructorParameterIsDecorated( /*useLegacyDecorators*/ + false, node); const willTransformPrivateElementsOrClassStaticBlocks = languageVersion <= 9 /* ES2022 */; const willTransformInitializers = !emitStandardClassFields; if (willTransformStaticElementsOfDecoratedClass || willTransformPrivateElementsOrClassStaticBlocks) { for (const member of node.members) { - if (willTransformStaticElementsOfDecoratedClass && classElementOrClassElementParameterIsDecorated( - /*useLegacyDecorators*/ - false, - member, - node - )) { - return firstOrUndefined(getDecorators(node)) ?? node; + if (willTransformStaticElementsOfDecoratedClass && classElementOrClassElementParameterIsDecorated( /*useLegacyDecorators*/ + false, member, node)) { + var _firstOrUndefined; + return (_firstOrUndefined = firstOrUndefined(getDecorators(node))) !== null && _firstOrUndefined !== void 0 ? _firstOrUndefined : node; } else if (willTransformPrivateElementsOrClassStaticBlocks) { if (isClassStaticBlockDeclaration(member)) { return member; @@ -81628,19 +75548,15 @@ ${lanes.join("\n")} } } 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 /* ESNext */; let location; - if (willTransformESDecorators && classOrConstructorParameterIsDecorated( - /*useLegacyDecorators*/ - false, - node - )) { - location = firstOrUndefined(getDecorators(node)) ?? node; + if (willTransformESDecorators && classOrConstructorParameterIsDecorated( /*useLegacyDecorators*/ + false, node)) { + var _firstOrUndefined2; + location = (_firstOrUndefined2 = firstOrUndefined(getDecorators(node))) !== null && _firstOrUndefined2 !== void 0 ? _firstOrUndefined2 : node; } else { location = getFirstTransformableStaticClassElement(node); } @@ -81651,6 +75567,7 @@ ${lanes.join("\n")} } } } + function checkClassExpression(node) { checkClassLikeDeclaration(node); checkNodeDeferred(node); @@ -81663,7 +75580,7 @@ ${lanes.join("\n")} } function checkClassDeclaration(node) { const firstDecorator = find(node.modifiers, isDecorator); - if (legacyDecorators && firstDecorator && some(node.members, (p) => hasStaticModifier(p) && isPrivateIdentifierClassElementDeclaration(p))) { + if (legacyDecorators && firstDecorator && some(node.members, p => hasStaticModifier(p) && isPrivateIdentifierClassElementDeclaration(p))) { grammarErrorOnNode(firstDecorator, Diagnostics.Class_decorators_can_t_be_used_with_static_private_identifier_Consider_removing_the_experimental_decorator); } if (!node.name && !hasSyntacticModifier(node, 2048 /* Default */)) { @@ -81696,6 +75613,7 @@ ${lanes.join("\n")} if (languageVersion < 2 /* ES2015 */) { checkExternalEmitHelpers(baseTypeNode.parent, 1 /* Extends */); } + const extendsNode = getClassExtendsHeritageElement(node); if (extendsNode && extendsNode !== baseTypeNode) { checkExpression(extendsNode.expression); @@ -81717,12 +75635,8 @@ ${lanes.join("\n")} } } const baseWithThis = getTypeWithThisArgument(baseType, type.thisType); - if (!checkTypeAssignableTo( - typeWithThis, - baseWithThis, - /*errorNode*/ - void 0 - )) { + if (!checkTypeAssignableTo(typeWithThis, baseWithThis, /*errorNode*/ + void 0)) { issueMemberSpecificError(node, typeWithThis, baseWithThis, Diagnostics.Class_0_incorrectly_extends_base_class_1); } else { checkTypeAssignableTo(staticType, getTypeWithoutSignatures(staticBaseType), node.name || node, Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1); @@ -81732,14 +75646,14 @@ ${lanes.join("\n")} error2(node.name || node, Diagnostics.A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any); } else { const constructSignatures = getSignaturesOfType(baseConstructorType, 1 /* Construct */); - if (constructSignatures.some((signature) => signature.flags & 4 /* Abstract */) && !hasSyntacticModifier(node, 64 /* Abstract */)) { + if (constructSignatures.some(signature => signature.flags & 4 /* Abstract */) && !hasSyntacticModifier(node, 64 /* Abstract */)) { error2(node.name || node, Diagnostics.A_mixin_class_that_extends_from_a_type_variable_containing_an_abstract_construct_signature_must_also_be_declared_abstract); } } } if (!(staticBaseType.symbol && staticBaseType.symbol.flags & 32 /* Class */) && !(baseConstructorType.flags & 8650752 /* TypeVariable */)) { const constructors = getInstantiatedConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments, baseTypeNode); - if (forEach(constructors, (sig) => !isJSConstructor(sig.declaration) && !isTypeIdenticalTo(getReturnTypeOfSignature(sig), baseType))) { + if (forEach(constructors, sig => !isJSConstructor(sig.declaration) && !isTypeIdenticalTo(getReturnTypeOfSignature(sig), baseType))) { error2(baseTypeNode.expression, Diagnostics.Base_constructors_must_all_have_the_same_return_type); } } @@ -81760,12 +75674,8 @@ ${lanes.join("\n")} } addLazyDiagnostic(() => { checkIndexConstraints(type, symbol); - checkIndexConstraints( - staticType, - symbol, - /*isStaticIndex*/ - true - ); + checkIndexConstraints(staticType, symbol, /*isStaticIndex*/ + true); checkTypeForDuplicateIndexSignatures(node); checkPropertyInitialization(node); }); @@ -81776,12 +75686,8 @@ ${lanes.join("\n")} if (isValidBaseType(t)) { const genericDiag = t.symbol && t.symbol.flags & 32 /* Class */ ? Diagnostics.Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclass : Diagnostics.Class_0_incorrectly_implements_interface_1; const baseWithThis = getTypeWithThisArgument(t, type.thisType); - if (!checkTypeAssignableTo( - typeWithThis, - baseWithThis, - /*errorNode*/ - void 0 - )) { + if (!checkTypeAssignableTo(typeWithThis, baseWithThis, /*errorNode*/ + void 0)) { issueMemberSpecificError(node, typeWithThis, baseWithThis, genericDiag); } } else { @@ -81801,33 +75707,15 @@ ${lanes.join("\n")} continue; } if (isConstructorDeclaration(member)) { - forEach(member.parameters, (param) => { + forEach(member.parameters, param => { if (isParameterPropertyDeclaration(param, member)) { - checkExistingMemberForOverrideModifier( - node, - staticType, - baseStaticType, - baseWithThis, - type, - typeWithThis, - param, - /*memberIsParameterProperty*/ - true - ); + checkExistingMemberForOverrideModifier(node, staticType, baseStaticType, baseWithThis, type, typeWithThis, param, /*memberIsParameterProperty*/ + true); } }); } - checkExistingMemberForOverrideModifier( - node, - staticType, - baseStaticType, - baseWithThis, - type, - typeWithThis, - member, - /*memberIsParameterProperty*/ - false - ); + checkExistingMemberForOverrideModifier(node, staticType, baseStaticType, baseWithThis, type, typeWithThis, member, /*memberIsParameterProperty*/ + false); } } function checkExistingMemberForOverrideModifier(node, staticType, baseStaticType, baseWithThis, type, typeWithThis, member, memberIsParameterProperty, reportErrors2 = true) { @@ -81835,20 +75723,8 @@ ${lanes.join("\n")} if (!declaredProp) { return 0 /* Ok */; } - return checkMemberForOverrideModifier( - node, - staticType, - baseStaticType, - baseWithThis, - type, - typeWithThis, - hasOverrideModifier(member), - hasAbstractModifier(member), - isStatic(member), - memberIsParameterProperty, - symbolName(declaredProp), - reportErrors2 ? member : void 0 - ); + + return checkMemberForOverrideModifier(node, staticType, baseStaticType, baseWithThis, type, typeWithThis, hasOverrideModifier(member), hasAbstractModifier(member), isStatic(member), memberIsParameterProperty, symbolName(declaredProp), reportErrors2 ? member : void 0); } function checkMemberForOverrideModifier(node, staticType, baseStaticType, baseWithThis, type, typeWithThis, memberHasOverrideModifier, memberHasAbstractModifier, memberIsStatic, memberIsParameterProperty, memberName, errorNode) { const isJs = isInJSFile(node); @@ -81863,16 +75739,7 @@ ${lanes.join("\n")} if (prop && !baseProp && memberHasOverrideModifier) { if (errorNode) { const suggestion = getSuggestedSymbolForNonexistentClassMember(memberName, baseType); - suggestion ? error2( - errorNode, - isJs ? Diagnostics.This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_it_is_not_declared_in_the_base_class_0_Did_you_mean_1 : Diagnostics.This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0_Did_you_mean_1, - baseClassName, - symbolToString(suggestion) - ) : error2( - errorNode, - isJs ? Diagnostics.This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_it_is_not_declared_in_the_base_class_0 : Diagnostics.This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0, - baseClassName - ); + suggestion ? error2(errorNode, isJs ? Diagnostics.This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_it_is_not_declared_in_the_base_class_0_Did_you_mean_1 : Diagnostics.This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0_Did_you_mean_1, baseClassName, symbolToString(suggestion)) : error2(errorNode, isJs ? Diagnostics.This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_it_is_not_declared_in_the_base_class_0 : Diagnostics.This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0, baseClassName); } return 2 /* HasInvalidOverride */; } else if (prop && (baseProp == null ? void 0 : baseProp.declarations) && compilerOptions.noImplicitOverride && !nodeInAmbientContext) { @@ -81880,6 +75747,7 @@ ${lanes.join("\n")} if (memberHasOverrideModifier) { return 0 /* Ok */; } + if (!baseHasAbstract) { if (errorNode) { const diag2 = memberIsParameterProperty ? isJs ? Diagnostics.This_parameter_property_must_have_a_JSDoc_comment_with_an_override_tag_because_it_overrides_a_member_in_the_base_class_0 : Diagnostics.This_parameter_property_must_have_an_override_modifier_because_it_overrides_a_member_in_base_class_0 : isJs ? Diagnostics.This_member_must_have_a_JSDoc_comment_with_an_override_tag_because_it_overrides_a_member_in_the_base_class_0 : Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_a_member_in_the_base_class_0; @@ -81896,16 +75764,14 @@ ${lanes.join("\n")} } else if (memberHasOverrideModifier) { if (errorNode) { const className = typeToString(type); - error2( - errorNode, - isJs ? Diagnostics.This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_its_containing_class_0_does_not_extend_another_class : Diagnostics.This_member_cannot_have_an_override_modifier_because_its_containing_class_0_does_not_extend_another_class, - className - ); + error2(errorNode, isJs ? Diagnostics.This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_its_containing_class_0_does_not_extend_another_class : Diagnostics.This_member_cannot_have_an_override_modifier_because_its_containing_class_0_does_not_extend_another_class, className); } return 2 /* HasInvalidOverride */; } + return 0 /* Ok */; } + function issueMemberSpecificError(node, typeWithThis, baseWithThis, broadDiag) { let issuedMemberError = false; for (const member of node.members) { @@ -81917,22 +75783,10 @@ ${lanes.join("\n")} const prop = getPropertyOfType(typeWithThis, declaredProp.escapedName); const baseProp = getPropertyOfType(baseWithThis, declaredProp.escapedName); if (prop && baseProp) { - const rootChain = () => chainDiagnosticMessages( - /*details*/ - void 0, - Diagnostics.Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2, - symbolToString(declaredProp), - typeToString(typeWithThis), - typeToString(baseWithThis) - ); - if (!checkTypeAssignableTo( - getTypeOfSymbol(prop), - getTypeOfSymbol(baseProp), - member.name || member, - /*headMessage*/ - void 0, - rootChain - )) { + const rootChain = () => chainDiagnosticMessages( /*details*/ + void 0, Diagnostics.Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2, symbolToString(declaredProp), typeToString(typeWithThis), typeToString(baseWithThis)); + if (!checkTypeAssignableTo(getTypeOfSymbol(prop), getTypeOfSymbol(baseProp), member.name || member, /*headMessage*/ + void 0, rootChain)) { issuedMemberError = true; } } @@ -81958,6 +75812,7 @@ ${lanes.join("\n")} if (!member.name) { return 0 /* Ok */; } + const classSymbol = getSymbolOfDeclaration(node); const type = getDeclaredTypeOfSymbol(classSymbol); const typeWithThis = getTypeWithThisArgument(type); @@ -81967,131 +75822,98 @@ ${lanes.join("\n")} const baseWithThis = (baseTypes == null ? void 0 : baseTypes.length) ? getTypeWithThisArgument(first(baseTypes), type.thisType) : void 0; const baseStaticType = getBaseConstructorTypeOfClass(type); const memberHasOverrideModifier = member.parent ? hasOverrideModifier(member) : hasSyntacticModifier(member, 16 /* Override */); - return checkMemberForOverrideModifier( - node, - staticType, - baseStaticType, - baseWithThis, - type, - typeWithThis, - memberHasOverrideModifier, - hasAbstractModifier(member), - isStatic(member), - /*memberIsParameterProperty*/ - false, - symbolName(memberSymbol) - ); + return checkMemberForOverrideModifier(node, staticType, baseStaticType, baseWithThis, type, typeWithThis, memberHasOverrideModifier, hasAbstractModifier(member), isStatic(member), /*memberIsParameterProperty*/ + false, symbolName(memberSymbol)); } function getTargetSymbol(s) { return getCheckFlags(s) & 1 /* Instantiated */ ? s.links.target : s; } function getClassOrInterfaceDeclarationsOfSymbol(symbol) { - return filter(symbol.declarations, (d) => d.kind === 263 /* ClassDeclaration */ || d.kind === 264 /* InterfaceDeclaration */); + return filter(symbol.declarations, d => d.kind === 263 /* ClassDeclaration */ || d.kind === 264 /* InterfaceDeclaration */); } + function checkKindsOfPropertyMemberOverrides(type, baseType) { var _a, _b, _c, _d; const baseProperties = getPropertiesOfType(baseType); let inheritedAbstractMemberNotImplementedError; - basePropertyCheck: - for (const baseProperty of baseProperties) { - const base = getTargetSymbol(baseProperty); - if (base.flags & 4194304 /* Prototype */) { - continue; - } - 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; - } - } - if (!inheritedAbstractMemberNotImplementedError) { - inheritedAbstractMemberNotImplementedError = error2( - derivedClassDecl, - Diagnostics.Non_abstract_class_0_does_not_implement_all_abstract_members_of_1, - typeToString(type), - typeToString(baseType) - ); - } - if (derivedClassDecl.kind === 231 /* ClassExpression */) { - addRelatedInfo( - inheritedAbstractMemberNotImplementedError, - createDiagnosticForNode( - baseProperty.valueDeclaration ?? (baseProperty.declarations && first(baseProperty.declarations)) ?? derivedClassDecl, - Diagnostics.Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1, - symbolToString(baseProperty), - typeToString(baseType) - ) - ); - } else { - addRelatedInfo( - inheritedAbstractMemberNotImplementedError, - createDiagnosticForNode( - baseProperty.valueDeclaration ?? (baseProperty.declarations && first(baseProperty.declarations)) ?? derivedClassDecl, - Diagnostics.Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2, - typeToString(type), - symbolToString(baseProperty), - typeToString(baseType) - ) - ); - } - } - } else { - const derivedDeclarationFlags = getDeclarationModifierFlagsFromSymbol(derived); - if (baseDeclarationFlags & 2 /* Private */ || derivedDeclarationFlags & 2 /* Private */) { - continue; - } - let errorMessage; - const basePropertyFlags = base.flags & 98308 /* PropertyOrAccessor */; - const derivedPropertyFlags = derived.flags & 98308 /* PropertyOrAccessor */; - if (basePropertyFlags && derivedPropertyFlags) { - if ((getCheckFlags(base) & 6 /* Synthetic */ ? (_a = base.declarations) == null ? void 0 : _a.some((d) => isPropertyAbstractOrInterface(d, baseDeclarationFlags)) : (_b = base.declarations) == null ? void 0 : _b.every((d) => isPropertyAbstractOrInterface(d, baseDeclarationFlags))) || getCheckFlags(base) & 262144 /* Mapped */ || derived.valueDeclaration && isBinaryExpression(derived.valueDeclaration)) { - continue; - } - const overriddenInstanceProperty = basePropertyFlags !== 4 /* Property */ && derivedPropertyFlags === 4 /* Property */; - const overriddenInstanceAccessor = basePropertyFlags === 4 /* Property */ && derivedPropertyFlags !== 4 /* Property */; - if (overriddenInstanceProperty || overriddenInstanceAccessor) { - const errorMessage2 = overriddenInstanceProperty ? Diagnostics._0_is_defined_as_an_accessor_in_class_1_but_is_overridden_here_in_2_as_an_instance_property : Diagnostics._0_is_defined_as_a_property_in_class_1_but_is_overridden_here_in_2_as_an_accessor; - error2(getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage2, symbolToString(base), typeToString(baseType), typeToString(type)); - } else if (useDefineForClassFields) { - const uninitialized = (_c = derived.declarations) == null ? void 0 : _c.find((d) => d.kind === 172 /* PropertyDeclaration */ && !d.initializer); - if (uninitialized && !(derived.flags & 33554432 /* Transient */) && !(baseDeclarationFlags & 64 /* Abstract */) && !(derivedDeclarationFlags & 64 /* Abstract */) && !((_d = derived.declarations) == null ? void 0 : _d.some((d) => !!(d.flags & 33554432 /* Ambient */)))) { - const constructor = findConstructorDeclaration(getClassLikeDeclarationOfSymbol(type.symbol)); - const propName = uninitialized.name; - if (uninitialized.exclamationToken || !constructor || !isIdentifier(propName) || !strictNullChecks || !isPropertyInitializedInConstructor(propName, type, constructor)) { - const errorMessage2 = Diagnostics.Property_0_will_overwrite_the_base_property_in_1_If_this_is_intentional_add_an_initializer_Otherwise_add_a_declare_modifier_or_remove_the_redundant_declaration; - 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 { - 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; - } - error2(getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage, typeToString(baseType), symbolToString(base), typeToString(type)); - } + 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; + } + } + if (!inheritedAbstractMemberNotImplementedError) { + inheritedAbstractMemberNotImplementedError = error2(derivedClassDecl, Diagnostics.Non_abstract_class_0_does_not_implement_all_abstract_members_of_1, typeToString(type), typeToString(baseType)); + } + if (derivedClassDecl.kind === 231 /* ClassExpression */) { + var _ref26, _baseProperty$valueDe; + addRelatedInfo(inheritedAbstractMemberNotImplementedError, createDiagnosticForNode((_ref26 = (_baseProperty$valueDe = baseProperty.valueDeclaration) !== null && _baseProperty$valueDe !== void 0 ? _baseProperty$valueDe : baseProperty.declarations && first(baseProperty.declarations)) !== null && _ref26 !== void 0 ? _ref26 : derivedClassDecl, Diagnostics.Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1, symbolToString(baseProperty), typeToString(baseType))); + } else { + var _ref27, _baseProperty$valueDe2; + addRelatedInfo(inheritedAbstractMemberNotImplementedError, createDiagnosticForNode((_ref27 = (_baseProperty$valueDe2 = baseProperty.valueDeclaration) !== null && _baseProperty$valueDe2 !== void 0 ? _baseProperty$valueDe2 : baseProperty.declarations && first(baseProperty.declarations)) !== null && _ref27 !== void 0 ? _ref27 : derivedClassDecl, Diagnostics.Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2, typeToString(type), symbolToString(baseProperty), typeToString(baseType))); + } + } + } else { + const derivedDeclarationFlags = getDeclarationModifierFlagsFromSymbol(derived); + if (baseDeclarationFlags & 2 /* Private */ || derivedDeclarationFlags & 2 /* Private */) { + continue; + } + let errorMessage; + const basePropertyFlags = base.flags & 98308 /* PropertyOrAccessor */; + const derivedPropertyFlags = derived.flags & 98308 /* PropertyOrAccessor */; + if (basePropertyFlags && derivedPropertyFlags) { + if ((getCheckFlags(base) & 6 /* Synthetic */ ? (_a = base.declarations) == null ? void 0 : _a.some(d => isPropertyAbstractOrInterface(d, baseDeclarationFlags)) : (_b = base.declarations) == null ? void 0 : _b.every(d => isPropertyAbstractOrInterface(d, baseDeclarationFlags))) || getCheckFlags(base) & 262144 /* Mapped */ || derived.valueDeclaration && isBinaryExpression(derived.valueDeclaration)) { + continue; + } + const overriddenInstanceProperty = basePropertyFlags !== 4 /* Property */ && derivedPropertyFlags === 4 /* Property */; + const overriddenInstanceAccessor = basePropertyFlags === 4 /* Property */ && derivedPropertyFlags !== 4 /* Property */; + if (overriddenInstanceProperty || overriddenInstanceAccessor) { + const errorMessage2 = overriddenInstanceProperty ? Diagnostics._0_is_defined_as_an_accessor_in_class_1_but_is_overridden_here_in_2_as_an_instance_property : Diagnostics._0_is_defined_as_a_property_in_class_1_but_is_overridden_here_in_2_as_an_accessor; + error2(getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage2, symbolToString(base), typeToString(baseType), typeToString(type)); + } else if (useDefineForClassFields) { + const uninitialized = (_c = derived.declarations) == null ? void 0 : _c.find(d => d.kind === 172 /* PropertyDeclaration */ && !d.initializer); + if (uninitialized && !(derived.flags & 33554432 /* Transient */) && !(baseDeclarationFlags & 64 /* Abstract */) && !(derivedDeclarationFlags & 64 /* Abstract */) && !((_d = derived.declarations) == null ? void 0 : _d.some(d => !!(d.flags & 33554432 /* Ambient */)))) { + const constructor = findConstructorDeclaration(getClassLikeDeclarationOfSymbol(type.symbol)); + const propName = uninitialized.name; + if (uninitialized.exclamationToken || !constructor || !isIdentifier(propName) || !strictNullChecks || !isPropertyInitializedInConstructor(propName, type, constructor)) { + const errorMessage2 = Diagnostics.Property_0_will_overwrite_the_base_property_in_1_If_this_is_intentional_add_an_initializer_Otherwise_add_a_declare_modifier_or_remove_the_redundant_declaration; + 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 { + 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; + } + error2(getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage, typeToString(baseType), symbolToString(base), typeToString(type)); + } + } } function isPropertyAbstractOrInterface(declaration, baseDeclarationFlags) { return baseDeclarationFlags & 64 /* Abstract */ && (!isPropertyDeclaration(declaration) || !declaration.initializer) || isInterfaceDeclaration(declaration.parent); @@ -82100,8 +75922,8 @@ ${lanes.join("\n")} if (!length(baseTypes)) { return properties; } - const seen = /* @__PURE__ */ new Map(); - forEach(properties, (p) => { + const seen = /* @__PURE__ */new Map(); + forEach(properties, p => { seen.set(p.escapedName, p); }); for (const base of baseTypes) { @@ -82120,9 +75942,12 @@ ${lanes.join("\n")} if (baseTypes.length < 2) { return true; } - const seen = /* @__PURE__ */ new Map(); - forEach(resolveDeclaredMembers(type).declaredProperties, (p) => { - seen.set(p.escapedName, { prop: p, containingType: type }); + const seen = /* @__PURE__ */new Map(); + forEach(resolveDeclaredMembers(type).declaredProperties, p => { + seen.set(p.escapedName, { + prop: p, + containingType: type + }); }); let ok = true; for (const base of baseTypes) { @@ -82130,21 +75955,18 @@ ${lanes.join("\n")} for (const prop of properties) { const existing = seen.get(prop.escapedName); if (!existing) { - seen.set(prop.escapedName, { prop, containingType: base }); + seen.set(prop.escapedName, { + prop, + containingType: base + }); } else { const isInheritedProperty = existing.containingType !== type; if (isInheritedProperty && !isPropertyIdenticalTo(existing.prop, prop)) { ok = false; const typeName1 = typeToString(existing.containingType); const typeName2 = typeToString(base); - let errorInfo = chainDiagnosticMessages( - /*details*/ - void 0, - Diagnostics.Named_property_0_of_types_1_and_2_are_not_identical, - symbolToString(prop), - typeName1, - typeName2 - ); + let errorInfo = chainDiagnosticMessages( /*details*/ + void 0, Diagnostics.Named_property_0_of_types_1_and_2_are_not_identical, symbolToString(prop), typeName1, typeName2); errorInfo = chainDiagnosticMessages(errorInfo, Diagnostics.Interface_0_cannot_simultaneously_extend_types_1_and_2, typeToString(type), typeName1, typeName2); diagnostics.add(createDiagnosticForNodeFromMessageChain(getSourceFileOfNode(typeNode), typeNode, errorInfo)); } @@ -82202,8 +76024,7 @@ ${lanes.join("\n")} 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); @@ -82223,7 +76044,7 @@ ${lanes.join("\n")} } checkObjectTypeForDuplicateDeclarations(node); }); - forEach(getInterfaceBaseTypeNodes(node), (heritageElement) => { + forEach(getInterfaceBaseTypeNodes(node), heritageElement => { if (!isEntityNameExpression(heritageElement.expression) || isOptionalChain(heritageElement.expression)) { error2(heritageElement.expression, Diagnostics.An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments); } @@ -82288,10 +76109,7 @@ ${lanes.join("\n")} const value = evaluate(initializer, member); if (value !== void 0) { if (isConstEnum && typeof value === "number" && !isFinite(value)) { - error2( - initializer, - isNaN(value) ? Diagnostics.const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN : Diagnostics.const_enum_member_initializer_was_evaluated_to_a_non_finite_value - ); + error2(initializer, isNaN(value) ? Diagnostics.const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN : Diagnostics.const_enum_member_initializer_was_evaluated_to_a_non_finite_value); } } else if (isConstEnum) { error2(initializer, Diagnostics.const_enum_member_initializers_must_be_constant_expressions); @@ -82361,30 +76179,19 @@ ${lanes.join("\n")} return +expr.text; case 217 /* ParenthesizedExpression */: return evaluate(expr.expression, location); - case 80 /* Identifier */: { - const identifier = expr; - if (isInfinityOrNaNString(identifier.escapedText) && resolveEntityName( - identifier, - 111551 /* Value */, - /*ignoreErrors*/ - true - ) === getGlobalSymbol( - identifier.escapedText, - 111551 /* Value */, - /*diagnostic*/ - void 0 - )) { - return +identifier.escapedText; + case 80 /* Identifier */: + { + const identifier = expr; + if (isInfinityOrNaNString(identifier.escapedText) && resolveEntityName(identifier, 111551 /* Value */, /*ignoreErrors*/ + true) === getGlobalSymbol(identifier.escapedText, 111551 /* Value */, /*diagnostic*/ + void 0)) { + return +identifier.escapedText; + } } - } case 211 /* PropertyAccessExpression */: if (isEntityNameExpression(expr)) { - const symbol = resolveEntityName( - expr, - 111551 /* Value */, - /*ignoreErrors*/ - true - ); + const symbol = resolveEntityName(expr, 111551 /* Value */, /*ignoreErrors*/ + true); if (symbol) { if (symbol.flags & 8 /* EnumMember */) { return location ? evaluateEnumMember(expr, symbol, location) : getEnumMemberValue(symbol.valueDeclaration); @@ -82401,12 +76208,8 @@ ${lanes.join("\n")} case 212 /* ElementAccessExpression */: const root = expr.expression; if (isEntityNameExpression(root) && isStringLiteralLike(expr.argumentExpression)) { - const rootSymbol = resolveEntityName( - root, - 111551 /* Value */, - /*ignoreErrors*/ - true - ); + const rootSymbol = resolveEntityName(root, 111551 /* Value */, /*ignoreErrors*/ + true); if (rootSymbol && rootSymbol.flags & 384 /* Enum */) { const name = escapeLeadingUnderscores(expr.argumentExpression.text); const member = rootSymbol.exports.get(name); @@ -82457,14 +76260,14 @@ ${lanes.join("\n")} if (node === firstDeclaration) { if (enumSymbol.declarations && enumSymbol.declarations.length > 1) { const enumIsConst = isEnumConst(node); - forEach(enumSymbol.declarations, (decl) => { + forEach(enumSymbol.declarations, decl => { if (isEnumDeclaration(decl) && isEnumConst(decl) !== enumIsConst) { error2(getNameOfDeclaration(decl), Diagnostics.Enum_declarations_must_all_be_const_or_non_const); } }); } let seenEnumMissingInitialInitializer = false; - forEach(enumSymbol.declarations, (declaration) => { + forEach(enumSymbol.declarations, declaration => { if (declaration.kind !== 266 /* EnumDeclaration */) { return false; } @@ -82561,8 +76364,9 @@ ${lanes.join("\n")} getNodeLinks(node).flags |= 2048 /* LexicalModuleMergesWithClass */; } } + if (compilerOptions.verbatimModuleSyntax && node.parent.kind === 312 /* SourceFile */ && (moduleKind === 1 /* CommonJS */ || node.parent.impliedNodeFormat === 1 /* CommonJS */)) { - const exportModifier = (_b = node.modifiers) == null ? void 0 : _b.find((m) => m.kind === 95 /* ExportKeyword */); + const exportModifier = (_b = node.modifiers) == null ? void 0 : _b.find(m => m.kind === 95 /* ExportKeyword */); if (exportModifier) { error2(exportModifier, Diagnostics.A_top_level_export_modifier_cannot_be_used_on_value_declarations_in_a_CommonJS_module_when_verbatimModuleSyntax_is_enabled); } @@ -82658,10 +76462,7 @@ ${lanes.join("\n")} } const inAmbientExternalModule = node.parent.kind === 268 /* ModuleBlock */ && isAmbientModule(node.parent.parent); if (node.parent.kind !== 312 /* SourceFile */ && !inAmbientExternalModule) { - error2( - moduleName, - node.kind === 278 /* ExportDeclaration */ ? Diagnostics.Export_declarations_are_not_permitted_in_a_namespace : Diagnostics.Import_declarations_in_a_namespace_cannot_reference_a_module - ); + error2(moduleName, node.kind === 278 /* ExportDeclaration */ ? Diagnostics.Export_declarations_are_not_permitted_in_a_namespace : Diagnostics.Import_declarations_in_a_namespace_cannot_reference_a_module); return false; } if (inAmbientExternalModule && isExternalModuleNameRelative(moduleName.text)) { @@ -82698,27 +76499,16 @@ ${lanes.join("\n")} if (alreadyExportedSymbol === target) { const exportingDeclaration = (_c = alreadyExportedSymbol.declarations) == null ? void 0 : _c.find(isJSDocNode); if (exportingDeclaration) { - addRelatedInfo( - diag2, - createDiagnosticForNode( - exportingDeclaration, - Diagnostics._0_is_automatically_exported_here, - unescapeLeadingUnderscores(alreadyExportedSymbol.escapedName) - ) - ); + addRelatedInfo(diag2, createDiagnosticForNode(exportingDeclaration, Diagnostics._0_is_automatically_exported_here, unescapeLeadingUnderscores(alreadyExportedSymbol.escapedName))); } } } else { + var _ref28; Debug.assert(node.kind !== 260 /* VariableDeclaration */); const importDeclaration = findAncestor(node, or(isImportDeclaration, isImportEqualsDeclaration)); - const moduleSpecifier = (importDeclaration && ((_d = tryGetModuleSpecifierFromDeclaration(importDeclaration)) == null ? void 0 : _d.text)) ?? "..."; + const moduleSpecifier = (_ref28 = importDeclaration && ((_d = tryGetModuleSpecifierFromDeclaration(importDeclaration)) == null ? void 0 : _d.text)) !== null && _ref28 !== void 0 ? _ref28 : "..."; const importedIdentifier = unescapeLeadingUnderscores(isIdentifier(errorNode) ? errorNode.escapedText : symbol.escapedName); - error2( - errorNode, - Diagnostics._0_is_a_type_and_cannot_be_imported_in_JavaScript_files_Use_1_in_a_JSDoc_type_annotation, - importedIdentifier, - `import("${moduleSpecifier}").${importedIdentifier}` - ); + error2(errorNode, Diagnostics._0_is_a_type_and_cannot_be_imported_in_JavaScript_files_Use_1_in_a_JSDoc_type_annotation, importedIdentifier, `import("${moduleSpecifier}").${importedIdentifier}`); } return; } @@ -82735,30 +76525,28 @@ ${lanes.join("\n")} switch (node.kind) { case 273 /* ImportClause */: case 276 /* ImportSpecifier */: - case 271 /* ImportEqualsDeclaration */: { - if (compilerOptions.preserveValueImports || compilerOptions.verbatimModuleSyntax) { - Debug.assertIsDefined(node.name, "An ImportClause with a symbol should have a name"); - const message = compilerOptions.verbatimModuleSyntax && isInternalModuleImportEqualsDeclaration(node) ? Diagnostics.An_import_alias_cannot_resolve_to_a_type_or_type_only_declaration_when_verbatimModuleSyntax_is_enabled : isType ? compilerOptions.verbatimModuleSyntax ? Diagnostics._0_is_a_type_and_must_be_imported_using_a_type_only_import_when_verbatimModuleSyntax_is_enabled : Diagnostics._0_is_a_type_and_must_be_imported_using_a_type_only_import_when_preserveValueImports_and_isolatedModules_are_both_enabled : compilerOptions.verbatimModuleSyntax ? Diagnostics._0_resolves_to_a_type_only_declaration_and_must_be_imported_using_a_type_only_import_when_verbatimModuleSyntax_is_enabled : Diagnostics._0_resolves_to_a_type_only_declaration_and_must_be_imported_using_a_type_only_import_when_preserveValueImports_and_isolatedModules_are_both_enabled; - const name = idText(node.kind === 276 /* ImportSpecifier */ ? node.propertyName || node.name : node.name); - addTypeOnlyDeclarationRelatedInfo( - error2(node, message, name), - isType ? void 0 : typeOnlyAlias, - name - ); - } - if (isType && node.kind === 271 /* ImportEqualsDeclaration */ && hasEffectiveModifier(node, 32 /* Export */)) { - error2(node, Diagnostics.Cannot_use_export_import_on_a_type_or_type_only_namespace_when_0_is_enabled, isolatedModulesLikeFlagName); - } - break; - } - case 281 /* ExportSpecifier */: { - if (compilerOptions.verbatimModuleSyntax || getSourceFileOfNode(typeOnlyAlias) !== getSourceFileOfNode(node)) { - const name = idText(node.propertyName || node.name); - const diagnostic = isType ? error2(node, Diagnostics.Re_exporting_a_type_when_0_is_enabled_requires_using_export_type, isolatedModulesLikeFlagName) : error2(node, Diagnostics._0_resolves_to_a_type_only_declaration_and_must_be_re_exported_using_a_type_only_re_export_when_1_is_enabled, name, isolatedModulesLikeFlagName); - addTypeOnlyDeclarationRelatedInfo(diagnostic, isType ? void 0 : typeOnlyAlias, name); + case 271 /* ImportEqualsDeclaration */: + { + if (compilerOptions.preserveValueImports || compilerOptions.verbatimModuleSyntax) { + Debug.assertIsDefined(node.name, "An ImportClause with a symbol should have a name"); + const message = compilerOptions.verbatimModuleSyntax && isInternalModuleImportEqualsDeclaration(node) ? Diagnostics.An_import_alias_cannot_resolve_to_a_type_or_type_only_declaration_when_verbatimModuleSyntax_is_enabled : isType ? compilerOptions.verbatimModuleSyntax ? Diagnostics._0_is_a_type_and_must_be_imported_using_a_type_only_import_when_verbatimModuleSyntax_is_enabled : Diagnostics._0_is_a_type_and_must_be_imported_using_a_type_only_import_when_preserveValueImports_and_isolatedModules_are_both_enabled : compilerOptions.verbatimModuleSyntax ? Diagnostics._0_resolves_to_a_type_only_declaration_and_must_be_imported_using_a_type_only_import_when_verbatimModuleSyntax_is_enabled : Diagnostics._0_resolves_to_a_type_only_declaration_and_must_be_imported_using_a_type_only_import_when_preserveValueImports_and_isolatedModules_are_both_enabled; + const name = idText(node.kind === 276 /* ImportSpecifier */ ? node.propertyName || node.name : node.name); + addTypeOnlyDeclarationRelatedInfo(error2(node, message, name), isType ? void 0 : typeOnlyAlias, name); + } + if (isType && node.kind === 271 /* ImportEqualsDeclaration */ && hasEffectiveModifier(node, 32 /* Export */)) { + error2(node, Diagnostics.Cannot_use_export_import_on_a_type_or_type_only_namespace_when_0_is_enabled, isolatedModulesLikeFlagName); + } break; } - } + case 281 /* ExportSpecifier */: + { + if (compilerOptions.verbatimModuleSyntax || getSourceFileOfNode(typeOnlyAlias) !== getSourceFileOfNode(node)) { + const name = idText(node.propertyName || node.name); + const diagnostic = isType ? error2(node, Diagnostics.Re_exporting_a_type_when_0_is_enabled_requires_using_export_type, isolatedModulesLikeFlagName) : error2(node, Diagnostics._0_resolves_to_a_type_only_declaration_and_must_be_re_exported_using_a_type_only_re_export_when_1_is_enabled, name, isolatedModulesLikeFlagName); + addTypeOnlyDeclarationRelatedInfo(diagnostic, isType ? void 0 : typeOnlyAlias, name); + break; + } + } } } if (compilerOptions.verbatimModuleSyntax && node.kind !== 271 /* ImportEqualsDeclaration */ && !isInJSFile(node) && (moduleKind === 1 /* CommonJS */ || getSourceFileOfNode(node).impliedNodeFormat === 1 /* CommonJS */)) { @@ -82778,20 +76566,17 @@ ${lanes.join("\n")} 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; } } @@ -82808,6 +76593,7 @@ ${lanes.join("\n")} checkExternalEmitHelpers(node, 131072 /* ImportDefault */); } } + function checkImportAttributes(declaration) { var _a; const node = declaration.attributes; @@ -82905,6 +76691,7 @@ ${lanes.join("\n")} if (node.moduleSpecifier && node.exportClause && isNamedExports(node.exportClause) && length(node.exportClause.elements) && languageVersion === 0 /* ES3 */) { checkExternalEmitHelpers(node, 4194304 /* CreateBinding */); } + checkGrammarExportDeclaration(node); if (!node.moduleSpecifier || checkExternalImportOrExportDeclaration(node)) { if (node.exportClause && !isNamespaceExport(node.exportClause)) { @@ -82932,6 +76719,7 @@ ${lanes.join("\n")} } } } + checkImportAttributes(node); } function checkGrammarExportDeclaration(node) { @@ -82949,28 +76737,22 @@ ${lanes.join("\n")} return !isInAppropriateContext; } function importClauseContainsReferencedImport(importClause) { - return forEachImportClauseDeclaration(importClause, (declaration) => { + return forEachImportClauseDeclaration(importClause, declaration => { return !!getSymbolOfDeclaration(declaration).isReferenced; }); } function importClauseContainsConstEnumUsedAsValue(importClause) { - return forEachImportClauseDeclaration(importClause, (declaration) => { + return forEachImportClauseDeclaration(importClause, declaration => { return !!getSymbolLinks(getSymbolOfDeclaration(declaration)).constEnumReferenced; }); } function canConvertImportDeclarationToTypeOnly(statement) { - return isImportDeclaration(statement) && statement.importClause && !statement.importClause.isTypeOnly && importClauseContainsReferencedImport(statement.importClause) && !isReferencedAliasDeclaration( - statement.importClause, - /*checkChildren*/ - true - ) && !importClauseContainsConstEnumUsedAsValue(statement.importClause); + return isImportDeclaration(statement) && statement.importClause && !statement.importClause.isTypeOnly && importClauseContainsReferencedImport(statement.importClause) && !isReferencedAliasDeclaration(statement.importClause, /*checkChildren*/ + true) && !importClauseContainsConstEnumUsedAsValue(statement.importClause); } function canConvertImportEqualsDeclarationToTypeOnly(statement) { - return isImportEqualsDeclaration(statement) && isExternalModuleReference(statement.moduleReference) && !statement.isTypeOnly && getSymbolOfDeclaration(statement).isReferenced && !isReferencedAliasDeclaration( - statement, - /*checkChildren*/ - false - ) && !getSymbolLinks(getSymbolOfDeclaration(statement)).constEnumReferenced; + return isImportEqualsDeclaration(statement) && isExternalModuleReference(statement.moduleReference) && !statement.isTypeOnly && getSymbolOfDeclaration(statement).isReferenced && !isReferencedAliasDeclaration(statement, /*checkChildren*/ + false) && !getSymbolLinks(getSymbolOfDeclaration(statement)).constEnumReferenced; } function checkImportsForTypeOnlyConversion(sourceFile) { if (!canCollectSymbolAliasAccessabilityData) { @@ -82978,35 +76760,22 @@ ${lanes.join("\n")} } for (const statement of sourceFile.statements) { if (canConvertImportDeclarationToTypeOnly(statement) || canConvertImportEqualsDeclarationToTypeOnly(statement)) { - error2( - statement, - Diagnostics.This_import_is_never_used_as_a_value_and_must_use_import_type_because_importsNotUsedAsValues_is_set_to_error - ); + error2(statement, Diagnostics.This_import_is_never_used_as_a_value_and_must_use_import_type_because_importsNotUsedAsValues_is_set_to_error); } } } function checkExportSpecifier(node) { checkAliasSymbol(node); if (getEmitDeclarations(compilerOptions)) { - collectLinkedAliases( - node.propertyName || node.name, - /*setVisibility*/ - true - ); + collectLinkedAliases(node.propertyName || node.name, /*setVisibility*/ + true); } if (!node.parent.parent.moduleSpecifier) { const exportedName = node.propertyName || node.name; - const symbol = resolveName( - exportedName, - exportedName.escapedText, - 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, - /*nameNotFoundMessage*/ - void 0, - /*nameArg*/ - void 0, - /*isUse*/ - true - ); + const symbol = resolveName(exportedName, exportedName.escapedText, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ + void 0, /*nameArg*/ + void 0, /*isUse*/ + true); 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 { @@ -83024,6 +76793,7 @@ ${lanes.join("\n")} } } } + function checkExportAssignment(node) { const illegalContextMessage = node.isExportEquals ? Diagnostics.An_export_assignment_must_be_at_the_top_level_of_a_file_or_module_declaration : Diagnostics.A_default_export_must_be_at_the_top_level_of_a_file_or_module_declaration; if (checkGrammarModuleElementContext(node, illegalContextMessage)) { @@ -83048,42 +76818,25 @@ ${lanes.join("\n")} const isIllegalExportDefaultInCJS = !node.isExportEquals && !(node.flags & 33554432 /* Ambient */) && compilerOptions.verbatimModuleSyntax && (moduleKind === 1 /* CommonJS */ || getSourceFileOfNode(node).impliedNodeFormat === 1 /* CommonJS */); if (node.expression.kind === 80 /* Identifier */) { const id = node.expression; - const sym = getExportSymbolOfValueSymbolIfExported(resolveEntityName( - id, - 67108863 /* All */, - /*ignoreErrors*/ - true, - /*dontResolveAlias*/ - true, - node - )); + const sym = getExportSymbolOfValueSymbolIfExported(resolveEntityName(id, 67108863 /* All */, /*ignoreErrors*/ + true, /*dontResolveAlias*/ + true, node)); if (sym) { markAliasReferenced(sym, id); if (getSymbolFlags(sym) & 111551 /* Value */) { checkExpressionCached(id); if (!isIllegalExportDefaultInCJS && !(node.flags & 33554432 /* Ambient */) && compilerOptions.verbatimModuleSyntax && getTypeOnlyAliasDeclaration(sym, 111551 /* Value */)) { - error2( - id, - node.isExportEquals ? Diagnostics.An_export_declaration_must_reference_a_real_value_when_verbatimModuleSyntax_is_enabled_but_0_resolves_to_a_type_only_declaration : Diagnostics.An_export_default_must_reference_a_real_value_when_verbatimModuleSyntax_is_enabled_but_0_resolves_to_a_type_only_declaration, - idText(id) - ); + error2(id, node.isExportEquals ? Diagnostics.An_export_declaration_must_reference_a_real_value_when_verbatimModuleSyntax_is_enabled_but_0_resolves_to_a_type_only_declaration : Diagnostics.An_export_default_must_reference_a_real_value_when_verbatimModuleSyntax_is_enabled_but_0_resolves_to_a_type_only_declaration, idText(id)); } } else if (!isIllegalExportDefaultInCJS && !(node.flags & 33554432 /* Ambient */) && compilerOptions.verbatimModuleSyntax) { - error2( - id, - node.isExportEquals ? Diagnostics.An_export_declaration_must_reference_a_value_when_verbatimModuleSyntax_is_enabled_but_0_only_refers_to_a_type : Diagnostics.An_export_default_must_reference_a_value_when_verbatimModuleSyntax_is_enabled_but_0_only_refers_to_a_type, - idText(id) - ); + error2(id, node.isExportEquals ? Diagnostics.An_export_declaration_must_reference_a_value_when_verbatimModuleSyntax_is_enabled_but_0_only_refers_to_a_type : Diagnostics.An_export_default_must_reference_a_value_when_verbatimModuleSyntax_is_enabled_but_0_only_refers_to_a_type, idText(id)); } } else { checkExpressionCached(id); } if (getEmitDeclarations(compilerOptions)) { - collectLinkedAliases( - id, - /*setVisibility*/ - true - ); + collectLinkedAliases(id, /*setVisibility*/ + true); } } else { checkExpressionCached(node.expression); @@ -83119,7 +76872,10 @@ ${lanes.join("\n")} } const exports = getExportsOfModule(moduleSymbol); if (exports) { - exports.forEach(({ declarations, flags }, id) => { + exports.forEach(({ + declarations, + flags + }, id) => { if (id === "__export") { return; } @@ -83145,7 +76901,7 @@ ${lanes.join("\n")} } } function isDuplicatedCommonJSExport(declarations) { - return declarations && declarations.length > 1 && declarations.every((d) => isInJSFile(d) && isAccessExpression(d) && (isExportsIdentifier(d.expression) || isModuleExportsAccessExpression(d.expression))); + return declarations && declarations.length > 1 && declarations.every(d => isInJSFile(d) && isAccessExpression(d) && (isExportsIdentifier(d.expression) || isModuleExportsAccessExpression(d.expression))); } function checkSourceElement(node) { if (node) { @@ -83158,9 +76914,12 @@ ${lanes.join("\n")} } function checkSourceElementWorker(node) { if (canHaveJSDoc(node)) { - forEach(node.jsDoc, ({ comment, tags }) => { + forEach(node.jsDoc, ({ + comment, + tags + }) => { checkJSDocCommentWorker(comment); - forEach(tags, (tag) => { + forEach(tags, tag => { checkJSDocCommentWorker(tag.comment); if (isInJSFile(node)) { checkSourceElement(tag); @@ -83354,7 +77113,7 @@ ${lanes.join("\n")} } function checkJSDocCommentWorker(node) { if (isArray(node)) { - forEach(node, (tag) => { + forEach(node, tag => { if (isJSDocLinkLike(tag)) { checkSourceElement(tag); } @@ -83368,14 +77127,7 @@ ${lanes.join("\n")} const diagnostic = node.postfix ? Diagnostics._0_at_the_end_of_a_type_is_not_valid_TypeScript_syntax_Did_you_mean_to_write_1 : Diagnostics._0_at_the_start_of_a_type_is_not_valid_TypeScript_syntax_Did_you_mean_to_write_1; const typeNode = node.type; const type = getTypeFromTypeNode(typeNode); - grammarErrorOnNode( - node, - diagnostic, - token, - typeToString( - isJSDocNullableType(node) && !(type === neverType || type === voidType) ? getUnionType(append([type, undefinedType], node.postfix ? void 0 : nullType)) : type - ) - ); + grammarErrorOnNode(node, diagnostic, token, typeToString(isJSDocNullableType(node) && !(type === neverType || type === voidType) ? getUnionType(append([type, undefinedType], node.postfix ? void 0 : nullType)) : type)); } else { grammarErrorOnNode(node, Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments); } @@ -83384,7 +77136,9 @@ ${lanes.join("\n")} function checkJSDocVariadicType(node) { checkJSDocTypeIsInJsFile(node); checkSourceElement(node.type); - const { parent: parent2 } = node; + const { + parent: parent2 + } = node; if (isParameter(parent2) && isJSDocFunctionType(parent2.parent)) { if (last(parent2.parent.parameters) !== parent2) { error2(node, Diagnostics.A_rest_parameter_must_be_last_in_a_parameter_list); @@ -83410,7 +77164,9 @@ ${lanes.join("\n")} } function getTypeFromJSDocVariadicType(node) { const type = getTypeFromTypeNode(node.type); - const { parent: parent2 } = node; + const { + parent: parent2 + } = node; const paramTag = node.parent.parent; if (isJSDocTypeExpression(node.parent) && isJSDocParameterTag(paramTag)) { const host2 = getHostSignatureFromJSDoc(paramTag); @@ -83432,7 +77188,7 @@ ${lanes.join("\n")} const enclosingFile = getSourceFileOfNode(node); const links = getNodeLinks(enclosingFile); if (!(links.flags & 1 /* TypeChecked */)) { - links.deferredNodes || (links.deferredNodes = /* @__PURE__ */ new Set()); + links.deferredNodes || (links.deferredNodes = /* @__PURE__ */new Set()); links.deferredNodes.add(node); } else { Debug.assert(!links.deferredNodes, "A type-checked file should have no deferred nodes."); @@ -83447,7 +77203,12 @@ ${lanes.join("\n")} } function checkDeferredNode(node) { var _a, _b; - (_a = tracing) == null ? void 0 : _a.push(tracing.Phase.Check, "checkDeferredNode", { kind: node.kind, pos: node.pos, end: node.end, path: node.tracingPath }); + (_a = tracing) == null ? void 0 : _a.push(tracing.Phase.Check, "checkDeferredNode", { + kind: node.kind, + pos: node.pos, + end: node.end, + path: node.tracingPath + }); const saveCurrentNode = currentNode; currentNode = node; instantiationCount = 0; @@ -83500,13 +77261,10 @@ ${lanes.join("\n")} } function checkSourceFile(node) { var _a, _b; - (_a = tracing) == null ? void 0 : _a.push( - tracing.Phase.Check, - "checkSourceFile", - { path: node.path }, - /*separateBeginAndEnd*/ - true - ); + (_a = tracing) == null ? void 0 : _a.push(tracing.Phase.Check, "checkSourceFile", { + path: node.path + }, /*separateBeginAndEnd*/ + true); mark("beforeCheck"); checkSourceFileWorker(node); mark("afterCheck"); @@ -83584,6 +77342,7 @@ ${lanes.join("\n")} links.flags |= 1 /* TypeChecked */; } } + function getDiagnostics2(sourceFile, ct) { try { cancellationToken = ct; @@ -83601,7 +77360,7 @@ ${lanes.join("\n")} function checkSourceFileWithEagerDiagnostics(sourceFile) { ensurePendingDiagnosticWorkComplete(); const oldAddLazyDiagnostics = addLazyDiagnostic; - addLazyDiagnostic = (cb) => cb(); + addLazyDiagnostic = cb => cb(); checkSourceFile(sourceFile); addLazyDiagnostic = oldAddLazyDiagnostics; } @@ -83644,8 +77403,7 @@ ${lanes.join("\n")} } switch (location.kind) { case 312 /* SourceFile */: - if (!isExternalModule(location)) - break; + if (!isExternalModule(location)) break; case 267 /* ModuleDeclaration */: copyLocallyVisibleExportSymbols(getSymbolOfDeclaration(location).exports, meaning & 2623475 /* ModuleMember */); break; @@ -83662,6 +77420,7 @@ ${lanes.join("\n")} if (!isStaticSymbol) { copySymbols(getMembersOfSymbol(getSymbolOfDeclaration(location)), meaning & 788968 /* Type */); } + break; case 218 /* FunctionExpression */: const funcName = location.name; @@ -83688,14 +77447,14 @@ ${lanes.join("\n")} } function copySymbols(source, meaning2) { if (meaning2) { - source.forEach((symbol) => { + source.forEach(symbol => { copySymbol(symbol, meaning2); }); } } function copyLocallyVisibleExportSymbols(source, meaning2) { if (meaning2) { - source.forEach((symbol) => { + source.forEach(symbol => { if (!getDeclarationOfKind(symbol, 281 /* ExportSpecifier */) && !getDeclarationOfKind(symbol, 280 /* NamespaceExport */) && symbol.escapedName !== "default" /* Default */) { copySymbol(symbol, meaning2); } @@ -83712,24 +77471,25 @@ ${lanes.join("\n")} } return node.parent.kind === 183 /* TypeReference */; } + function isInNameOfExpressionWithTypeArguments(node) { while (node.parent.kind === 211 /* PropertyAccessExpression */) { node = node.parent; } return node.parent.kind === 233 /* ExpressionWithTypeArguments */; } + function forEachEnclosingClass(node, callback) { let result; let containingClass = getContainingClass(node); while (containingClass) { - if (result = callback(containingClass)) - break; + if (result = callback(containingClass)) break; containingClass = getContainingClass(containingClass); } return result; } function isNodeUsedDuringClassInitialization(node) { - return !!findAncestor(node, (element) => { + return !!findAncestor(node, element => { if (isConstructorDeclaration(element) && nodeIsPresent(element.body) || isPropertyDeclaration(element)) { return true; } else if (isClassLike(element) || isFunctionLikeDeclaration(element)) { @@ -83739,7 +77499,7 @@ ${lanes.join("\n")} }); } function isNodeWithinClass(node, classDeclaration) { - return !!forEachEnclosingClass(node, (n) => n === classDeclaration); + return !!forEachEnclosingClass(node, n => n === classDeclaration); } function getLeftSideOfImportEqualsOrExportAssignment(nodeOnRightSide) { while (nodeOnRightSide.parent.kind === 166 /* QualifiedName */) { @@ -83781,21 +77541,14 @@ ${lanes.join("\n")} } function isThisPropertyAndThisTyped(node) { if (node.expression.kind === 110 /* ThisKeyword */) { - const container = getThisContainer( - node, - /*includeArrowFunctions*/ - false, - /*includeClassComputedPropertyName*/ - false - ); + const container = getThisContainer(node, /*includeArrowFunctions*/ + false, /*includeClassComputedPropertyName*/ + false); if (isFunctionLike(container)) { const containingLiteral = getContainingObjectLiteral(container); if (containingLiteral) { - const contextualType = getApparentTypeOfContextualType( - containingLiteral, - /*contextFlags*/ - void 0 - ); + const contextualType = getApparentTypeOfContextualType(containingLiteral, /*contextFlags*/ + void 0); const type = getThisTypeOfObjectLiteralFromContextualType(containingLiteral, contextualType); return type && !isTypeAny(type); } @@ -83815,24 +77568,17 @@ ${lanes.join("\n")} } } if (name.parent.kind === 277 /* ExportAssignment */ && isEntityNameExpression(name)) { - const success = resolveEntityName( - name, - /*all meanings*/ - 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, - /*ignoreErrors*/ - true - ); + const success = resolveEntityName(name, /*all meanings*/ + 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*ignoreErrors*/ + true); if (success && success !== unknownSymbol) { return success; } } else if (isEntityName(name) && isInRightSideOfImportOrExportAssignment(name)) { const importEqualsDeclaration = getAncestor(name, 271 /* ImportEqualsDeclaration */); Debug.assert(importEqualsDeclaration !== void 0); - return getSymbolOfPartOfRightHandSideOfImportEquals( - name, - /*dontResolveAlias*/ - true - ); + return getSymbolOfPartOfRightHandSideOfImportEquals(name, /*dontResolveAlias*/ + true); } if (isEntityName(name)) { const possibleImportNode = isImportTypeQualifierPart(name); @@ -83855,13 +77601,10 @@ ${lanes.join("\n")} } else { meaning = 1920 /* Namespace */; } + meaning |= 2097152 /* Alias */; - const entityNameSymbol = isEntityNameExpression(name) ? resolveEntityName( - name, - meaning, - /*ignoreErrors*/ - true - ) : void 0; + const entityNameSymbol = isEntityNameExpression(name) ? resolveEntityName(name, meaning, /*ignoreErrors*/ + true) : void 0; if (entityNameSymbol) { return entityNameSymbol; } @@ -83885,38 +77628,22 @@ ${lanes.join("\n")} const symbol = getIntrinsicTagSymbol(name.parent); return symbol === unknownSymbol ? void 0 : symbol; } - const result = resolveEntityName( - name, - meaning, - /*ignoreErrors*/ - true, - /*dontResolveAlias*/ - true, - getHostSignatureFromJSDoc(name) - ); + const result = resolveEntityName(name, meaning, /*ignoreErrors*/ + true, /*dontResolveAlias*/ + true, getHostSignatureFromJSDoc(name)); if (!result && isJSDoc2) { const container = findAncestor(name, or(isClassLike, isInterfaceDeclaration)); if (container) { - return resolveJSDocMemberName( - name, - /*ignoreErrors*/ - true, - getSymbolOfDeclaration(container) - ); + return resolveJSDocMemberName(name, /*ignoreErrors*/ + true, getSymbolOfDeclaration(container)); } } if (result && isJSDoc2) { const container = getJSDocHost(name); if (container && isEnumMember(container) && container === result.valueDeclaration) { - return resolveEntityName( - name, - meaning, - /*ignoreErrors*/ - true, - /*dontResolveAlias*/ - true, - getSourceFileOfNode(container) - ) || result; + return resolveEntityName(name, meaning, /*ignoreErrors*/ + true, /*dontResolveAlias*/ + true, getSourceFileOfNode(container)) || result; } } return result; @@ -83935,6 +77662,7 @@ ${lanes.join("\n")} } else { checkQualifiedName(name, 0 /* Normal */); } + if (!links.resolvedSymbol && isJSDoc2 && isQualifiedName(name)) { return resolveJSDocMemberName(name); } @@ -83944,23 +77672,16 @@ ${lanes.join("\n")} } } else if (isTypeReferenceIdentifier(name)) { const meaning = name.parent.kind === 183 /* TypeReference */ ? 788968 /* Type */ : 1920 /* Namespace */; - const symbol = resolveEntityName( - name, - meaning, - /*ignoreErrors*/ - false, - /*dontResolveAlias*/ - true - ); + const symbol = resolveEntityName(name, meaning, /*ignoreErrors*/ + false, /*dontResolveAlias*/ + true); return symbol && symbol !== unknownSymbol ? symbol : getUnresolvedSymbolForEntityName(name); } if (name.parent.kind === 182 /* TypePredicate */) { - return resolveEntityName( - name, - /*meaning*/ - 1 /* FunctionScopedVariable */ - ); + return resolveEntityName(name, /*meaning*/ + 1 /* FunctionScopedVariable */); } + return void 0; } function getApplicableIndexSymbol(type, keyType) { @@ -83971,16 +77692,16 @@ ${lanes.join("\n")} return symbol; } else if (symbol) { const symbolLinks2 = getSymbolLinks(symbol); - const declarationList = mapDefined(infos, (i) => i.declaration); + const declarationList = mapDefined(infos, i => i.declaration); const nodeListId = map(declarationList, getNodeId).join(","); if (!symbolLinks2.filteredIndexSymbolCache) { - symbolLinks2.filteredIndexSymbolCache = /* @__PURE__ */ new Map(); + symbolLinks2.filteredIndexSymbolCache = /* @__PURE__ */new Map(); } if (symbolLinks2.filteredIndexSymbolCache.has(nodeListId)) { return symbolLinks2.filteredIndexSymbolCache.get(nodeListId); } else { const copy = createSymbol(131072 /* Signature */, "__index" /* Index */); - copy.declarations = mapDefined(infos, (i) => i.declaration); + copy.declarations = mapDefined(infos, i => i.declaration); copy.parent = type.aliasSymbol ? type.aliasSymbol : type.symbol ? type.symbol : getSymbolAtLocation(copy.declarations[0].parent); symbolLinks2.filteredIndexSymbolCache.set(nodeListId, copy); return copy; @@ -83991,14 +77712,8 @@ ${lanes.join("\n")} function resolveJSDocMemberName(name, ignoreErrors, container) { if (isEntityName(name)) { const meaning = 788968 /* Type */ | 1920 /* Namespace */ | 111551 /* Value */; - let symbol = resolveEntityName( - name, - meaning, - ignoreErrors, - /*dontResolveAlias*/ - true, - getHostSignatureFromJSDoc(name) - ); + let symbol = resolveEntityName(name, meaning, ignoreErrors, /*dontResolveAlias*/ + true, getHostSignatureFromJSDoc(name)); if (!symbol && isIdentifier(name) && container) { symbol = getMergedSymbol(getSymbol2(getExportsOfSymbol(container), name.escapedText, meaning)); } @@ -84018,7 +77733,9 @@ ${lanes.join("\n")} if (isSourceFile(node)) { return isExternalModule(node) ? getMergedSymbol(node.symbol) : void 0; } - const { parent: parent2 } = node; + const { + parent: parent2 + } = node; const grandParent = parent2.parent; if (node.flags & 67108864 /* InWithStatement */) { return void 0; @@ -84057,13 +77774,9 @@ ${lanes.join("\n")} return getSymbolOfNameOrPropertyAccessExpression(node); } case 110 /* ThisKeyword */: - const container = getThisContainer( - node, - /*includeArrowFunctions*/ - false, - /*includeClassComputedPropertyName*/ - false - ); + const container = getThisContainer(node, /*includeArrowFunctions*/ + false, /*includeClassComputedPropertyName*/ + false); if (isFunctionLike(container)) { const sig = getSignatureFromDeclaration(container); if (sig.thisParameter) { @@ -84085,11 +77798,8 @@ ${lanes.join("\n")} return void 0; case 11 /* StringLiteral */: case 15 /* NoSubstitutionTemplateLiteral */: - if (isExternalModuleImportEqualsDeclaration(node.parent.parent) && getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node || (node.parent.kind === 272 /* ImportDeclaration */ || node.parent.kind === 278 /* ExportDeclaration */) && node.parent.moduleSpecifier === node || (isInJSFile(node) && getEmitModuleResolutionKind(compilerOptions) !== 100 /* Bundler */ && isRequireCall( - node.parent, - /*requireStringLiteralLikeArgument*/ - false - ) || isImportCall(node.parent)) || isLiteralTypeNode(node.parent) && isLiteralImportTypeNode(node.parent.parent) && node.parent.parent.argument === node.parent) { + if (isExternalModuleImportEqualsDeclaration(node.parent.parent) && getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node || (node.parent.kind === 272 /* ImportDeclaration */ || node.parent.kind === 278 /* ExportDeclaration */) && node.parent.moduleSpecifier === node || isInJSFile(node) && getEmitModuleResolutionKind(compilerOptions) !== 100 /* Bundler */ && isRequireCall(node.parent, /*requireStringLiteralLikeArgument*/ + false) || isImportCall(node.parent) || isLiteralTypeNode(node.parent) && isLiteralImportTypeNode(node.parent.parent) && node.parent.parent.argument === node.parent) { return resolveExternalModuleName(node, node, ignoreErrors); } if (isCallExpression(parent2) && isBindableObjectDefinePropertyCall(parent2) && parent2.arguments[1] === node) { @@ -84112,9 +77822,10 @@ ${lanes.join("\n")} return isMetaProperty(node.parent) ? checkMetaPropertyKeyword(node.parent).symbol : void 0; case 104 /* InstanceOfKeyword */: if (isBinaryExpression(node.parent)) { + var _ref29; const type = getTypeOfExpression(node.parent.right); const hasInstanceMethodType = getSymbolHasInstanceMethodOfObjectType(type); - return (hasInstanceMethodType == null ? void 0 : hasInstanceMethodType.symbol) ?? type.symbol; + return (_ref29 = hasInstanceMethodType == null ? void 0 : hasInstanceMethodType.symbol) !== null && _ref29 !== void 0 ? _ref29 : type.symbol; } return void 0; case 236 /* MetaProperty */: @@ -84133,7 +77844,7 @@ ${lanes.join("\n")} const keyType = getLiteralTypeFromPropertyName(node); const objectType = getTypeOfExpression(node.parent.expression); const objectTypes = objectType.flags & 1048576 /* Union */ ? objectType.types : [objectType]; - return flatMap(objectTypes, (t) => filter(getIndexInfosOfType(t), (info) => isApplicableIndexType(keyType, info.keyType))); + return flatMap(objectTypes, t => filter(getIndexInfosOfType(t), info => isApplicableIndexType(keyType, info.keyType))); } return void 0; } @@ -84141,6 +77852,7 @@ ${lanes.join("\n")} if (location && location.kind === 304 /* ShorthandPropertyAssignment */) { return resolveEntityName(location.name, 111551 /* Value */ | 2097152 /* Alias */); } + return void 0; } function getExportSpecifierLocalTargetSymbol(node) { @@ -84150,6 +77862,7 @@ ${lanes.join("\n")} return resolveEntityName(node, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); } } + function getTypeOfNode(node) { if (isSourceFile(node) && !isExternalModule(node)) { return errorType; @@ -84179,12 +77892,8 @@ ${lanes.join("\n")} return symbol ? getDeclaredTypeOfSymbol(symbol) : errorType; } if (isBindingElement(node)) { - return getTypeForVariableLikeDeclaration( - node, - /*includeOptionality*/ - true, - 0 /* Normal */ - ) || errorType; + return getTypeForVariableLikeDeclaration(node, /*includeOptionality*/ + true, 0 /* Normal */) || errorType; } if (isDeclaration(node)) { const symbol = getSymbolOfDeclaration(node); @@ -84198,12 +77907,8 @@ ${lanes.join("\n")} return errorType; } if (isBindingPattern(node)) { - return getTypeForVariableLikeDeclaration( - node.parent, - /*includeOptionality*/ - true, - 0 /* Normal */ - ) || errorType; + return getTypeForVariableLikeDeclaration(node.parent, /*includeOptionality*/ + true, 0 /* Normal */) || errorType; } if (isInRightSideOfImportOrExportAssignment(node)) { const symbol = getSymbolAtLocation(node); @@ -84272,7 +77977,7 @@ ${lanes.join("\n")} const propsByName = createSymbolTable(getPropertiesOfType(type)); const functionType = getSignaturesOfType(type, 0 /* Call */).length ? globalCallableFunctionType : getSignaturesOfType(type, 1 /* Construct */).length ? globalNewableFunctionType : void 0; if (functionType) { - forEach(getPropertiesOfType(functionType), (p) => { + forEach(getPropertiesOfType(functionType), p => { if (!propsByName.has(p.escapedName)) { propsByName.set(p.escapedName, p); } @@ -84289,9 +77994,15 @@ ${lanes.join("\n")} } function getImmediateRootSymbols(symbol) { if (getCheckFlags(symbol) & 6 /* Synthetic */) { - return mapDefined(getSymbolLinks(symbol).containingType.types, (type) => getPropertyOfType(type, symbol.escapedName)); + return mapDefined(getSymbolLinks(symbol).containingType.types, type => getPropertyOfType(type, symbol.escapedName)); } else if (symbol.flags & 33554432 /* Transient */) { - const { links: { leftSpread, rightSpread, syntheticOrigin } } = symbol; + const { + links: { + leftSpread, + rightSpread, + syntheticOrigin + } + } = symbol; return leftSpread ? [leftSpread, rightSpread] : syntheticOrigin ? [syntheticOrigin] : singleElementArray(tryGetTarget(symbol)); } return void 0; @@ -84305,14 +78016,11 @@ ${lanes.join("\n")} 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; } @@ -84333,6 +78041,7 @@ ${lanes.join("\n")} return s && !!(getSymbolFlags(s) & 111551 /* Value */); } } + function isNameOfModuleOrEnumDeclaration(node) { return isModuleOrEnumDeclaration(node.parent) && node === node.parent.name; } @@ -84340,11 +78049,8 @@ ${lanes.join("\n")} var _a; const node = getParseTreeNode(nodeIn, isIdentifier); if (node) { - let symbol = getReferencedValueSymbol( - node, - /*startInDeclarationContainer*/ - isNameOfModuleOrEnumDeclaration(node) - ); + let symbol = getReferencedValueSymbol(node, /*startInDeclarationContainer*/ + isNameOfModuleOrEnumDeclaration(node)); if (symbol) { if (symbol.flags & 1048576 /* ExportValue */) { const exportSymbol = getMergedSymbol(symbol.exportSymbol); @@ -84361,7 +78067,7 @@ ${lanes.join("\n")} const symbolIsUmdExport = symbolFile !== referenceFile; return symbolIsUmdExport ? void 0 : symbolFile; } - return findAncestor(node.parent, (n) => isModuleOrEnumDeclaration(n) && getSymbolOfDeclaration(n) === parentSymbol); + return findAncestor(node.parent, n => isModuleOrEnumDeclaration(n) && getSymbolOfDeclaration(n) === parentSymbol); } } } @@ -84374,11 +78080,8 @@ ${lanes.join("\n")} const node = getParseTreeNode(nodeIn, isIdentifier); if (node) { const symbol = getReferencedValueOrAliasSymbol(node); - if (isNonLocalAlias( - symbol, - /*excludes*/ - 111551 /* Value */ - ) && !getTypeOnlyAliasDeclaration(symbol, 111551 /* Value */)) { + if (isNonLocalAlias(symbol, /*excludes*/ + 111551 /* Value */) && !getTypeOnlyAliasDeclaration(symbol, 111551 /* Value */)) { return getDeclarationOfAliasSymbol(symbol); } } @@ -84387,6 +78090,7 @@ ${lanes.join("\n")} function isSymbolOfDestructuredElementOfCatchBinding(symbol) { return symbol.valueDeclaration && isBindingElement(symbol.valueDeclaration) && walkUpBindingElementsAndPatterns(symbol.valueDeclaration).parent.kind === 299 /* CatchClause */; } + function isSymbolOfDeclarationWithCollidingName(symbol) { if (symbol.flags & 418 /* BlockScoped */ && symbol.valueDeclaration && !isSourceFile(symbol.valueDeclaration)) { const links = getSymbolLinks(symbol); @@ -84394,30 +78098,17 @@ ${lanes.join("\n")} const container = getEnclosingBlockScopeContainer(symbol.valueDeclaration); if (isStatementWithLocals(container) || isSymbolOfDestructuredElementOfCatchBinding(symbol)) { const nodeLinks2 = getNodeLinks(symbol.valueDeclaration); - if (resolveName( - container.parent, - symbol.escapedName, - 111551 /* Value */, - /*nameNotFoundMessage*/ - void 0, - /*nameArg*/ - void 0, - /*isUse*/ - false - )) { + if (resolveName(container.parent, symbol.escapedName, 111551 /* Value */, /*nameNotFoundMessage*/ + void 0, /*nameArg*/ + void 0, /*isUse*/ + false)) { links.isDeclarationWithCollidingName = true; } else if (nodeLinks2.flags & 16384 /* CapturedBlockScopedBinding */) { const isDeclaredInLoop = nodeLinks2.flags & 32768 /* BlockScopedBindingInLoop */; - const inLoopInitializer = isIterationStatement( - container, - /*lookInLabeledStatements*/ - false - ); - const inLoopBodyBlock = container.kind === 241 /* Block */ && isIterationStatement( - container.parent, - /*lookInLabeledStatements*/ - false - ); + const inLoopInitializer = isIterationStatement(container, /*lookInLabeledStatements*/ + false); + const inLoopBodyBlock = container.kind === 241 /* Block */ && isIterationStatement(container.parent, /*lookInLabeledStatements*/ + false); links.isDeclarationWithCollidingName = !isBlockScopedContainerTopLevel(container) && (!isDeclaredInLoop || !inLoopInitializer && !inLoopBodyBlock); } else { links.isDeclarationWithCollidingName = false; @@ -84460,11 +78151,8 @@ ${lanes.join("\n")} case 276 /* ImportSpecifier */: case 281 /* ExportSpecifier */: const symbol = getSymbolOfDeclaration(node); - return !!symbol && isAliasResolvedToValue( - symbol, - /*excludeTypeOnlyValues*/ - true - ); + return !!symbol && isAliasResolvedToValue(symbol, /*excludeTypeOnlyValues*/ + true); case 278 /* ExportDeclaration */: const exportClause = node.exportClause; return !!exportClause && (isNamespaceExport(exportClause) || some(exportClause.elements, isValueAliasDeclaration)); @@ -84489,12 +78177,8 @@ ${lanes.join("\n")} if (target === unknownSymbol) { return !excludeTypeOnlyValues || !getTypeOnlyAliasDeclaration(symbol); } - return !!(getSymbolFlags( - symbol, - excludeTypeOnlyValues, - /*excludeLocalMeanings*/ - true - ) & 111551 /* Value */) && (shouldPreserveConstEnums(compilerOptions) || !isConstEnumOrConstEnumOnlyModule(target)); + return !!(getSymbolFlags(symbol, excludeTypeOnlyValues, /*excludeLocalMeanings*/ + true) & 111551 /* Value */) && (shouldPreserveConstEnums(compilerOptions) || !isConstEnumOrConstEnumOnlyModule(target)); } function isConstEnumOrConstEnumOnlyModule(s) { return isConstEnumSymbol(s) || !!s.constEnumOnlyModule; @@ -84513,17 +78197,17 @@ ${lanes.join("\n")} } } if (checkChildren) { - return !!forEachChild(node, (node2) => isReferencedAliasDeclaration(node2, checkChildren)); + return !!forEachChild(node, node2 => isReferencedAliasDeclaration(node2, checkChildren)); } return false; } 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 + return signaturesOfSymbol.length > 1 || + // If there is single signature for the symbol, it is overload if that signature isn't coming from the node // e.g.: function foo(a: string): string; // function foo(a: any) { // This is implementation of the overloads // return a; @@ -84535,9 +78219,11 @@ ${lanes.join("\n")} function isRequiredInitializedParameter(parameter) { return !!strictNullChecks && !isOptionalParameter(parameter) && !isJSDocParameterTag(parameter) && !!parameter.initializer && !hasSyntacticModifier(parameter, 31 /* ParameterPropertyModifier */); } + function isOptionalUninitializedParameterProperty(parameter) { return strictNullChecks && isOptionalParameter(parameter) && !parameter.initializer && hasSyntacticModifier(parameter, 31 /* ParameterPropertyModifier */); } + function isExpandoFunctionDeclaration(node) { const declaration = getParseTreeNode(node, isFunctionDeclaration); if (!declaration) { @@ -84547,7 +78233,7 @@ ${lanes.join("\n")} if (!symbol || !(symbol.flags & 16 /* Function */)) { return false; } - return !!forEachEntry(getExportsOfSymbol(symbol), (p) => p.flags & 111551 /* Value */ && isExpandoPropertyDeclaration(p.valueDeclaration)); + return !!forEachEntry(getExportsOfSymbol(symbol), p => p.flags & 111551 /* Value */ && isExpandoPropertyDeclaration(p.valueDeclaration)); } function getPropertiesOfContainerFunction(node) { const declaration = getParseTreeNode(node, isFunctionDeclaration); @@ -84560,8 +78246,7 @@ ${lanes.join("\n")} 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 getEnumMemberValue(node) { @@ -84596,62 +78281,44 @@ ${lanes.join("\n")} 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)) { - const rootValueSymbol = resolveEntityName( - getFirstIdentifier(typeName), - 111551 /* Value */, - /*ignoreErrors*/ - true, - /*dontResolveAlias*/ - true, - location - ); + const rootValueSymbol = resolveEntityName(getFirstIdentifier(typeName), 111551 /* Value */, /*ignoreErrors*/ + true, /*dontResolveAlias*/ + true, location); isTypeOnly = !!((_a = rootValueSymbol == null ? void 0 : rootValueSymbol.declarations) == null ? void 0 : _a.every(isTypeOnlyImportOrExportDeclaration)); } - const valueSymbol = resolveEntityName( - typeName, - 111551 /* Value */, - /*ignoreErrors*/ - true, - /*dontResolveAlias*/ - true, - location - ); + const valueSymbol = resolveEntityName(typeName, 111551 /* Value */, /*ignoreErrors*/ + true, /*dontResolveAlias*/ + true, location); const resolvedSymbol = valueSymbol && valueSymbol.flags & 2097152 /* Alias */ ? resolveAlias(valueSymbol) : valueSymbol; isTypeOnly || (isTypeOnly = !!(valueSymbol && getTypeOnlyAliasDeclaration(valueSymbol, 111551 /* Value */))); - const typeSymbol = resolveEntityName( - typeName, - 788968 /* Type */, - /*ignoreErrors*/ - true, - /*dontResolveAlias*/ - false, - location - ); + const typeSymbol = resolveEntityName(typeName, 788968 /* Type */, /*ignoreErrors*/ + true, /*dontResolveAlias*/ + false, location); if (resolvedSymbol && resolvedSymbol === typeSymbol) { - const globalPromiseSymbol = getGlobalPromiseConstructorSymbol( - /*reportErrors*/ - false - ); + const globalPromiseSymbol = getGlobalPromiseConstructorSymbol( /*reportErrors*/ + false); if (globalPromiseSymbol && resolvedSymbol === globalPromiseSymbol) { return 9 /* Promise */; } + const constructorType = getTypeOfSymbol(resolvedSymbol); if (constructorType && isConstructorType(constructorType)) { return isTypeOnly ? 10 /* TypeWithCallSignature */ : 1 /* TypeWithConstructSignatureAndValue */; } } + if (!typeSymbol) { return isTypeOnly ? 11 /* ObjectType */ : 0 /* Unknown */; } + const type = getDeclaredTypeOfSymbol(typeSymbol); if (isErrorType(type)) { return isTypeOnly ? 11 /* ObjectType */ : 0 /* Unknown */; @@ -84679,16 +78346,19 @@ ${lanes.join("\n")} return 11 /* ObjectType */; } } + function createTypeOfDeclaration(declarationIn, enclosingDeclaration, flags, tracker, addUndefined) { const declaration = getParseTreeNode(declarationIn, isVariableLikeOrAccessor); if (!declaration) { return factory.createToken(133 /* AnyKeyword */); } + const symbol = getSymbolOfDeclaration(declaration); let type = symbol && !(symbol.flags & (2048 /* TypeLiteral */ | 131072 /* Signature */)) ? getWidenedLiteralType(getTypeOfSymbol(symbol)) : errorType; if (type.flags & 8192 /* UniqueESSymbol */ && type.symbol === symbol) { flags |= 1048576 /* AllowUniqueESSymbolType */; } + if (addUndefined) { type = getOptionalType(type); } @@ -84699,6 +78369,7 @@ ${lanes.join("\n")} if (!signatureDeclaration) { return factory.createToken(133 /* AnyKeyword */); } + const signature = getSignatureFromDeclaration(signatureDeclaration); return nodeBuilder.typeToTypeNode(getReturnTypeOfSignature(signature), enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, tracker); } @@ -84707,6 +78378,7 @@ ${lanes.join("\n")} if (!expr) { return factory.createToken(133 /* AnyKeyword */); } + const type = getWidenedType(getRegularTypeOfExpression(expr)); return nodeBuilder.typeToTypeNode(type, enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, tracker); } @@ -84725,38 +78397,22 @@ ${lanes.join("\n")} location = getDeclarationContainer(parent2); } } - return resolveName( - location, - reference.escapedText, - 111551 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */, - /*nameNotFoundMessage*/ - void 0, - /*nameArg*/ - void 0, - /*isUse*/ - true - ); + return resolveName(location, reference.escapedText, 111551 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ + void 0, /*nameArg*/ + void 0, /*isUse*/ + true); } function getReferencedValueOrAliasSymbol(reference) { const resolvedSymbol = getNodeLinks(reference).resolvedSymbol; if (resolvedSymbol && resolvedSymbol !== unknownSymbol) { return resolvedSymbol; } - return resolveName( - reference, - reference.escapedText, - 111551 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */, - /*nameNotFoundMessage*/ - void 0, - /*nameArg*/ - void 0, - /*isUse*/ - true, - /*excludeGlobals*/ - void 0, - /*getSpellingSuggestions*/ - void 0 - ); + return resolveName(reference, reference.escapedText, 111551 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ + void 0, /*nameArg*/ + void 0, /*isUse*/ + true, /*excludeGlobals*/ + void 0, /*getSpellingSuggestions*/ + void 0); } function getReferencedValueDeclaration(referenceIn) { if (!isGeneratedIdentifier(referenceIn)) { @@ -84776,7 +78432,7 @@ ${lanes.join("\n")} if (reference) { const symbol = getReferencedValueSymbol(reference); if (symbol) { - return filter(getExportSymbolOfValueSymbolIfExported(symbol).declarations, (declaration) => { + return filter(getExportSymbolOfValueSymbolIfExported(symbol).declarations, declaration => { switch (declaration.kind) { case 260 /* VariableDeclaration */: case 169 /* Parameter */: @@ -84812,16 +78468,9 @@ ${lanes.join("\n")} return false; } function literalTypeToNode(type, enclosing, tracker) { - const enumResult = type.flags & 1056 /* EnumLike */ ? nodeBuilder.symbolToExpression( - type.symbol, - 111551 /* Value */, - enclosing, - /*flags*/ - void 0, - tracker - ) : type === trueType ? factory.createTrue() : type === falseType && factory.createFalse(); - if (enumResult) - return enumResult; + const enumResult = type.flags & 1056 /* EnumLike */ ? nodeBuilder.symbolToExpression(type.symbol, 111551 /* Value */, enclosing, /*flags*/ + void 0, tracker) : type === trueType ? factory.createTrue() : type === falseType && factory.createFalse(); + if (enumResult) return enumResult; const literalValue = type.value; return typeof literalValue === "object" ? factory.createBigIntLiteral(literalValue) : typeof literalValue === "number" ? factory.createNumericLiteral(literalValue) : factory.createStringLiteral(literalValue); } @@ -84855,8 +78504,10 @@ ${lanes.join("\n")} const resolvedTypeReferenceDirectives = host.getResolvedTypeReferenceDirectives(); let fileToDirective; if (resolvedTypeReferenceDirectives) { - fileToDirective = /* @__PURE__ */ new Map(); - resolvedTypeReferenceDirectives.forEach(({ resolvedTypeReferenceDirective }, key, mode) => { + fileToDirective = /* @__PURE__ */new Map(); + resolvedTypeReferenceDirectives.forEach(({ + resolvedTypeReferenceDirective + }, key, mode) => { if (!(resolvedTypeReferenceDirective == null ? void 0 : resolvedTypeReferenceDirective.resolvedFileName)) { return; } @@ -84871,7 +78522,7 @@ ${lanes.join("\n")} getReferencedImportDeclaration, getReferencedDeclarationWithCollidingName, isDeclarationWithCollidingName, - isValueAliasDeclaration: (nodeIn) => { + isValueAliasDeclaration: nodeIn => { const node = getParseTreeNode(nodeIn); return node && canCollectSymbolAliasAccessabilityData ? isValueAliasDeclaration(node) : true; }, @@ -84880,7 +78531,7 @@ ${lanes.join("\n")} const node = getParseTreeNode(nodeIn); return node && canCollectSymbolAliasAccessabilityData ? isReferencedAliasDeclaration(node, checkChildren) : true; }, - getNodeCheckFlags: (nodeIn) => { + getNodeCheckFlags: nodeIn => { const node = getParseTreeNode(nodeIn); return node ? getNodeCheckFlags(node) : 0; }, @@ -84897,7 +78548,7 @@ ${lanes.join("\n")} createLiteralConstValue, isSymbolAccessible, isEntityNameVisible, - getConstantValue: (nodeIn) => { + getConstantValue: nodeIn => { const node = getParseTreeNode(nodeIn, canHaveConstantValue); return node ? getConstantValue2(node) : void 0; }, @@ -84908,18 +78559,19 @@ ${lanes.join("\n")} isOptionalParameter, moduleExportsSomeValue, isArgumentsLocalBinding, - getExternalModuleFileFromDeclaration: (nodeIn) => { + getExternalModuleFileFromDeclaration: nodeIn => { const node = getParseTreeNode(nodeIn, hasPossibleExternalModuleReference); return node && getExternalModuleFileFromDeclaration(node); }, getTypeReferenceDirectivesForEntityName, getTypeReferenceDirectivesForSymbol, isLiteralConstDeclaration, - isLateBound: (nodeIn) => { + isLateBound: nodeIn => { const node = getParseTreeNode(nodeIn, isDeclaration); const symbol = node && getSymbolOfDeclaration(node); return !!(symbol && getCheckFlags(symbol) & 4096 /* Late */); }, + getJsxFactoryEntity, getJsxFragmentFactoryEntity, getAllAccessorDeclarations(accessor) { @@ -84937,12 +78589,8 @@ ${lanes.join("\n")} getAccessor }; }, - getSymbolOfExternalModuleSpecifier: (moduleName) => resolveExternalModuleNameWorker( - moduleName, - moduleName, - /*moduleNotFoundError*/ - void 0 - ), + getSymbolOfExternalModuleSpecifier: moduleName => resolveExternalModuleNameWorker(moduleName, moduleName, /*moduleNotFoundError*/ + void 0), isBindingCapturedByNode: (node, decl) => { const parseNode = getParseTreeNode(node); const parseDecl = getParseTreeNode(decl); @@ -84958,25 +78606,19 @@ ${lanes.join("\n")} return !sym.exports ? [] : nodeBuilder.symbolTableToDeclarationStatements(sym.exports, node, flags, tracker, bundled); }, isImportRequiredByAugmentation, - tryFindAmbientModule: (moduleReferenceExpression) => { + tryFindAmbientModule: moduleReferenceExpression => { const node = getParseTreeNode(moduleReferenceExpression); const moduleSpecifier = node && isStringLiteralLike(node) ? node.text : void 0; - return moduleSpecifier !== void 0 ? tryFindAmbientModule( - moduleSpecifier, - /*withAugmentations*/ - true - ) : void 0; + return moduleSpecifier !== void 0 ? tryFindAmbientModule(moduleSpecifier, /*withAugmentations*/ + true) : void 0; } }; 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 exports = getExportsOfModule(file.symbol); for (const s of arrayFrom(exports.values())) { if (s.mergeId) { @@ -84996,6 +78638,7 @@ ${lanes.join("\n")} function isInHeritageClause(node) { return node.parent && node.parent.kind === 233 /* ExpressionWithTypeArguments */ && node.parent.parent && node.parent.parent.kind === 298 /* HeritageClause */; } + function getTypeReferenceDirectivesForEntityName(node) { if (!fileToDirective) { return void 0; @@ -85009,12 +78652,9 @@ ${lanes.join("\n")} meaning = 111551 /* Value */ | 1048576 /* ExportValue */; } } - const symbol = resolveEntityName( - node, - meaning, - /*ignoreErrors*/ - true - ); + + const symbol = resolveEntityName(node, meaning, /*ignoreErrors*/ + true); return symbol && symbol !== unknownSymbol ? getTypeReferenceDirectivesForSymbol(symbol, meaning) : void 0; } function getTypeReferenceDirectivesForSymbol(symbol, meaning) { @@ -85060,10 +78700,11 @@ ${lanes.join("\n")} return false; } function addReferencedFilesToTypeDirective(file, key, mode) { - if (fileToDirective.has(file.path)) - return; + if (fileToDirective.has(file.path)) return; fileToDirective.set(file.path, [key, mode]); - for (const { fileName } of file.referencedFiles) { + for (const { + fileName + } of file.referencedFiles) { const resolvedFile = resolveTripleslashReference(fileName, file.fileName); const referencedFile = host.getSourceFile(resolvedFile); if (referencedFile) { @@ -85074,22 +78715,19 @@ ${lanes.join("\n")} } function getExternalModuleFileFromDeclaration(declaration) { const specifier = declaration.kind === 267 /* ModuleDeclaration */ ? tryCast(declaration.name, isStringLiteral) : getExternalModuleName(declaration); - const moduleSymbol = resolveExternalModuleNameWorker( - specifier, - specifier, - /*moduleNotFoundError*/ - void 0 - ); + const moduleSymbol = resolveExternalModuleNameWorker(specifier, specifier, /*moduleNotFoundError*/ + void 0); if (!moduleSymbol) { return void 0; } return getDeclarationOfKind(moduleSymbol, 312 /* SourceFile */); } + function initializeTypeChecker() { for (const file of host.getSourceFiles()) { bindSourceFile(file, compilerOptions); } - amalgamatedDuplicates = /* @__PURE__ */ new Map(); + amalgamatedDuplicates = /* @__PURE__ */new Map(); let augmentations; for (const file of host.getSourceFiles()) { if (file.redirectInfo) { @@ -85125,121 +78763,75 @@ ${lanes.join("\n")} if (augmentations) { for (const list of augmentations) { for (const augmentation of list) { - if (!isGlobalScopeAugmentation(augmentation.parent)) - continue; + if (!isGlobalScopeAugmentation(augmentation.parent)) continue; mergeModuleAugmentation(augmentation); } } } addToSymbolTable(globals, builtinGlobals, Diagnostics.Declaration_name_conflicts_with_built_in_global_identifier_0); getSymbolLinks(undefinedSymbol).type = undefinedWideningType; - getSymbolLinks(argumentsSymbol).type = getGlobalType( - "IArguments", - /*arity*/ - 0, - /*reportErrors*/ - true - ); + getSymbolLinks(argumentsSymbol).type = getGlobalType("IArguments", /*arity*/ + 0, /*reportErrors*/ + true); getSymbolLinks(unknownSymbol).type = errorType; getSymbolLinks(globalThisSymbol).type = createObjectType(16 /* Anonymous */, globalThisSymbol); - globalArrayType = getGlobalType( - "Array", - /*arity*/ - 1, - /*reportErrors*/ - true - ); - globalObjectType = getGlobalType( - "Object", - /*arity*/ - 0, - /*reportErrors*/ - true - ); - globalFunctionType = getGlobalType( - "Function", - /*arity*/ - 0, - /*reportErrors*/ - true - ); - globalCallableFunctionType = strictBindCallApply && getGlobalType( - "CallableFunction", - /*arity*/ - 0, - /*reportErrors*/ - true - ) || globalFunctionType; - globalNewableFunctionType = strictBindCallApply && getGlobalType( - "NewableFunction", - /*arity*/ - 0, - /*reportErrors*/ - true - ) || globalFunctionType; - globalStringType = getGlobalType( - "String", - /*arity*/ - 0, - /*reportErrors*/ - true - ); - globalNumberType = getGlobalType( - "Number", - /*arity*/ - 0, - /*reportErrors*/ - true - ); - globalBooleanType = getGlobalType( - "Boolean", - /*arity*/ - 0, - /*reportErrors*/ - true - ); - globalRegExpType = getGlobalType( - "RegExp", - /*arity*/ - 0, - /*reportErrors*/ - true - ); + globalArrayType = getGlobalType("Array", /*arity*/ + 1, /*reportErrors*/ + true); + globalObjectType = getGlobalType("Object", /*arity*/ + 0, /*reportErrors*/ + true); + globalFunctionType = getGlobalType("Function", /*arity*/ + 0, /*reportErrors*/ + true); + globalCallableFunctionType = strictBindCallApply && getGlobalType("CallableFunction", /*arity*/ + 0, /*reportErrors*/ + true) || globalFunctionType; + globalNewableFunctionType = strictBindCallApply && getGlobalType("NewableFunction", /*arity*/ + 0, /*reportErrors*/ + true) || globalFunctionType; + globalStringType = getGlobalType("String", /*arity*/ + 0, /*reportErrors*/ + true); + globalNumberType = getGlobalType("Number", /*arity*/ + 0, /*reportErrors*/ + true); + globalBooleanType = getGlobalType("Boolean", /*arity*/ + 0, /*reportErrors*/ + true); + globalRegExpType = getGlobalType("RegExp", /*arity*/ + 0, /*reportErrors*/ + true); anyArrayType = createArrayType(anyType); autoArrayType = createArrayType(autoType); if (autoArrayType === emptyObjectType) { - autoArrayType = createAnonymousType( - /*symbol*/ - void 0, - emptySymbols, - emptyArray, - emptyArray, - emptyArray - ); + autoArrayType = createAnonymousType( /*symbol*/ + void 0, emptySymbols, emptyArray, emptyArray, emptyArray); } - globalReadonlyArrayType = getGlobalTypeOrUndefined( - "ReadonlyArray", - /*arity*/ - 1 - ) || globalArrayType; + globalReadonlyArrayType = getGlobalTypeOrUndefined("ReadonlyArray", /*arity*/ + 1) || globalArrayType; anyReadonlyArrayType = globalReadonlyArrayType ? createTypeFromGenericGlobalType(globalReadonlyArrayType, [anyType]) : anyArrayType; - globalThisType = getGlobalTypeOrUndefined( - "ThisType", - /*arity*/ - 1 - ); + globalThisType = getGlobalTypeOrUndefined("ThisType", /*arity*/ + 1); if (augmentations) { for (const list of augmentations) { for (const augmentation of list) { - if (isGlobalScopeAugmentation(augmentation.parent)) - continue; + if (isGlobalScopeAugmentation(augmentation.parent)) continue; mergeModuleAugmentation(augmentation); } } } - amalgamatedDuplicates.forEach(({ firstFile, secondFile, conflictingSymbols }) => { + amalgamatedDuplicates.forEach(({ + firstFile, + secondFile, + conflictingSymbols + }) => { if (conflictingSymbols.size < 8) { - conflictingSymbols.forEach(({ isBlockScoped, firstFileLocations, secondFileLocations }, symbolName2) => { + conflictingSymbols.forEach(({ + isBlockScoped, + firstFileLocations, + secondFileLocations + }, symbolName2) => { const message = isBlockScoped ? Diagnostics.Cannot_redeclare_block_scoped_variable_0 : Diagnostics.Duplicate_identifier_0; for (const node of firstFileLocations) { addDuplicateDeclarationError(node, message, symbolName2, secondFileLocations); @@ -85250,14 +78842,8 @@ ${lanes.join("\n")} }); } else { const list = arrayFrom(conflictingSymbols.keys()).join(", "); - diagnostics.add(addRelatedInfo( - createDiagnosticForNode(firstFile, Diagnostics.Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0, list), - createDiagnosticForNode(secondFile, Diagnostics.Conflicts_are_in_this_file) - )); - diagnostics.add(addRelatedInfo( - createDiagnosticForNode(secondFile, Diagnostics.Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0, list), - createDiagnosticForNode(firstFile, Diagnostics.Conflicts_are_in_this_file) - )); + diagnostics.add(addRelatedInfo(createDiagnosticForNode(firstFile, Diagnostics.Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0, list), createDiagnosticForNode(secondFile, Diagnostics.Conflicts_are_in_this_file))); + diagnostics.add(addRelatedInfo(createDiagnosticForNode(secondFile, Diagnostics.Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0, list), createDiagnosticForNode(firstFile, Diagnostics.Conflicts_are_in_this_file))); } }); amalgamatedDuplicates = void 0; @@ -85272,22 +78858,21 @@ ${lanes.join("\n")} for (let helper = 1 /* FirstEmitHelper */; helper <= 33554432 /* LastEmitHelper */; helper <<= 1) { if (uncheckedHelpers & helper) { for (const name of getHelperNames(helper)) { - if (requestedExternalEmitHelperNames.has(name)) - continue; + 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)) { + 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)) { + 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)) { + 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); } } @@ -85378,6 +78963,7 @@ ${lanes.join("\n")} let hasLeadingDecorators = false; for (const modifier of node.modifiers) { if (isDecorator(modifier)) { + var _firstDecorator; if (!nodeCanBeDecorated(legacyDecorators, node, node.parent, node.parent.parent)) { if (node.kind === 174 /* MethodDeclaration */ && !nodeIsPresent(node.body)) { return grammarErrorOnFirstToken(node, Diagnostics.A_decorator_can_only_decorate_a_method_implementation_not_an_overload); @@ -85397,10 +78983,7 @@ ${lanes.join("\n")} Debug.assertIsDefined(firstDecorator); const sourceFile = getSourceFileOfNode(modifier); if (!hasParseDiagnostics(sourceFile)) { - addRelatedInfo( - error2(modifier, Diagnostics.Decorators_may_not_appear_after_export_or_export_default_if_they_also_appear_before_export), - createDiagnosticForNode(firstDecorator, Diagnostics.Decorator_used_before_export_here) - ); + addRelatedInfo(error2(modifier, Diagnostics.Decorators_may_not_appear_after_export_or_export_default_if_they_also_appear_before_export), createDiagnosticForNode(firstDecorator, Diagnostics.Decorator_used_before_export_here)); return true; } return false; @@ -85411,7 +78994,7 @@ ${lanes.join("\n")} } else if (flags & 32 /* Export */) { sawExportBeforeDecorators = true; } - firstDecorator ?? (firstDecorator = modifier); + (_firstDecorator = firstDecorator) !== null && _firstDecorator !== void 0 ? _firstDecorator : firstDecorator = modifier; } else { if (modifier.kind !== 148 /* ReadonlyKeyword */) { if (node.kind === 171 /* PropertySignature */ || node.kind === 173 /* MethodSignature */) { @@ -85431,6 +79014,7 @@ ${lanes.join("\n")} if (node.kind !== 266 /* EnumDeclaration */ && node.kind !== 168 /* TypeParameter */) { return grammarErrorOnNode(node, Diagnostics.A_class_member_cannot_have_the_0_keyword, tokenToString(87 /* ConstKeyword */)); } + const parent2 = node.parent; if (node.kind === 168 /* TypeParameter */ && !(isFunctionLikeDeclaration(parent2) || isClassLike(parent2) || isFunctionTypeNode(parent2) || isConstructorTypeNode(parent2) || isCallSignatureDeclaration(parent2) || isConstructSignatureDeclaration(parent2) || isMethodSignature(parent2))) { return grammarErrorOnNode(modifier, Diagnostics._0_modifier_can_only_appear_on_a_type_parameter_of_a_function_method_or_class, tokenToString(modifier.kind)); @@ -85524,7 +79108,8 @@ ${lanes.join("\n")} flags |= 8 /* Readonly */; break; case 95 /* ExportKeyword */: - if (compilerOptions.verbatimModuleSyntax && !(node.flags & 33554432 /* Ambient */) && node.kind !== 265 /* TypeAliasDeclaration */ && node.kind !== 264 /* InterfaceDeclaration */ && // ModuleDeclaration needs to be checked that it is uninstantiated later + if (compilerOptions.verbatimModuleSyntax && !(node.flags & 33554432 /* Ambient */) && node.kind !== 265 /* TypeAliasDeclaration */ && node.kind !== 264 /* InterfaceDeclaration */ && + // ModuleDeclaration needs to be checked that it is uninstantiated later node.kind !== 267 /* ModuleDeclaration */ && node.parent.kind === 312 /* SourceFile */ && (moduleKind === 1 /* CommonJS */ || getSourceFileOfNode(node).impliedNodeFormat === 1 /* CommonJS */)) { return grammarErrorOnNode(modifier, Diagnostics.A_top_level_export_modifier_cannot_be_used_on_value_declarations_in_a_CommonJS_module_when_verbatimModuleSyntax_is_enabled); } @@ -85676,8 +79261,7 @@ ${lanes.join("\n")} 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); } @@ -85794,7 +79378,7 @@ ${lanes.join("\n")} } } function getNonSimpleParameters(parameters) { - return filter(parameters, (parameter) => !!parameter.initializer || isBindingPattern(parameter.name) || isRestParameter(parameter)); + return filter(parameters, parameter => !!parameter.initializer || isBindingPattern(parameter.name) || isRestParameter(parameter)); } function checkGrammarForUseStrictSimpleParameterList(node) { if (languageVersion >= 3 /* ES2016 */) { @@ -85802,11 +79386,8 @@ ${lanes.join("\n")} if (useStrictDirective) { const nonSimpleParameters = getNonSimpleParameters(node.parameters); if (length(nonSimpleParameters)) { - forEach(nonSimpleParameters, (parameter) => { - addRelatedInfo( - error2(parameter, Diagnostics.This_parameter_is_not_allowed_with_use_strict_directive), - createDiagnosticForNode(useStrictDirective, Diagnostics.use_strict_directive_used_here) - ); + forEach(nonSimpleParameters, parameter => { + addRelatedInfo(error2(parameter, Diagnostics.This_parameter_is_not_allowed_with_use_strict_directive), createDiagnosticForNode(useStrictDirective, Diagnostics.use_strict_directive_used_here)); }); const diagnostics2 = nonSimpleParameters.map((parameter, index) => index === 0 ? createDiagnosticForNode(parameter, Diagnostics.Non_simple_parameter_declared_here) : createDiagnosticForNode(parameter, Diagnostics.and_here)); addRelatedInfo(error2(useStrictDirective, Diagnostics.use_strict_directive_cannot_be_used_with_non_simple_parameter_list), ...diagnostics2); @@ -85833,7 +79414,9 @@ ${lanes.join("\n")} grammarErrorOnNode(node.typeParameters[0], Diagnostics.This_syntax_is_reserved_in_files_with_the_mts_or_cts_extension_Add_a_trailing_comma_or_explicit_constraint); } } - const { equalsGreaterThanToken } = node; + const { + equalsGreaterThanToken + } = node; const startLine = getLineAndCharacterOfPosition(file, equalsGreaterThanToken.pos).line; const endLine = getLineAndCharacterOfPosition(file, equalsGreaterThanToken.end).line; return startLine !== endLine && grammarErrorOnNode(equalsGreaterThanToken, Diagnostics.Line_terminator_not_permitted_before_arrow); @@ -85864,7 +79447,7 @@ ${lanes.join("\n")} return grammarErrorOnNode(parameter.name, Diagnostics.An_index_signature_parameter_must_have_a_type_annotation); } const type = getTypeFromTypeNode(parameter.type); - if (someType(type, (t) => !!(t.flags & 8576 /* StringOrNumberLiteralOrUnique */)) || isGenericType(type)) { + if (someType(type, t => !!(t.flags & 8576 /* StringOrNumberLiteralOrUnique */)) || isGenericType(type)) { return grammarErrorOnNode(parameter.name, Diagnostics.An_index_signature_parameter_type_cannot_be_a_literal_type_or_generic_type_Consider_using_a_mapped_object_type_instead); } if (!everyType(type, isValidIndexKeyType)) { @@ -85970,9 +79553,8 @@ ${lanes.join("\n")} } function checkGrammarForGenerator(node) { if (node.asteriskToken) { - Debug.assert( - node.kind === 262 /* FunctionDeclaration */ || node.kind === 218 /* FunctionExpression */ || node.kind === 174 /* MethodDeclaration */ - ); + Debug.assert(node.kind === 262 /* FunctionDeclaration */ || node.kind === 218 /* FunctionExpression */ || node.kind === 174 /* MethodDeclaration */); + if (node.flags & 33554432 /* Ambient */) { return grammarErrorOnNode(node.asteriskToken, Diagnostics.Generators_are_not_allowed_in_an_ambient_context); } @@ -85988,7 +79570,7 @@ ${lanes.join("\n")} return !!exclamationToken && grammarErrorOnNode(exclamationToken, message); } function checkGrammarObjectLiteralExpression(node, inDestructuring) { - const seen = /* @__PURE__ */ new Map(); + const seen = /* @__PURE__ */new Map(); for (const prop of node.properties) { if (prop.kind === 305 /* SpreadAssignment */) { if (inDestructuring) { @@ -86074,12 +79656,15 @@ ${lanes.join("\n")} function checkGrammarJsxElement(node) { checkGrammarJsxName(node.tagName); checkGrammarTypeArguments(node, node.typeArguments); - const seen = /* @__PURE__ */ new Map(); + const seen = /* @__PURE__ */new Map(); for (const attr of node.attributes.properties) { if (attr.kind === 293 /* JsxSpreadAttribute */) { continue; } - const { name, initializer } = attr; + const { + name, + initializer + } = attr; const escapedText = getEscapedTextOfJsxAttributeName(name); if (!seen.get(escapedText)) { seen.set(escapedText, true); @@ -86120,9 +79705,7 @@ ${lanes.join("\n")} case 100 /* Node16 */: case 199 /* NodeNext */: if (sourceFile.impliedNodeFormat === 1 /* CommonJS */) { - diagnostics.add( - createDiagnosticForNode(forInOrOfStatement.awaitModifier, Diagnostics.The_current_file_is_a_CommonJS_module_and_cannot_use_await_at_the_top_level) - ); + diagnostics.add(createDiagnosticForNode(forInOrOfStatement.awaitModifier, Diagnostics.The_current_file_is_a_CommonJS_module_and_cannot_use_await_at_the_top_level)); break; } case 7 /* ES2022 */: @@ -86132,9 +79715,7 @@ ${lanes.join("\n")} break; } default: - diagnostics.add( - createDiagnosticForNode(forInOrOfStatement.awaitModifier, Diagnostics.Top_level_for_await_loops_are_only_allowed_when_the_module_option_is_set_to_es2022_esnext_system_node16_or_nodenext_and_the_target_option_is_set_to_es2017_or_higher) - ); + diagnostics.add(createDiagnosticForNode(forInOrOfStatement.awaitModifier, Diagnostics.Top_level_for_await_loops_are_only_allowed_when_the_module_option_is_set_to_es2022_esnext_system_node16_or_nodenext_and_the_target_option_is_set_to_es2017_or_higher)); break; } } @@ -86206,10 +79787,7 @@ ${lanes.join("\n")} return grammarErrorOnNode(accessor.name, Diagnostics.An_accessor_cannot_have_type_parameters); } if (!doesAccessorHaveCorrectParameterCount(accessor)) { - return grammarErrorOnNode( - accessor.name, - accessor.kind === 177 /* GetAccessor */ ? Diagnostics.A_get_accessor_cannot_have_parameters : Diagnostics.A_set_accessor_must_have_exactly_one_parameter - ); + return grammarErrorOnNode(accessor.name, accessor.kind === 177 /* GetAccessor */ ? Diagnostics.A_get_accessor_cannot_have_parameters : Diagnostics.A_set_accessor_must_have_exactly_one_parameter); } if (accessor.kind === 178 /* SetAccessor */) { if (accessor.type) { @@ -86241,6 +79819,7 @@ ${lanes.join("\n")} if (node.type.kind !== 155 /* SymbolKeyword */) { return grammarErrorOnNode(node.type, Diagnostics._0_expected, tokenToString(155 /* SymbolKeyword */)); } + let parent2 = walkUpParenthesizedTypes(node.parent); if (isInJSFile(parent2) && isJSDocTypeExpression(parent2)) { const host2 = getJSDocHost(parent2); @@ -86280,6 +79859,7 @@ ${lanes.join("\n")} } } } + function checkGrammarForInvalidDynamicName(node, message) { if (isNonBindableDynamicName(node)) { return grammarErrorOnNode(node, message); @@ -86329,11 +79909,8 @@ ${lanes.join("\n")} switch (current.kind) { case 256 /* LabeledStatement */: if (node.label && current.label.escapedText === node.label.escapedText) { - const isMisplacedContinueLabel = node.kind === 251 /* ContinueStatement */ && !isIterationStatement( - current.statement, - /*lookInLabeledStatements*/ - true - ); + const isMisplacedContinueLabel = node.kind === 251 /* ContinueStatement */ && !isIterationStatement(current.statement, /*lookInLabeledStatements*/ + true); if (isMisplacedContinueLabel) { return grammarErrorOnNode(node, Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement); } @@ -86346,11 +79923,8 @@ ${lanes.join("\n")} } break; default: - if (isIterationStatement( - current, - /*lookInLabeledStatements*/ - false - ) && !node.label) { + if (isIterationStatement(current, /*lookInLabeledStatements*/ + false) && !node.label) { return false; } break; @@ -86383,14 +79957,17 @@ ${lanes.join("\n")} function isStringOrNumberLiteralExpression(expr) { return isStringOrNumericLiteralLike(expr) || expr.kind === 224 /* PrefixUnaryExpression */ && expr.operator === 41 /* MinusToken */ && expr.operand.kind === 9 /* NumericLiteral */; } + function isBigIntLiteralExpression(expr) { return expr.kind === 10 /* BigIntLiteral */ || expr.kind === 224 /* PrefixUnaryExpression */ && expr.operator === 41 /* MinusToken */ && expr.operand.kind === 10 /* BigIntLiteral */; } + function isSimpleLiteralEnumReference(expr) { if ((isPropertyAccessExpression(expr) || isElementAccessExpression(expr) && isStringOrNumberLiteralExpression(expr.argumentExpression)) && isEntityNameExpression(expr.expression)) { return !!(checkExpressionCached(expr).flags & 1056 /* EnumLike */); } } + function checkAmbientInitializer(node) { const initializer = node.initializer; if (initializer) { @@ -86482,10 +80059,7 @@ ${lanes.join("\n")} } const blockScopeFlags = declarationList.flags & 7 /* BlockScoped */; if ((blockScopeFlags === 4 /* Using */ || blockScopeFlags === 6 /* AwaitUsing */) && isForInStatement(declarationList.parent)) { - return grammarErrorOnNode( - declarationList, - blockScopeFlags === 4 /* Using */ ? Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_using_declaration : Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_an_await_using_declaration - ); + return grammarErrorOnNode(declarationList, blockScopeFlags === 4 /* Using */ ? Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_using_declaration : Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_an_await_using_declaration); } if (blockScopeFlags === 6 /* AwaitUsing */) { return checkAwaitGrammar(declarationList); @@ -86656,8 +80230,7 @@ ${lanes.join("\n")} if (!links2.hasReportedStatementInAmbientContext) { return links2.hasReportedStatementInAmbientContext = grammarErrorOnFirstToken(node, Diagnostics.Statements_are_not_allowed_in_ambient_contexts); } - } else { - } + } else {} } return false; } @@ -86671,11 +80244,8 @@ ${lanes.join("\n")} if (value <= 2 ** 53 - 1) { return; } - addErrorOrSuggestion( - /*isError*/ - false, - createDiagnosticForNode(node, Diagnostics.Numeric_literals_with_absolute_values_equal_to_2_53_or_greater_are_too_large_to_be_represented_accurately_as_integers) - ); + addErrorOrSuggestion( /*isError*/ + false, createDiagnosticForNode(node, Diagnostics.Numeric_literals_with_absolute_values_equal_to_2_53_or_greater_are_too_large_to_be_represented_accurately_as_integers)); } function checkGrammarBigIntLiteral(node) { const literalType = isLiteralTypeNode(node.parent) || isPrefixUnaryExpression(node.parent) && isLiteralTypeNode(node.parent.parent); @@ -86692,14 +80262,8 @@ ${lanes.join("\n")} const sourceFile = getSourceFileOfNode(node); if (!hasParseDiagnostics(sourceFile)) { const span = getSpanOfTokenAtPosition(sourceFile, node.pos); - diagnostics.add(createFileDiagnostic( - sourceFile, - textSpanEnd(span), - /*length*/ - 0, - message, - ...args - )); + diagnostics.add(createFileDiagnostic(sourceFile, textSpanEnd(span), /*length*/ + 0, message, ...args)); return true; } return false; @@ -86726,12 +80290,9 @@ ${lanes.join("\n")} return false; } function checkGrammarNamedImportsOrExports(namedBindings) { - return !!forEach(namedBindings.elements, (specifier) => { + return !!forEach(namedBindings.elements, specifier => { if (specifier.isTypeOnly) { - return grammarErrorOnFirstToken( - specifier, - specifier.kind === 276 /* ImportSpecifier */ ? Diagnostics.The_type_modifier_cannot_be_used_on_a_named_import_when_import_type_is_used_on_its_import_statement : Diagnostics.The_type_modifier_cannot_be_used_on_a_named_export_when_export_type_is_used_on_its_export_statement - ); + return grammarErrorOnFirstToken(specifier, specifier.kind === 276 /* ImportSpecifier */ ? Diagnostics.The_type_modifier_cannot_be_used_on_a_named_import_when_import_type_is_used_on_its_import_statement : Diagnostics.The_type_modifier_cannot_be_used_on_a_named_export_when_export_type_is_used_on_its_export_statement); } }); } @@ -86765,7 +80326,7 @@ ${lanes.join("\n")} function findMatchingTypeReferenceOrTypeAliasReference(source, unionTarget) { const sourceObjectFlags = getObjectFlags(source); if (sourceObjectFlags & (4 /* Reference */ | 16 /* Anonymous */) && unionTarget.flags & 1048576 /* Union */) { - return find(unionTarget.types, (target) => { + return find(unionTarget.types, target => { if (target.flags & 524288 /* Object */) { const overlapObjFlags = sourceObjectFlags & getObjectFlags(target); if (overlapObjFlags & 4 /* Reference */) { @@ -86781,14 +80342,14 @@ ${lanes.join("\n")} } function findBestTypeForObjectLiteral(source, unionTarget) { if (getObjectFlags(source) & 128 /* ObjectLiteral */ && someType(unionTarget, isArrayLikeType)) { - return find(unionTarget.types, (t) => !isArrayLikeType(t)); + return find(unionTarget.types, t => !isArrayLikeType(t)); } } function findBestTypeForInvokable(source, unionTarget) { let signatureKind = 0 /* Call */; const hasSignatures = getSignaturesOfType(source, signatureKind).length > 0 || (signatureKind = 1 /* Construct */, getSignaturesOfType(source, signatureKind).length > 0); if (hasSignatures) { - return find(unionTarget.types, (t) => getSignaturesOfType(t, signatureKind).length > 0); + return find(unionTarget.types, t => getSignaturesOfType(t, signatureKind).length > 0); } } function findMostOverlappyType(source, unionTarget) { @@ -86814,7 +80375,7 @@ ${lanes.join("\n")} } function filterPrimitivesIfContainsNonPrimitive(type) { if (maybeTypeOfKind(type, 67108864 /* NonPrimitive */)) { - const result = filterType(type, (t) => !(t.flags & 402784252 /* Primitive */)); + const result = filterType(type, t => !(t.flags & 402784252 /* Primitive */)); if (!(result.flags & 131072 /* Never */)) { return result; } @@ -86831,7 +80392,7 @@ ${lanes.join("\n")} if (sourceProperties) { const sourcePropertiesFiltered = findDiscriminantProperties(sourceProperties, target); if (sourcePropertiesFiltered) { - const discriminated = discriminateTypeByDiscriminableItems(target, map(sourcePropertiesFiltered, (p) => [() => getTypeOfSymbol(p), p.escapedName]), isRelatedTo); + const discriminated = discriminateTypeByDiscriminableItems(target, map(sourcePropertiesFiltered, p => [() => getTypeOfSymbol(p), p.escapedName]), isRelatedTo); if (discriminated !== target) { return discriminated; } @@ -86865,6 +80426,7 @@ ${lanes.join("\n")} return blockScopeKind === 2 /* Const */ || blockScopeKind === 4 /* Using */ || blockScopeKind === 6 /* AwaitUsing */; } } + function isNotAccessor(declaration) { return !isAccessor(declaration); } @@ -86893,9 +80455,11 @@ ${lanes.join("\n")} function signatureHasRestParameter(s) { return !!(s.flags & 1 /* HasRestParameter */); } + function signatureHasLiteralTypes(s) { return !!(s.flags & 2 /* HasLiteralTypes */); } + function createBasicNodeBuilderModuleSpecifierResolutionHost(host) { return { getCommonSourceDirectory: !!host.getCommonSourceDirectory ? () => host.getCommonSourceDirectory() : () => "", @@ -86907,17 +80471,18 @@ ${lanes.join("\n")} }, useCaseSensitiveFileNames: maybeBind(host, host.useCaseSensitiveFileNames), redirectTargetsMap: host.redirectTargetsMap, - getProjectReferenceRedirect: (fileName) => host.getProjectReferenceRedirect(fileName), - isSourceOfProjectReferenceRedirect: (fileName) => host.isSourceOfProjectReferenceRedirect(fileName), - fileExists: (fileName) => host.fileExists(fileName), + getProjectReferenceRedirect: fileName => host.getProjectReferenceRedirect(fileName), + isSourceOfProjectReferenceRedirect: fileName => host.isSourceOfProjectReferenceRedirect(fileName), + fileExists: fileName => host.fileExists(fileName), getFileIncludeReasons: () => host.getFileIncludeReasons(), - readFile: host.readFile ? (fileName) => host.readFile(fileName) : void 0 + readFile: host.readFile ? fileName => host.readFile(fileName) : void 0 }; } var ambientModuleSymbolRegex, anon, nextSymbolId, nextNodeId, nextMergeId, nextFlowId, TypeFacts, typeofNEFacts, CheckMode, SignatureCheckMode, isNotOverloadAndNotAccessor, intrinsicTypeKinds, SymbolLinks, JsxNames, SymbolTrackerImpl; var init_checker = __esm({ "src/compiler/checker.ts"() { "use strict"; + init_ts2(); init_ts_moduleSpecifiers(); init_ts_performance(); @@ -86927,7 +80492,7 @@ ${lanes.join("\n")} nextNodeId = 1; nextMergeId = 1; nextFlowId = 1; - TypeFacts = /* @__PURE__ */ ((TypeFacts3) => { + TypeFacts = /* @__PURE__ */(TypeFacts3 => { TypeFacts3[TypeFacts3["None"] = 0] = "None"; TypeFacts3[TypeFacts3["TypeofEQString"] = 1] = "TypeofEQString"; TypeFacts3[TypeFacts3["TypeofEQNumber"] = 2] = "TypeofEQNumber"; @@ -87016,7 +80581,8 @@ ${lanes.join("\n")} object: 8192 /* TypeofNEObject */, function: 16384 /* TypeofNEFunction */ })); - CheckMode = /* @__PURE__ */ ((CheckMode3) => { + + CheckMode = /* @__PURE__ */(CheckMode3 => { CheckMode3[CheckMode3["Normal"] = 0] = "Normal"; CheckMode3[CheckMode3["Contextual"] = 1] = "Contextual"; CheckMode3[CheckMode3["Inferential"] = 2] = "Inferential"; @@ -87027,7 +80593,7 @@ ${lanes.join("\n")} CheckMode3[CheckMode3["TypeOnly"] = 64] = "TypeOnly"; return CheckMode3; })(CheckMode || {}); - SignatureCheckMode = /* @__PURE__ */ ((SignatureCheckMode3) => { + SignatureCheckMode = /* @__PURE__ */(SignatureCheckMode3 => { SignatureCheckMode3[SignatureCheckMode3["None"] = 0] = "None"; SignatureCheckMode3[SignatureCheckMode3["BivariantCallback"] = 1] = "BivariantCallback"; SignatureCheckMode3[SignatureCheckMode3["StrictCallback"] = 2] = "StrictCallback"; @@ -87044,9 +80610,9 @@ ${lanes.join("\n")} Capitalize: 2 /* Capitalize */, Uncapitalize: 3 /* Uncapitalize */ })); - SymbolLinks = class { - }; - ((JsxNames2) => { + + SymbolLinks = class {}; + (JsxNames2 => { JsxNames2.JSX = "JSX"; JsxNames2.IntrinsicElements = "IntrinsicElements"; JsxNames2.ElementClass = "ElementClass"; @@ -87075,12 +80641,12 @@ ${lanes.join("\n")} trackSymbol(symbol, enclosingDeclaration, meaning) { var _a, _b; if (((_a = this.inner) == null ? void 0 : _a.trackSymbol) && !this.disableTrackSymbol) { + var _b$trackedSymbols; if (this.inner.trackSymbol(symbol, enclosingDeclaration, meaning)) { 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$trackedSymbols = (_b = this.context).trackedSymbols) !== null && _b$trackedSymbols !== void 0 ? _b$trackedSymbols : _b.trackedSymbols = []).push([symbol, enclosingDeclaration, meaning]); } return false; } @@ -87256,8 +80822,7 @@ ${lanes.join("\n")} 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) { @@ -87280,8 +80845,7 @@ ${lanes.join("\n")} 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; } } @@ -87294,81 +80858,23 @@ ${lanes.join("\n")} return parameter.dotDotDotToken ? parameter : isBindingPattern(parameter.name) ? addDefaultValueAssignmentForBindingPattern(parameter, context) : parameter.initializer ? addDefaultValueAssignmentForInitializer(parameter, parameter.name, parameter.initializer, context) : parameter; } function addDefaultValueAssignmentForBindingPattern(parameter, context) { - const { factory: factory2 } = context; - context.addInitializationStatement( - factory2.createVariableStatement( - /*modifiers*/ - void 0, - factory2.createVariableDeclarationList([ - factory2.createVariableDeclaration( - parameter.name, - /*exclamationToken*/ - void 0, - parameter.type, - parameter.initializer ? factory2.createConditionalExpression( - factory2.createStrictEquality( - factory2.getGeneratedNameForNode(parameter), - factory2.createVoidZero() - ), - /*questionToken*/ - void 0, - parameter.initializer, - /*colonToken*/ - void 0, - factory2.getGeneratedNameForNode(parameter) - ) : factory2.getGeneratedNameForNode(parameter) - ) - ]) - ) - ); - return factory2.updateParameterDeclaration( - parameter, - parameter.modifiers, - parameter.dotDotDotToken, - factory2.getGeneratedNameForNode(parameter), - parameter.questionToken, - parameter.type, - /*initializer*/ - void 0 - ); + const { + factory: factory2 + } = context; + context.addInitializationStatement(factory2.createVariableStatement( /*modifiers*/ + void 0, factory2.createVariableDeclarationList([factory2.createVariableDeclaration(parameter.name, /*exclamationToken*/ + void 0, parameter.type, parameter.initializer ? factory2.createConditionalExpression(factory2.createStrictEquality(factory2.getGeneratedNameForNode(parameter), factory2.createVoidZero()), /*questionToken*/ + void 0, parameter.initializer, /*colonToken*/ + void 0, factory2.getGeneratedNameForNode(parameter)) : factory2.getGeneratedNameForNode(parameter))]))); + return factory2.updateParameterDeclaration(parameter, parameter.modifiers, parameter.dotDotDotToken, factory2.getGeneratedNameForNode(parameter), parameter.questionToken, parameter.type, /*initializer*/ + void 0); } function addDefaultValueAssignmentForInitializer(parameter, name, initializer, context) { const factory2 = context.factory; - context.addInitializationStatement( - factory2.createIfStatement( - factory2.createTypeCheck(factory2.cloneNode(name), "undefined"), - setEmitFlags( - setTextRange( - factory2.createBlock([ - factory2.createExpressionStatement( - setEmitFlags( - setTextRange( - factory2.createAssignment( - setEmitFlags(factory2.cloneNode(name), 96 /* NoSourceMap */), - setEmitFlags(initializer, 96 /* NoSourceMap */ | getEmitFlags(initializer) | 3072 /* NoComments */) - ), - parameter - ), - 3072 /* NoComments */ - ) - ) - ]), - parameter - ), - 1 /* SingleLine */ | 64 /* NoTrailingSourceMap */ | 768 /* NoTokenSourceMaps */ | 3072 /* NoComments */ - ) - ) - ); - return factory2.updateParameterDeclaration( - parameter, - parameter.modifiers, - parameter.dotDotDotToken, - parameter.name, - parameter.questionToken, - parameter.type, - /*initializer*/ - void 0 - ); + context.addInitializationStatement(factory2.createIfStatement(factory2.createTypeCheck(factory2.cloneNode(name), "undefined"), setEmitFlags(setTextRange(factory2.createBlock([factory2.createExpressionStatement(setEmitFlags(setTextRange(factory2.createAssignment(setEmitFlags(factory2.cloneNode(name), 96 /* NoSourceMap */), setEmitFlags(initializer, 96 /* NoSourceMap */ | getEmitFlags(initializer) | 3072 /* NoComments */)), parameter), 3072 /* NoComments */))]), parameter), 1 /* SingleLine */ | 64 /* NoTrailingSourceMap */ | 768 /* NoTokenSourceMaps */ | 3072 /* NoComments */))); + + return factory2.updateParameterDeclaration(parameter, parameter.modifiers, parameter.dotDotDotToken, parameter.name, parameter.questionToken, parameter.type, /*initializer*/ + void 0); } function visitFunctionBody(node, visitor, context, nodeVisitor = visitNode) { context.resumeLexicalEnvironment(); @@ -87405,7 +80911,7 @@ ${lanes.join("\n")} } let i = 0; const length2 = elements.length; - return visitNodes2(elements, (node) => { + return visitNodes2(elements, node => { const discarded = i < length2 - 1; i++; return discarded ? discardVisitor(node) : visitor(node); @@ -87426,1039 +80932,432 @@ ${lanes.join("\n")} var init_visitorPublic = __esm({ "src/compiler/visitorPublic.ts"() { "use strict"; + init_ts2(); visitEachChildTable = { [166 /* QualifiedName */]: function visitEachChildOfQualifiedName(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateQualifiedName( - node, - Debug.checkDefined(nodeVisitor(node.left, visitor, isEntityName)), - Debug.checkDefined(nodeVisitor(node.right, visitor, isIdentifier)) - ); + return context.factory.updateQualifiedName(node, Debug.checkDefined(nodeVisitor(node.left, visitor, isEntityName)), Debug.checkDefined(nodeVisitor(node.right, visitor, isIdentifier))); }, [167 /* ComputedPropertyName */]: function visitEachChildOfComputedPropertyName(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateComputedPropertyName( - node, - Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)) - ); + return context.factory.updateComputedPropertyName(node, Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression))); }, // Signature elements [168 /* TypeParameter */]: function visitEachChildOfTypeParameterDeclaration(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateTypeParameterDeclaration( - node, - nodesVisitor(node.modifiers, visitor, isModifier), - Debug.checkDefined(nodeVisitor(node.name, visitor, isIdentifier)), - nodeVisitor(node.constraint, visitor, isTypeNode), - nodeVisitor(node.default, visitor, isTypeNode) - ); + return context.factory.updateTypeParameterDeclaration(node, nodesVisitor(node.modifiers, visitor, isModifier), Debug.checkDefined(nodeVisitor(node.name, visitor, isIdentifier)), nodeVisitor(node.constraint, visitor, isTypeNode), nodeVisitor(node.default, visitor, isTypeNode)); }, [169 /* Parameter */]: function visitEachChildOfParameterDeclaration(node, visitor, context, nodesVisitor, nodeVisitor, tokenVisitor) { - return context.factory.updateParameterDeclaration( - node, - nodesVisitor(node.modifiers, visitor, isModifierLike), - tokenVisitor ? nodeVisitor(node.dotDotDotToken, tokenVisitor, isDotDotDotToken) : node.dotDotDotToken, - Debug.checkDefined(nodeVisitor(node.name, visitor, isBindingName)), - tokenVisitor ? nodeVisitor(node.questionToken, tokenVisitor, isQuestionToken) : node.questionToken, - nodeVisitor(node.type, visitor, isTypeNode), - nodeVisitor(node.initializer, visitor, isExpression) - ); + return context.factory.updateParameterDeclaration(node, nodesVisitor(node.modifiers, visitor, isModifierLike), tokenVisitor ? nodeVisitor(node.dotDotDotToken, tokenVisitor, isDotDotDotToken) : node.dotDotDotToken, Debug.checkDefined(nodeVisitor(node.name, visitor, isBindingName)), tokenVisitor ? nodeVisitor(node.questionToken, tokenVisitor, isQuestionToken) : node.questionToken, nodeVisitor(node.type, visitor, isTypeNode), nodeVisitor(node.initializer, visitor, isExpression)); }, [170 /* Decorator */]: function visitEachChildOfDecorator(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateDecorator( - node, - Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)) - ); + return context.factory.updateDecorator(node, Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression))); }, // Type elements [171 /* PropertySignature */]: function visitEachChildOfPropertySignature(node, visitor, context, nodesVisitor, nodeVisitor, tokenVisitor) { - return context.factory.updatePropertySignature( - node, - nodesVisitor(node.modifiers, visitor, isModifier), - Debug.checkDefined(nodeVisitor(node.name, visitor, isPropertyName)), - tokenVisitor ? nodeVisitor(node.questionToken, tokenVisitor, isQuestionToken) : node.questionToken, - nodeVisitor(node.type, visitor, isTypeNode) - ); + return context.factory.updatePropertySignature(node, nodesVisitor(node.modifiers, visitor, isModifier), Debug.checkDefined(nodeVisitor(node.name, visitor, isPropertyName)), tokenVisitor ? nodeVisitor(node.questionToken, tokenVisitor, isQuestionToken) : node.questionToken, nodeVisitor(node.type, visitor, isTypeNode)); }, [172 /* PropertyDeclaration */]: function visitEachChildOfPropertyDeclaration(node, visitor, context, nodesVisitor, nodeVisitor, tokenVisitor) { - return context.factory.updatePropertyDeclaration( - node, - nodesVisitor(node.modifiers, visitor, isModifierLike), - Debug.checkDefined(nodeVisitor(node.name, visitor, isPropertyName)), - // QuestionToken and ExclamationToken are mutually exclusive in PropertyDeclaration - tokenVisitor ? nodeVisitor(node.questionToken ?? node.exclamationToken, tokenVisitor, isQuestionOrExclamationToken) : node.questionToken ?? node.exclamationToken, - nodeVisitor(node.type, visitor, isTypeNode), - nodeVisitor(node.initializer, visitor, isExpression) - ); + var _node$questionToken5, _node$questionToken6; + return context.factory.updatePropertyDeclaration(node, nodesVisitor(node.modifiers, visitor, isModifierLike), Debug.checkDefined(nodeVisitor(node.name, visitor, isPropertyName)), + // QuestionToken and ExclamationToken are mutually exclusive in PropertyDeclaration + tokenVisitor ? nodeVisitor((_node$questionToken5 = node.questionToken) !== null && _node$questionToken5 !== void 0 ? _node$questionToken5 : node.exclamationToken, tokenVisitor, isQuestionOrExclamationToken) : (_node$questionToken6 = node.questionToken) !== null && _node$questionToken6 !== void 0 ? _node$questionToken6 : node.exclamationToken, nodeVisitor(node.type, visitor, isTypeNode), nodeVisitor(node.initializer, visitor, isExpression)); }, [173 /* MethodSignature */]: function visitEachChildOfMethodSignature(node, visitor, context, nodesVisitor, nodeVisitor, tokenVisitor) { - return context.factory.updateMethodSignature( - node, - nodesVisitor(node.modifiers, visitor, isModifier), - Debug.checkDefined(nodeVisitor(node.name, visitor, isPropertyName)), - tokenVisitor ? nodeVisitor(node.questionToken, tokenVisitor, isQuestionToken) : node.questionToken, - nodesVisitor(node.typeParameters, visitor, isTypeParameterDeclaration), - nodesVisitor(node.parameters, visitor, isParameter), - nodeVisitor(node.type, visitor, isTypeNode) - ); + return context.factory.updateMethodSignature(node, nodesVisitor(node.modifiers, visitor, isModifier), Debug.checkDefined(nodeVisitor(node.name, visitor, isPropertyName)), tokenVisitor ? nodeVisitor(node.questionToken, tokenVisitor, isQuestionToken) : node.questionToken, nodesVisitor(node.typeParameters, visitor, isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, isParameter), nodeVisitor(node.type, visitor, isTypeNode)); }, [174 /* MethodDeclaration */]: function visitEachChildOfMethodDeclaration(node, visitor, context, nodesVisitor, nodeVisitor, tokenVisitor) { - return context.factory.updateMethodDeclaration( - node, - nodesVisitor(node.modifiers, visitor, isModifierLike), - tokenVisitor ? nodeVisitor(node.asteriskToken, tokenVisitor, isAsteriskToken) : node.asteriskToken, - Debug.checkDefined(nodeVisitor(node.name, visitor, isPropertyName)), - tokenVisitor ? nodeVisitor(node.questionToken, tokenVisitor, isQuestionToken) : node.questionToken, - nodesVisitor(node.typeParameters, visitor, isTypeParameterDeclaration), - visitParameterList(node.parameters, visitor, context, nodesVisitor), - nodeVisitor(node.type, visitor, isTypeNode), - visitFunctionBody(node.body, visitor, context, nodeVisitor) - ); + return context.factory.updateMethodDeclaration(node, nodesVisitor(node.modifiers, visitor, isModifierLike), tokenVisitor ? nodeVisitor(node.asteriskToken, tokenVisitor, isAsteriskToken) : node.asteriskToken, Debug.checkDefined(nodeVisitor(node.name, visitor, isPropertyName)), tokenVisitor ? nodeVisitor(node.questionToken, tokenVisitor, isQuestionToken) : node.questionToken, nodesVisitor(node.typeParameters, visitor, isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, isTypeNode), visitFunctionBody(node.body, visitor, context, nodeVisitor)); }, [176 /* Constructor */]: function visitEachChildOfConstructorDeclaration(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateConstructorDeclaration( - node, - nodesVisitor(node.modifiers, visitor, isModifierLike), - visitParameterList(node.parameters, visitor, context, nodesVisitor), - visitFunctionBody(node.body, visitor, context, nodeVisitor) - ); + return context.factory.updateConstructorDeclaration(node, nodesVisitor(node.modifiers, visitor, isModifierLike), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context, nodeVisitor)); }, [177 /* GetAccessor */]: function visitEachChildOfGetAccessorDeclaration(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateGetAccessorDeclaration( - node, - nodesVisitor(node.modifiers, visitor, isModifierLike), - Debug.checkDefined(nodeVisitor(node.name, visitor, isPropertyName)), - visitParameterList(node.parameters, visitor, context, nodesVisitor), - nodeVisitor(node.type, visitor, isTypeNode), - visitFunctionBody(node.body, visitor, context, nodeVisitor) - ); + return context.factory.updateGetAccessorDeclaration(node, nodesVisitor(node.modifiers, visitor, isModifierLike), Debug.checkDefined(nodeVisitor(node.name, visitor, isPropertyName)), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, isTypeNode), visitFunctionBody(node.body, visitor, context, nodeVisitor)); }, [178 /* SetAccessor */]: function visitEachChildOfSetAccessorDeclaration(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateSetAccessorDeclaration( - node, - nodesVisitor(node.modifiers, visitor, isModifierLike), - Debug.checkDefined(nodeVisitor(node.name, visitor, isPropertyName)), - visitParameterList(node.parameters, visitor, context, nodesVisitor), - visitFunctionBody(node.body, visitor, context, nodeVisitor) - ); + return context.factory.updateSetAccessorDeclaration(node, nodesVisitor(node.modifiers, visitor, isModifierLike), Debug.checkDefined(nodeVisitor(node.name, visitor, isPropertyName)), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context, nodeVisitor)); }, [175 /* ClassStaticBlockDeclaration */]: function visitEachChildOfClassStaticBlockDeclaration(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { context.startLexicalEnvironment(); context.suspendLexicalEnvironment(); - return context.factory.updateClassStaticBlockDeclaration( - node, - visitFunctionBody(node.body, visitor, context, nodeVisitor) - ); + return context.factory.updateClassStaticBlockDeclaration(node, visitFunctionBody(node.body, visitor, context, nodeVisitor)); }, [179 /* CallSignature */]: function visitEachChildOfCallSignatureDeclaration(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateCallSignature( - node, - nodesVisitor(node.typeParameters, visitor, isTypeParameterDeclaration), - nodesVisitor(node.parameters, visitor, isParameter), - nodeVisitor(node.type, visitor, isTypeNode) - ); + return context.factory.updateCallSignature(node, nodesVisitor(node.typeParameters, visitor, isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, isParameter), nodeVisitor(node.type, visitor, isTypeNode)); }, [180 /* ConstructSignature */]: function visitEachChildOfConstructSignatureDeclaration(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateConstructSignature( - node, - nodesVisitor(node.typeParameters, visitor, isTypeParameterDeclaration), - nodesVisitor(node.parameters, visitor, isParameter), - nodeVisitor(node.type, visitor, isTypeNode) - ); + return context.factory.updateConstructSignature(node, nodesVisitor(node.typeParameters, visitor, isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, isParameter), nodeVisitor(node.type, visitor, isTypeNode)); }, [181 /* IndexSignature */]: function visitEachChildOfIndexSignatureDeclaration(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateIndexSignature( - node, - nodesVisitor(node.modifiers, visitor, isModifierLike), - nodesVisitor(node.parameters, visitor, isParameter), - Debug.checkDefined(nodeVisitor(node.type, visitor, isTypeNode)) - ); + return context.factory.updateIndexSignature(node, nodesVisitor(node.modifiers, visitor, isModifierLike), nodesVisitor(node.parameters, visitor, isParameter), Debug.checkDefined(nodeVisitor(node.type, visitor, isTypeNode))); }, // Types [182 /* TypePredicate */]: function visitEachChildOfTypePredicateNode(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateTypePredicateNode( - node, - nodeVisitor(node.assertsModifier, visitor, isAssertsKeyword), - Debug.checkDefined(nodeVisitor(node.parameterName, visitor, isIdentifierOrThisTypeNode)), - nodeVisitor(node.type, visitor, isTypeNode) - ); + return context.factory.updateTypePredicateNode(node, nodeVisitor(node.assertsModifier, visitor, isAssertsKeyword), Debug.checkDefined(nodeVisitor(node.parameterName, visitor, isIdentifierOrThisTypeNode)), nodeVisitor(node.type, visitor, isTypeNode)); }, [183 /* TypeReference */]: function visitEachChildOfTypeReferenceNode(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateTypeReferenceNode( - node, - Debug.checkDefined(nodeVisitor(node.typeName, visitor, isEntityName)), - nodesVisitor(node.typeArguments, visitor, isTypeNode) - ); + return context.factory.updateTypeReferenceNode(node, Debug.checkDefined(nodeVisitor(node.typeName, visitor, isEntityName)), nodesVisitor(node.typeArguments, visitor, isTypeNode)); }, [184 /* FunctionType */]: function visitEachChildOfFunctionTypeNode(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateFunctionTypeNode( - node, - nodesVisitor(node.typeParameters, visitor, isTypeParameterDeclaration), - nodesVisitor(node.parameters, visitor, isParameter), - Debug.checkDefined(nodeVisitor(node.type, visitor, isTypeNode)) - ); + return context.factory.updateFunctionTypeNode(node, nodesVisitor(node.typeParameters, visitor, isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, isParameter), Debug.checkDefined(nodeVisitor(node.type, visitor, isTypeNode))); }, [185 /* ConstructorType */]: function visitEachChildOfConstructorTypeNode(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateConstructorTypeNode( - node, - nodesVisitor(node.modifiers, visitor, isModifier), - nodesVisitor(node.typeParameters, visitor, isTypeParameterDeclaration), - nodesVisitor(node.parameters, visitor, isParameter), - Debug.checkDefined(nodeVisitor(node.type, visitor, isTypeNode)) - ); + return context.factory.updateConstructorTypeNode(node, nodesVisitor(node.modifiers, visitor, isModifier), nodesVisitor(node.typeParameters, visitor, isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, isParameter), Debug.checkDefined(nodeVisitor(node.type, visitor, isTypeNode))); }, [186 /* TypeQuery */]: function visitEachChildOfTypeQueryNode(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateTypeQueryNode( - node, - Debug.checkDefined(nodeVisitor(node.exprName, visitor, isEntityName)), - nodesVisitor(node.typeArguments, visitor, isTypeNode) - ); + return context.factory.updateTypeQueryNode(node, Debug.checkDefined(nodeVisitor(node.exprName, visitor, isEntityName)), nodesVisitor(node.typeArguments, visitor, isTypeNode)); }, [187 /* TypeLiteral */]: function visitEachChildOfTypeLiteralNode(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) { - return context.factory.updateTypeLiteralNode( - node, - nodesVisitor(node.members, visitor, isTypeElement) - ); + return context.factory.updateTypeLiteralNode(node, nodesVisitor(node.members, visitor, isTypeElement)); }, [188 /* ArrayType */]: function visitEachChildOfArrayTypeNode(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateArrayTypeNode( - node, - Debug.checkDefined(nodeVisitor(node.elementType, visitor, isTypeNode)) - ); + return context.factory.updateArrayTypeNode(node, Debug.checkDefined(nodeVisitor(node.elementType, visitor, isTypeNode))); }, [189 /* TupleType */]: function visitEachChildOfTupleTypeNode(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) { - return context.factory.updateTupleTypeNode( - node, - nodesVisitor(node.elements, visitor, isTypeNode) - ); + return context.factory.updateTupleTypeNode(node, nodesVisitor(node.elements, visitor, isTypeNode)); }, [190 /* OptionalType */]: function visitEachChildOfOptionalTypeNode(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateOptionalTypeNode( - node, - Debug.checkDefined(nodeVisitor(node.type, visitor, isTypeNode)) - ); + return context.factory.updateOptionalTypeNode(node, Debug.checkDefined(nodeVisitor(node.type, visitor, isTypeNode))); }, [191 /* RestType */]: function visitEachChildOfRestTypeNode(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateRestTypeNode( - node, - Debug.checkDefined(nodeVisitor(node.type, visitor, isTypeNode)) - ); + return context.factory.updateRestTypeNode(node, Debug.checkDefined(nodeVisitor(node.type, visitor, isTypeNode))); }, [192 /* UnionType */]: function visitEachChildOfUnionTypeNode(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) { - return context.factory.updateUnionTypeNode( - node, - nodesVisitor(node.types, visitor, isTypeNode) - ); + return context.factory.updateUnionTypeNode(node, nodesVisitor(node.types, visitor, isTypeNode)); }, [193 /* IntersectionType */]: function visitEachChildOfIntersectionTypeNode(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) { - return context.factory.updateIntersectionTypeNode( - node, - nodesVisitor(node.types, visitor, isTypeNode) - ); + return context.factory.updateIntersectionTypeNode(node, nodesVisitor(node.types, visitor, isTypeNode)); }, [194 /* ConditionalType */]: function visitEachChildOfConditionalTypeNode(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateConditionalTypeNode( - node, - Debug.checkDefined(nodeVisitor(node.checkType, visitor, isTypeNode)), - Debug.checkDefined(nodeVisitor(node.extendsType, visitor, isTypeNode)), - Debug.checkDefined(nodeVisitor(node.trueType, visitor, isTypeNode)), - Debug.checkDefined(nodeVisitor(node.falseType, visitor, isTypeNode)) - ); + return context.factory.updateConditionalTypeNode(node, Debug.checkDefined(nodeVisitor(node.checkType, visitor, isTypeNode)), Debug.checkDefined(nodeVisitor(node.extendsType, visitor, isTypeNode)), Debug.checkDefined(nodeVisitor(node.trueType, visitor, isTypeNode)), Debug.checkDefined(nodeVisitor(node.falseType, visitor, isTypeNode))); }, [195 /* InferType */]: function visitEachChildOfInferTypeNode(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateInferTypeNode( - node, - Debug.checkDefined(nodeVisitor(node.typeParameter, visitor, isTypeParameterDeclaration)) - ); + return context.factory.updateInferTypeNode(node, Debug.checkDefined(nodeVisitor(node.typeParameter, visitor, isTypeParameterDeclaration))); }, [205 /* ImportType */]: function visitEachChildOfImportTypeNode(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateImportTypeNode( - node, - Debug.checkDefined(nodeVisitor(node.argument, visitor, isTypeNode)), - nodeVisitor(node.attributes, visitor, isImportAttributes), - nodeVisitor(node.qualifier, visitor, isEntityName), - nodesVisitor(node.typeArguments, visitor, isTypeNode), - node.isTypeOf - ); + return context.factory.updateImportTypeNode(node, Debug.checkDefined(nodeVisitor(node.argument, visitor, isTypeNode)), nodeVisitor(node.attributes, visitor, isImportAttributes), nodeVisitor(node.qualifier, visitor, isEntityName), nodesVisitor(node.typeArguments, visitor, isTypeNode), node.isTypeOf); }, [302 /* ImportTypeAssertionContainer */]: function visitEachChildOfImportTypeAssertionContainer(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateImportTypeAssertionContainer( - node, - Debug.checkDefined(nodeVisitor(node.assertClause, visitor, isAssertClause)), - node.multiLine - ); + return context.factory.updateImportTypeAssertionContainer(node, Debug.checkDefined(nodeVisitor(node.assertClause, visitor, isAssertClause)), node.multiLine); }, [202 /* NamedTupleMember */]: function visitEachChildOfNamedTupleMember(node, visitor, context, _nodesVisitor, nodeVisitor, tokenVisitor) { - return context.factory.updateNamedTupleMember( - node, - tokenVisitor ? nodeVisitor(node.dotDotDotToken, tokenVisitor, isDotDotDotToken) : node.dotDotDotToken, - Debug.checkDefined(nodeVisitor(node.name, visitor, isIdentifier)), - tokenVisitor ? nodeVisitor(node.questionToken, tokenVisitor, isQuestionToken) : node.questionToken, - Debug.checkDefined(nodeVisitor(node.type, visitor, isTypeNode)) - ); + return context.factory.updateNamedTupleMember(node, tokenVisitor ? nodeVisitor(node.dotDotDotToken, tokenVisitor, isDotDotDotToken) : node.dotDotDotToken, Debug.checkDefined(nodeVisitor(node.name, visitor, isIdentifier)), tokenVisitor ? nodeVisitor(node.questionToken, tokenVisitor, isQuestionToken) : node.questionToken, Debug.checkDefined(nodeVisitor(node.type, visitor, isTypeNode))); }, [196 /* ParenthesizedType */]: function visitEachChildOfParenthesizedType(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateParenthesizedType( - node, - Debug.checkDefined(nodeVisitor(node.type, visitor, isTypeNode)) - ); + return context.factory.updateParenthesizedType(node, Debug.checkDefined(nodeVisitor(node.type, visitor, isTypeNode))); }, [198 /* TypeOperator */]: function visitEachChildOfTypeOperatorNode(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateTypeOperatorNode( - node, - Debug.checkDefined(nodeVisitor(node.type, visitor, isTypeNode)) - ); + return context.factory.updateTypeOperatorNode(node, Debug.checkDefined(nodeVisitor(node.type, visitor, isTypeNode))); }, [199 /* IndexedAccessType */]: function visitEachChildOfIndexedAccessType(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateIndexedAccessTypeNode( - node, - Debug.checkDefined(nodeVisitor(node.objectType, visitor, isTypeNode)), - Debug.checkDefined(nodeVisitor(node.indexType, visitor, isTypeNode)) - ); + return context.factory.updateIndexedAccessTypeNode(node, Debug.checkDefined(nodeVisitor(node.objectType, visitor, isTypeNode)), Debug.checkDefined(nodeVisitor(node.indexType, visitor, isTypeNode))); }, [200 /* MappedType */]: function visitEachChildOfMappedType(node, visitor, context, nodesVisitor, nodeVisitor, tokenVisitor) { - return context.factory.updateMappedTypeNode( - node, - tokenVisitor ? nodeVisitor(node.readonlyToken, tokenVisitor, isReadonlyKeywordOrPlusOrMinusToken) : node.readonlyToken, - Debug.checkDefined(nodeVisitor(node.typeParameter, visitor, isTypeParameterDeclaration)), - nodeVisitor(node.nameType, visitor, isTypeNode), - tokenVisitor ? nodeVisitor(node.questionToken, tokenVisitor, isQuestionOrPlusOrMinusToken) : node.questionToken, - nodeVisitor(node.type, visitor, isTypeNode), - nodesVisitor(node.members, visitor, isTypeElement) - ); + return context.factory.updateMappedTypeNode(node, tokenVisitor ? nodeVisitor(node.readonlyToken, tokenVisitor, isReadonlyKeywordOrPlusOrMinusToken) : node.readonlyToken, Debug.checkDefined(nodeVisitor(node.typeParameter, visitor, isTypeParameterDeclaration)), nodeVisitor(node.nameType, visitor, isTypeNode), tokenVisitor ? nodeVisitor(node.questionToken, tokenVisitor, isQuestionOrPlusOrMinusToken) : node.questionToken, nodeVisitor(node.type, visitor, isTypeNode), nodesVisitor(node.members, visitor, isTypeElement)); }, [201 /* LiteralType */]: function visitEachChildOfLiteralTypeNode(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateLiteralTypeNode( - node, - Debug.checkDefined(nodeVisitor(node.literal, visitor, isLiteralTypeLiteral)) - ); + return context.factory.updateLiteralTypeNode(node, Debug.checkDefined(nodeVisitor(node.literal, visitor, isLiteralTypeLiteral))); }, [203 /* TemplateLiteralType */]: function visitEachChildOfTemplateLiteralType(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateTemplateLiteralType( - node, - Debug.checkDefined(nodeVisitor(node.head, visitor, isTemplateHead)), - nodesVisitor(node.templateSpans, visitor, isTemplateLiteralTypeSpan) - ); + return context.factory.updateTemplateLiteralType(node, Debug.checkDefined(nodeVisitor(node.head, visitor, isTemplateHead)), nodesVisitor(node.templateSpans, visitor, isTemplateLiteralTypeSpan)); }, [204 /* TemplateLiteralTypeSpan */]: function visitEachChildOfTemplateLiteralTypeSpan(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateTemplateLiteralTypeSpan( - node, - Debug.checkDefined(nodeVisitor(node.type, visitor, isTypeNode)), - Debug.checkDefined(nodeVisitor(node.literal, visitor, isTemplateMiddleOrTemplateTail)) - ); + return context.factory.updateTemplateLiteralTypeSpan(node, Debug.checkDefined(nodeVisitor(node.type, visitor, isTypeNode)), Debug.checkDefined(nodeVisitor(node.literal, visitor, isTemplateMiddleOrTemplateTail))); }, // Binding patterns [206 /* ObjectBindingPattern */]: function visitEachChildOfObjectBindingPattern(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) { - return context.factory.updateObjectBindingPattern( - node, - nodesVisitor(node.elements, visitor, isBindingElement) - ); + return context.factory.updateObjectBindingPattern(node, nodesVisitor(node.elements, visitor, isBindingElement)); }, [207 /* ArrayBindingPattern */]: function visitEachChildOfArrayBindingPattern(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) { - return context.factory.updateArrayBindingPattern( - node, - nodesVisitor(node.elements, visitor, isArrayBindingElement) - ); + return context.factory.updateArrayBindingPattern(node, nodesVisitor(node.elements, visitor, isArrayBindingElement)); }, [208 /* BindingElement */]: function visitEachChildOfBindingElement(node, visitor, context, _nodesVisitor, nodeVisitor, tokenVisitor) { - return context.factory.updateBindingElement( - node, - tokenVisitor ? nodeVisitor(node.dotDotDotToken, tokenVisitor, isDotDotDotToken) : node.dotDotDotToken, - nodeVisitor(node.propertyName, visitor, isPropertyName), - Debug.checkDefined(nodeVisitor(node.name, visitor, isBindingName)), - nodeVisitor(node.initializer, visitor, isExpression) - ); + return context.factory.updateBindingElement(node, tokenVisitor ? nodeVisitor(node.dotDotDotToken, tokenVisitor, isDotDotDotToken) : node.dotDotDotToken, nodeVisitor(node.propertyName, visitor, isPropertyName), Debug.checkDefined(nodeVisitor(node.name, visitor, isBindingName)), nodeVisitor(node.initializer, visitor, isExpression)); }, // Expression [209 /* ArrayLiteralExpression */]: function visitEachChildOfArrayLiteralExpression(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) { - return context.factory.updateArrayLiteralExpression( - node, - nodesVisitor(node.elements, visitor, isExpression) - ); + return context.factory.updateArrayLiteralExpression(node, nodesVisitor(node.elements, visitor, isExpression)); }, [210 /* ObjectLiteralExpression */]: function visitEachChildOfObjectLiteralExpression(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) { - return context.factory.updateObjectLiteralExpression( - node, - nodesVisitor(node.properties, visitor, isObjectLiteralElementLike) - ); + return context.factory.updateObjectLiteralExpression(node, nodesVisitor(node.properties, visitor, isObjectLiteralElementLike)); }, [211 /* PropertyAccessExpression */]: function visitEachChildOfPropertyAccessExpression(node, visitor, context, _nodesVisitor, nodeVisitor, tokenVisitor) { - return isPropertyAccessChain(node) ? context.factory.updatePropertyAccessChain( - node, - Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)), - tokenVisitor ? nodeVisitor(node.questionDotToken, tokenVisitor, isQuestionDotToken) : node.questionDotToken, - Debug.checkDefined(nodeVisitor(node.name, visitor, isMemberName)) - ) : context.factory.updatePropertyAccessExpression( - node, - Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)), - Debug.checkDefined(nodeVisitor(node.name, visitor, isMemberName)) - ); + return isPropertyAccessChain(node) ? context.factory.updatePropertyAccessChain(node, Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)), tokenVisitor ? nodeVisitor(node.questionDotToken, tokenVisitor, isQuestionDotToken) : node.questionDotToken, Debug.checkDefined(nodeVisitor(node.name, visitor, isMemberName))) : context.factory.updatePropertyAccessExpression(node, Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)), Debug.checkDefined(nodeVisitor(node.name, visitor, isMemberName))); }, [212 /* ElementAccessExpression */]: function visitEachChildOfElementAccessExpression(node, visitor, context, _nodesVisitor, nodeVisitor, tokenVisitor) { - return isElementAccessChain(node) ? context.factory.updateElementAccessChain( - node, - Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)), - tokenVisitor ? nodeVisitor(node.questionDotToken, tokenVisitor, isQuestionDotToken) : node.questionDotToken, - Debug.checkDefined(nodeVisitor(node.argumentExpression, visitor, isExpression)) - ) : context.factory.updateElementAccessExpression( - node, - Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)), - Debug.checkDefined(nodeVisitor(node.argumentExpression, visitor, isExpression)) - ); + return isElementAccessChain(node) ? context.factory.updateElementAccessChain(node, Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)), tokenVisitor ? nodeVisitor(node.questionDotToken, tokenVisitor, isQuestionDotToken) : node.questionDotToken, Debug.checkDefined(nodeVisitor(node.argumentExpression, visitor, isExpression))) : context.factory.updateElementAccessExpression(node, Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)), Debug.checkDefined(nodeVisitor(node.argumentExpression, visitor, isExpression))); }, [213 /* CallExpression */]: function visitEachChildOfCallExpression(node, visitor, context, nodesVisitor, nodeVisitor, tokenVisitor) { - return isCallChain(node) ? context.factory.updateCallChain( - node, - Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)), - tokenVisitor ? nodeVisitor(node.questionDotToken, tokenVisitor, isQuestionDotToken) : node.questionDotToken, - nodesVisitor(node.typeArguments, visitor, isTypeNode), - nodesVisitor(node.arguments, visitor, isExpression) - ) : context.factory.updateCallExpression( - node, - Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)), - nodesVisitor(node.typeArguments, visitor, isTypeNode), - nodesVisitor(node.arguments, visitor, isExpression) - ); + return isCallChain(node) ? context.factory.updateCallChain(node, Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)), tokenVisitor ? nodeVisitor(node.questionDotToken, tokenVisitor, isQuestionDotToken) : node.questionDotToken, nodesVisitor(node.typeArguments, visitor, isTypeNode), nodesVisitor(node.arguments, visitor, isExpression)) : context.factory.updateCallExpression(node, Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)), nodesVisitor(node.typeArguments, visitor, isTypeNode), nodesVisitor(node.arguments, visitor, isExpression)); }, [214 /* NewExpression */]: function visitEachChildOfNewExpression(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateNewExpression( - node, - Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)), - nodesVisitor(node.typeArguments, visitor, isTypeNode), - nodesVisitor(node.arguments, visitor, isExpression) - ); + return context.factory.updateNewExpression(node, Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)), nodesVisitor(node.typeArguments, visitor, isTypeNode), nodesVisitor(node.arguments, visitor, isExpression)); }, [215 /* TaggedTemplateExpression */]: function visitEachChildOfTaggedTemplateExpression(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateTaggedTemplateExpression( - node, - Debug.checkDefined(nodeVisitor(node.tag, visitor, isExpression)), - nodesVisitor(node.typeArguments, visitor, isTypeNode), - Debug.checkDefined(nodeVisitor(node.template, visitor, isTemplateLiteral)) - ); + return context.factory.updateTaggedTemplateExpression(node, Debug.checkDefined(nodeVisitor(node.tag, visitor, isExpression)), nodesVisitor(node.typeArguments, visitor, isTypeNode), Debug.checkDefined(nodeVisitor(node.template, visitor, isTemplateLiteral))); }, [216 /* TypeAssertionExpression */]: function visitEachChildOfTypeAssertionExpression(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateTypeAssertion( - node, - Debug.checkDefined(nodeVisitor(node.type, visitor, isTypeNode)), - Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)) - ); + return context.factory.updateTypeAssertion(node, Debug.checkDefined(nodeVisitor(node.type, visitor, isTypeNode)), Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression))); }, [217 /* ParenthesizedExpression */]: function visitEachChildOfParenthesizedExpression(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateParenthesizedExpression( - node, - Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)) - ); + return context.factory.updateParenthesizedExpression(node, Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression))); }, [218 /* FunctionExpression */]: function visitEachChildOfFunctionExpression(node, visitor, context, nodesVisitor, nodeVisitor, tokenVisitor) { - return context.factory.updateFunctionExpression( - node, - nodesVisitor(node.modifiers, visitor, isModifier), - tokenVisitor ? nodeVisitor(node.asteriskToken, tokenVisitor, isAsteriskToken) : node.asteriskToken, - nodeVisitor(node.name, visitor, isIdentifier), - nodesVisitor(node.typeParameters, visitor, isTypeParameterDeclaration), - visitParameterList(node.parameters, visitor, context, nodesVisitor), - nodeVisitor(node.type, visitor, isTypeNode), - visitFunctionBody(node.body, visitor, context, nodeVisitor) - ); + return context.factory.updateFunctionExpression(node, nodesVisitor(node.modifiers, visitor, isModifier), tokenVisitor ? nodeVisitor(node.asteriskToken, tokenVisitor, isAsteriskToken) : node.asteriskToken, nodeVisitor(node.name, visitor, isIdentifier), nodesVisitor(node.typeParameters, visitor, isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, isTypeNode), visitFunctionBody(node.body, visitor, context, nodeVisitor)); }, [219 /* ArrowFunction */]: function visitEachChildOfArrowFunction(node, visitor, context, nodesVisitor, nodeVisitor, tokenVisitor) { - return context.factory.updateArrowFunction( - node, - nodesVisitor(node.modifiers, visitor, isModifier), - nodesVisitor(node.typeParameters, visitor, isTypeParameterDeclaration), - visitParameterList(node.parameters, visitor, context, nodesVisitor), - nodeVisitor(node.type, visitor, isTypeNode), - tokenVisitor ? Debug.checkDefined(nodeVisitor(node.equalsGreaterThanToken, tokenVisitor, isEqualsGreaterThanToken)) : node.equalsGreaterThanToken, - visitFunctionBody(node.body, visitor, context, nodeVisitor) - ); + return context.factory.updateArrowFunction(node, nodesVisitor(node.modifiers, visitor, isModifier), nodesVisitor(node.typeParameters, visitor, isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, isTypeNode), tokenVisitor ? Debug.checkDefined(nodeVisitor(node.equalsGreaterThanToken, tokenVisitor, isEqualsGreaterThanToken)) : node.equalsGreaterThanToken, visitFunctionBody(node.body, visitor, context, nodeVisitor)); }, [220 /* DeleteExpression */]: function visitEachChildOfDeleteExpression(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateDeleteExpression( - node, - Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)) - ); + return context.factory.updateDeleteExpression(node, Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression))); }, [221 /* TypeOfExpression */]: function visitEachChildOfTypeOfExpression(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateTypeOfExpression( - node, - Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)) - ); + return context.factory.updateTypeOfExpression(node, Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression))); }, [222 /* VoidExpression */]: function visitEachChildOfVoidExpression(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateVoidExpression( - node, - Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)) - ); + return context.factory.updateVoidExpression(node, Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression))); }, [223 /* AwaitExpression */]: function visitEachChildOfAwaitExpression(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateAwaitExpression( - node, - Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)) - ); + return context.factory.updateAwaitExpression(node, Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression))); }, [224 /* PrefixUnaryExpression */]: function visitEachChildOfPrefixUnaryExpression(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updatePrefixUnaryExpression( - node, - Debug.checkDefined(nodeVisitor(node.operand, visitor, isExpression)) - ); + return context.factory.updatePrefixUnaryExpression(node, Debug.checkDefined(nodeVisitor(node.operand, visitor, isExpression))); }, [225 /* PostfixUnaryExpression */]: function visitEachChildOfPostfixUnaryExpression(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updatePostfixUnaryExpression( - node, - Debug.checkDefined(nodeVisitor(node.operand, visitor, isExpression)) - ); + return context.factory.updatePostfixUnaryExpression(node, Debug.checkDefined(nodeVisitor(node.operand, visitor, isExpression))); }, [226 /* BinaryExpression */]: function visitEachChildOfBinaryExpression(node, visitor, context, _nodesVisitor, nodeVisitor, tokenVisitor) { - return context.factory.updateBinaryExpression( - node, - Debug.checkDefined(nodeVisitor(node.left, visitor, isExpression)), - tokenVisitor ? Debug.checkDefined(nodeVisitor(node.operatorToken, tokenVisitor, isBinaryOperatorToken)) : node.operatorToken, - Debug.checkDefined(nodeVisitor(node.right, visitor, isExpression)) - ); + return context.factory.updateBinaryExpression(node, Debug.checkDefined(nodeVisitor(node.left, visitor, isExpression)), tokenVisitor ? Debug.checkDefined(nodeVisitor(node.operatorToken, tokenVisitor, isBinaryOperatorToken)) : node.operatorToken, Debug.checkDefined(nodeVisitor(node.right, visitor, isExpression))); }, [227 /* ConditionalExpression */]: function visitEachChildOfConditionalExpression(node, visitor, context, _nodesVisitor, nodeVisitor, tokenVisitor) { - return context.factory.updateConditionalExpression( - node, - Debug.checkDefined(nodeVisitor(node.condition, visitor, isExpression)), - tokenVisitor ? Debug.checkDefined(nodeVisitor(node.questionToken, tokenVisitor, isQuestionToken)) : node.questionToken, - Debug.checkDefined(nodeVisitor(node.whenTrue, visitor, isExpression)), - tokenVisitor ? Debug.checkDefined(nodeVisitor(node.colonToken, tokenVisitor, isColonToken)) : node.colonToken, - Debug.checkDefined(nodeVisitor(node.whenFalse, visitor, isExpression)) - ); + return context.factory.updateConditionalExpression(node, Debug.checkDefined(nodeVisitor(node.condition, visitor, isExpression)), tokenVisitor ? Debug.checkDefined(nodeVisitor(node.questionToken, tokenVisitor, isQuestionToken)) : node.questionToken, Debug.checkDefined(nodeVisitor(node.whenTrue, visitor, isExpression)), tokenVisitor ? Debug.checkDefined(nodeVisitor(node.colonToken, tokenVisitor, isColonToken)) : node.colonToken, Debug.checkDefined(nodeVisitor(node.whenFalse, visitor, isExpression))); }, [228 /* TemplateExpression */]: function visitEachChildOfTemplateExpression(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateTemplateExpression( - node, - Debug.checkDefined(nodeVisitor(node.head, visitor, isTemplateHead)), - nodesVisitor(node.templateSpans, visitor, isTemplateSpan) - ); + return context.factory.updateTemplateExpression(node, Debug.checkDefined(nodeVisitor(node.head, visitor, isTemplateHead)), nodesVisitor(node.templateSpans, visitor, isTemplateSpan)); }, [229 /* YieldExpression */]: function visitEachChildOfYieldExpression(node, visitor, context, _nodesVisitor, nodeVisitor, tokenVisitor) { - return context.factory.updateYieldExpression( - node, - tokenVisitor ? nodeVisitor(node.asteriskToken, tokenVisitor, isAsteriskToken) : node.asteriskToken, - nodeVisitor(node.expression, visitor, isExpression) - ); + return context.factory.updateYieldExpression(node, tokenVisitor ? nodeVisitor(node.asteriskToken, tokenVisitor, isAsteriskToken) : node.asteriskToken, nodeVisitor(node.expression, visitor, isExpression)); }, [230 /* SpreadElement */]: function visitEachChildOfSpreadElement(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateSpreadElement( - node, - Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)) - ); + return context.factory.updateSpreadElement(node, Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression))); }, [231 /* ClassExpression */]: function visitEachChildOfClassExpression(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateClassExpression( - node, - nodesVisitor(node.modifiers, visitor, isModifierLike), - nodeVisitor(node.name, visitor, isIdentifier), - nodesVisitor(node.typeParameters, visitor, isTypeParameterDeclaration), - nodesVisitor(node.heritageClauses, visitor, isHeritageClause), - nodesVisitor(node.members, visitor, isClassElement) - ); + return context.factory.updateClassExpression(node, nodesVisitor(node.modifiers, visitor, isModifierLike), nodeVisitor(node.name, visitor, isIdentifier), nodesVisitor(node.typeParameters, visitor, isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, isHeritageClause), nodesVisitor(node.members, visitor, isClassElement)); }, [233 /* ExpressionWithTypeArguments */]: function visitEachChildOfExpressionWithTypeArguments(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateExpressionWithTypeArguments( - node, - Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)), - nodesVisitor(node.typeArguments, visitor, isTypeNode) - ); + return context.factory.updateExpressionWithTypeArguments(node, Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)), nodesVisitor(node.typeArguments, visitor, isTypeNode)); }, [234 /* AsExpression */]: function visitEachChildOfAsExpression(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateAsExpression( - node, - Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)), - Debug.checkDefined(nodeVisitor(node.type, visitor, isTypeNode)) - ); + return context.factory.updateAsExpression(node, Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)), Debug.checkDefined(nodeVisitor(node.type, visitor, isTypeNode))); }, [238 /* SatisfiesExpression */]: function visitEachChildOfSatisfiesExpression(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateSatisfiesExpression( - node, - Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)), - Debug.checkDefined(nodeVisitor(node.type, visitor, isTypeNode)) - ); + return context.factory.updateSatisfiesExpression(node, Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)), Debug.checkDefined(nodeVisitor(node.type, visitor, isTypeNode))); }, [235 /* NonNullExpression */]: function visitEachChildOfNonNullExpression(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { - return isOptionalChain(node) ? context.factory.updateNonNullChain( - node, - Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)) - ) : context.factory.updateNonNullExpression( - node, - Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)) - ); + return isOptionalChain(node) ? context.factory.updateNonNullChain(node, Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression))) : context.factory.updateNonNullExpression(node, Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression))); }, [236 /* MetaProperty */]: function visitEachChildOfMetaProperty(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateMetaProperty( - node, - Debug.checkDefined(nodeVisitor(node.name, visitor, isIdentifier)) - ); + return context.factory.updateMetaProperty(node, Debug.checkDefined(nodeVisitor(node.name, visitor, isIdentifier))); }, // Misc [239 /* TemplateSpan */]: function visitEachChildOfTemplateSpan(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateTemplateSpan( - node, - Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)), - Debug.checkDefined(nodeVisitor(node.literal, visitor, isTemplateMiddleOrTemplateTail)) - ); + return context.factory.updateTemplateSpan(node, Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)), Debug.checkDefined(nodeVisitor(node.literal, visitor, isTemplateMiddleOrTemplateTail))); }, // Element [241 /* Block */]: function visitEachChildOfBlock(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) { - return context.factory.updateBlock( - node, - nodesVisitor(node.statements, visitor, isStatement) - ); + return context.factory.updateBlock(node, nodesVisitor(node.statements, visitor, isStatement)); }, [243 /* VariableStatement */]: function visitEachChildOfVariableStatement(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateVariableStatement( - node, - nodesVisitor(node.modifiers, visitor, isModifierLike), - Debug.checkDefined(nodeVisitor(node.declarationList, visitor, isVariableDeclarationList)) - ); + return context.factory.updateVariableStatement(node, nodesVisitor(node.modifiers, visitor, isModifierLike), Debug.checkDefined(nodeVisitor(node.declarationList, visitor, isVariableDeclarationList))); }, [244 /* ExpressionStatement */]: function visitEachChildOfExpressionStatement(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateExpressionStatement( - node, - Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)) - ); + return context.factory.updateExpressionStatement(node, Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression))); }, [245 /* IfStatement */]: function visitEachChildOfIfStatement(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateIfStatement( - node, - Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)), - Debug.checkDefined(nodeVisitor(node.thenStatement, visitor, isStatement, context.factory.liftToBlock)), - nodeVisitor(node.elseStatement, visitor, isStatement, context.factory.liftToBlock) - ); + return context.factory.updateIfStatement(node, Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)), Debug.checkDefined(nodeVisitor(node.thenStatement, visitor, isStatement, context.factory.liftToBlock)), nodeVisitor(node.elseStatement, visitor, isStatement, context.factory.liftToBlock)); }, [246 /* DoStatement */]: function visitEachChildOfDoStatement(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateDoStatement( - node, - visitIterationBody(node.statement, visitor, context, nodeVisitor), - Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)) - ); + return context.factory.updateDoStatement(node, visitIterationBody(node.statement, visitor, context, nodeVisitor), Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression))); }, [247 /* WhileStatement */]: function visitEachChildOfWhileStatement(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateWhileStatement( - node, - Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)), - visitIterationBody(node.statement, visitor, context, nodeVisitor) - ); + return context.factory.updateWhileStatement(node, Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)), visitIterationBody(node.statement, visitor, context, nodeVisitor)); }, [248 /* ForStatement */]: function visitEachChildOfForStatement(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateForStatement( - node, - nodeVisitor(node.initializer, visitor, isForInitializer), - nodeVisitor(node.condition, visitor, isExpression), - nodeVisitor(node.incrementor, visitor, isExpression), - visitIterationBody(node.statement, visitor, context, nodeVisitor) - ); + return context.factory.updateForStatement(node, nodeVisitor(node.initializer, visitor, isForInitializer), nodeVisitor(node.condition, visitor, isExpression), nodeVisitor(node.incrementor, visitor, isExpression), visitIterationBody(node.statement, visitor, context, nodeVisitor)); }, [249 /* ForInStatement */]: function visitEachChildOfForInStatement(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateForInStatement( - node, - Debug.checkDefined(nodeVisitor(node.initializer, visitor, isForInitializer)), - Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)), - visitIterationBody(node.statement, visitor, context, nodeVisitor) - ); + return context.factory.updateForInStatement(node, Debug.checkDefined(nodeVisitor(node.initializer, visitor, isForInitializer)), Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)), visitIterationBody(node.statement, visitor, context, nodeVisitor)); }, [250 /* ForOfStatement */]: function visitEachChildOfForOfStatement(node, visitor, context, _nodesVisitor, nodeVisitor, tokenVisitor) { - return context.factory.updateForOfStatement( - node, - tokenVisitor ? nodeVisitor(node.awaitModifier, tokenVisitor, isAwaitKeyword) : node.awaitModifier, - Debug.checkDefined(nodeVisitor(node.initializer, visitor, isForInitializer)), - Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)), - visitIterationBody(node.statement, visitor, context, nodeVisitor) - ); + return context.factory.updateForOfStatement(node, tokenVisitor ? nodeVisitor(node.awaitModifier, tokenVisitor, isAwaitKeyword) : node.awaitModifier, Debug.checkDefined(nodeVisitor(node.initializer, visitor, isForInitializer)), Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)), visitIterationBody(node.statement, visitor, context, nodeVisitor)); }, [251 /* ContinueStatement */]: function visitEachChildOfContinueStatement(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateContinueStatement( - node, - nodeVisitor(node.label, visitor, isIdentifier) - ); + return context.factory.updateContinueStatement(node, nodeVisitor(node.label, visitor, isIdentifier)); }, [252 /* BreakStatement */]: function visitEachChildOfBreakStatement(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateBreakStatement( - node, - nodeVisitor(node.label, visitor, isIdentifier) - ); + return context.factory.updateBreakStatement(node, nodeVisitor(node.label, visitor, isIdentifier)); }, [253 /* ReturnStatement */]: function visitEachChildOfReturnStatement(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateReturnStatement( - node, - nodeVisitor(node.expression, visitor, isExpression) - ); + return context.factory.updateReturnStatement(node, nodeVisitor(node.expression, visitor, isExpression)); }, [254 /* WithStatement */]: function visitEachChildOfWithStatement(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateWithStatement( - node, - Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)), - Debug.checkDefined(nodeVisitor(node.statement, visitor, isStatement, context.factory.liftToBlock)) - ); + return context.factory.updateWithStatement(node, Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)), Debug.checkDefined(nodeVisitor(node.statement, visitor, isStatement, context.factory.liftToBlock))); }, [255 /* SwitchStatement */]: function visitEachChildOfSwitchStatement(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateSwitchStatement( - node, - Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)), - Debug.checkDefined(nodeVisitor(node.caseBlock, visitor, isCaseBlock)) - ); + return context.factory.updateSwitchStatement(node, Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)), Debug.checkDefined(nodeVisitor(node.caseBlock, visitor, isCaseBlock))); }, [256 /* LabeledStatement */]: function visitEachChildOfLabeledStatement(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateLabeledStatement( - node, - Debug.checkDefined(nodeVisitor(node.label, visitor, isIdentifier)), - Debug.checkDefined(nodeVisitor(node.statement, visitor, isStatement, context.factory.liftToBlock)) - ); + return context.factory.updateLabeledStatement(node, Debug.checkDefined(nodeVisitor(node.label, visitor, isIdentifier)), Debug.checkDefined(nodeVisitor(node.statement, visitor, isStatement, context.factory.liftToBlock))); }, [257 /* ThrowStatement */]: function visitEachChildOfThrowStatement(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateThrowStatement( - node, - Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)) - ); + return context.factory.updateThrowStatement(node, Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression))); }, [258 /* TryStatement */]: function visitEachChildOfTryStatement(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateTryStatement( - node, - Debug.checkDefined(nodeVisitor(node.tryBlock, visitor, isBlock)), - nodeVisitor(node.catchClause, visitor, isCatchClause), - nodeVisitor(node.finallyBlock, visitor, isBlock) - ); + return context.factory.updateTryStatement(node, Debug.checkDefined(nodeVisitor(node.tryBlock, visitor, isBlock)), nodeVisitor(node.catchClause, visitor, isCatchClause), nodeVisitor(node.finallyBlock, visitor, isBlock)); }, [260 /* VariableDeclaration */]: function visitEachChildOfVariableDeclaration(node, visitor, context, _nodesVisitor, nodeVisitor, tokenVisitor) { - return context.factory.updateVariableDeclaration( - node, - Debug.checkDefined(nodeVisitor(node.name, visitor, isBindingName)), - tokenVisitor ? nodeVisitor(node.exclamationToken, tokenVisitor, isExclamationToken) : node.exclamationToken, - nodeVisitor(node.type, visitor, isTypeNode), - nodeVisitor(node.initializer, visitor, isExpression) - ); + return context.factory.updateVariableDeclaration(node, Debug.checkDefined(nodeVisitor(node.name, visitor, isBindingName)), tokenVisitor ? nodeVisitor(node.exclamationToken, tokenVisitor, isExclamationToken) : node.exclamationToken, nodeVisitor(node.type, visitor, isTypeNode), nodeVisitor(node.initializer, visitor, isExpression)); }, [261 /* VariableDeclarationList */]: function visitEachChildOfVariableDeclarationList(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) { - return context.factory.updateVariableDeclarationList( - node, - nodesVisitor(node.declarations, visitor, isVariableDeclaration) - ); + return context.factory.updateVariableDeclarationList(node, nodesVisitor(node.declarations, visitor, isVariableDeclaration)); }, [262 /* FunctionDeclaration */]: function visitEachChildOfFunctionDeclaration(node, visitor, context, nodesVisitor, nodeVisitor, tokenVisitor) { - return context.factory.updateFunctionDeclaration( - node, - nodesVisitor(node.modifiers, visitor, isModifier), - tokenVisitor ? nodeVisitor(node.asteriskToken, tokenVisitor, isAsteriskToken) : node.asteriskToken, - nodeVisitor(node.name, visitor, isIdentifier), - nodesVisitor(node.typeParameters, visitor, isTypeParameterDeclaration), - visitParameterList(node.parameters, visitor, context, nodesVisitor), - nodeVisitor(node.type, visitor, isTypeNode), - visitFunctionBody(node.body, visitor, context, nodeVisitor) - ); + return context.factory.updateFunctionDeclaration(node, nodesVisitor(node.modifiers, visitor, isModifier), tokenVisitor ? nodeVisitor(node.asteriskToken, tokenVisitor, isAsteriskToken) : node.asteriskToken, nodeVisitor(node.name, visitor, isIdentifier), nodesVisitor(node.typeParameters, visitor, isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, isTypeNode), visitFunctionBody(node.body, visitor, context, nodeVisitor)); }, [263 /* ClassDeclaration */]: function visitEachChildOfClassDeclaration(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateClassDeclaration( - node, - nodesVisitor(node.modifiers, visitor, isModifierLike), - nodeVisitor(node.name, visitor, isIdentifier), - nodesVisitor(node.typeParameters, visitor, isTypeParameterDeclaration), - nodesVisitor(node.heritageClauses, visitor, isHeritageClause), - nodesVisitor(node.members, visitor, isClassElement) - ); + return context.factory.updateClassDeclaration(node, nodesVisitor(node.modifiers, visitor, isModifierLike), nodeVisitor(node.name, visitor, isIdentifier), nodesVisitor(node.typeParameters, visitor, isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, isHeritageClause), nodesVisitor(node.members, visitor, isClassElement)); }, [264 /* InterfaceDeclaration */]: function visitEachChildOfInterfaceDeclaration(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateInterfaceDeclaration( - node, - nodesVisitor(node.modifiers, visitor, isModifierLike), - Debug.checkDefined(nodeVisitor(node.name, visitor, isIdentifier)), - nodesVisitor(node.typeParameters, visitor, isTypeParameterDeclaration), - nodesVisitor(node.heritageClauses, visitor, isHeritageClause), - nodesVisitor(node.members, visitor, isTypeElement) - ); + return context.factory.updateInterfaceDeclaration(node, nodesVisitor(node.modifiers, visitor, isModifierLike), Debug.checkDefined(nodeVisitor(node.name, visitor, isIdentifier)), nodesVisitor(node.typeParameters, visitor, isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, isHeritageClause), nodesVisitor(node.members, visitor, isTypeElement)); }, [265 /* TypeAliasDeclaration */]: function visitEachChildOfTypeAliasDeclaration(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateTypeAliasDeclaration( - node, - nodesVisitor(node.modifiers, visitor, isModifierLike), - Debug.checkDefined(nodeVisitor(node.name, visitor, isIdentifier)), - nodesVisitor(node.typeParameters, visitor, isTypeParameterDeclaration), - Debug.checkDefined(nodeVisitor(node.type, visitor, isTypeNode)) - ); + return context.factory.updateTypeAliasDeclaration(node, nodesVisitor(node.modifiers, visitor, isModifierLike), Debug.checkDefined(nodeVisitor(node.name, visitor, isIdentifier)), nodesVisitor(node.typeParameters, visitor, isTypeParameterDeclaration), Debug.checkDefined(nodeVisitor(node.type, visitor, isTypeNode))); }, [266 /* EnumDeclaration */]: function visitEachChildOfEnumDeclaration(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateEnumDeclaration( - node, - nodesVisitor(node.modifiers, visitor, isModifierLike), - Debug.checkDefined(nodeVisitor(node.name, visitor, isIdentifier)), - nodesVisitor(node.members, visitor, isEnumMember) - ); + return context.factory.updateEnumDeclaration(node, nodesVisitor(node.modifiers, visitor, isModifierLike), Debug.checkDefined(nodeVisitor(node.name, visitor, isIdentifier)), nodesVisitor(node.members, visitor, isEnumMember)); }, [267 /* ModuleDeclaration */]: function visitEachChildOfModuleDeclaration(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateModuleDeclaration( - node, - nodesVisitor(node.modifiers, visitor, isModifierLike), - Debug.checkDefined(nodeVisitor(node.name, visitor, isModuleName)), - nodeVisitor(node.body, visitor, isModuleBody) - ); + return context.factory.updateModuleDeclaration(node, nodesVisitor(node.modifiers, visitor, isModifierLike), Debug.checkDefined(nodeVisitor(node.name, visitor, isModuleName)), nodeVisitor(node.body, visitor, isModuleBody)); }, [268 /* ModuleBlock */]: function visitEachChildOfModuleBlock(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) { - return context.factory.updateModuleBlock( - node, - nodesVisitor(node.statements, visitor, isStatement) - ); + return context.factory.updateModuleBlock(node, nodesVisitor(node.statements, visitor, isStatement)); }, [269 /* CaseBlock */]: function visitEachChildOfCaseBlock(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) { - return context.factory.updateCaseBlock( - node, - nodesVisitor(node.clauses, visitor, isCaseOrDefaultClause) - ); + return context.factory.updateCaseBlock(node, nodesVisitor(node.clauses, visitor, isCaseOrDefaultClause)); }, [270 /* NamespaceExportDeclaration */]: function visitEachChildOfNamespaceExportDeclaration(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateNamespaceExportDeclaration( - node, - Debug.checkDefined(nodeVisitor(node.name, visitor, isIdentifier)) - ); + return context.factory.updateNamespaceExportDeclaration(node, Debug.checkDefined(nodeVisitor(node.name, visitor, isIdentifier))); }, [271 /* ImportEqualsDeclaration */]: function visitEachChildOfImportEqualsDeclaration(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateImportEqualsDeclaration( - node, - nodesVisitor(node.modifiers, visitor, isModifierLike), - node.isTypeOnly, - Debug.checkDefined(nodeVisitor(node.name, visitor, isIdentifier)), - Debug.checkDefined(nodeVisitor(node.moduleReference, visitor, isModuleReference)) - ); + return context.factory.updateImportEqualsDeclaration(node, nodesVisitor(node.modifiers, visitor, isModifierLike), node.isTypeOnly, Debug.checkDefined(nodeVisitor(node.name, visitor, isIdentifier)), Debug.checkDefined(nodeVisitor(node.moduleReference, visitor, isModuleReference))); }, [272 /* ImportDeclaration */]: function visitEachChildOfImportDeclaration(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateImportDeclaration( - node, - nodesVisitor(node.modifiers, visitor, isModifierLike), - nodeVisitor(node.importClause, visitor, isImportClause), - Debug.checkDefined(nodeVisitor(node.moduleSpecifier, visitor, isExpression)), - nodeVisitor(node.attributes, visitor, isImportAttributes) - ); + return context.factory.updateImportDeclaration(node, nodesVisitor(node.modifiers, visitor, isModifierLike), nodeVisitor(node.importClause, visitor, isImportClause), Debug.checkDefined(nodeVisitor(node.moduleSpecifier, visitor, isExpression)), nodeVisitor(node.attributes, visitor, isImportAttributes)); }, [300 /* ImportAttributes */]: function visitEachChildOfImportAttributes(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) { - return context.factory.updateImportAttributes( - node, - nodesVisitor(node.elements, visitor, isImportAttribute), - node.multiLine - ); + return context.factory.updateImportAttributes(node, nodesVisitor(node.elements, visitor, isImportAttribute), node.multiLine); }, [301 /* ImportAttribute */]: function visitEachChildOfImportAttribute(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateImportAttribute( - node, - Debug.checkDefined(nodeVisitor(node.name, visitor, isImportAttributeName)), - Debug.checkDefined(nodeVisitor(node.value, visitor, isExpression)) - ); + return context.factory.updateImportAttribute(node, Debug.checkDefined(nodeVisitor(node.name, visitor, isImportAttributeName)), Debug.checkDefined(nodeVisitor(node.value, visitor, isExpression))); }, [273 /* ImportClause */]: function visitEachChildOfImportClause(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateImportClause( - node, - node.isTypeOnly, - nodeVisitor(node.name, visitor, isIdentifier), - nodeVisitor(node.namedBindings, visitor, isNamedImportBindings) - ); + return context.factory.updateImportClause(node, node.isTypeOnly, nodeVisitor(node.name, visitor, isIdentifier), nodeVisitor(node.namedBindings, visitor, isNamedImportBindings)); }, [274 /* NamespaceImport */]: function visitEachChildOfNamespaceImport(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateNamespaceImport( - node, - Debug.checkDefined(nodeVisitor(node.name, visitor, isIdentifier)) - ); + return context.factory.updateNamespaceImport(node, Debug.checkDefined(nodeVisitor(node.name, visitor, isIdentifier))); }, [280 /* NamespaceExport */]: function visitEachChildOfNamespaceExport(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateNamespaceExport( - node, - Debug.checkDefined(nodeVisitor(node.name, visitor, isIdentifier)) - ); + return context.factory.updateNamespaceExport(node, Debug.checkDefined(nodeVisitor(node.name, visitor, isIdentifier))); }, [275 /* NamedImports */]: function visitEachChildOfNamedImports(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) { - return context.factory.updateNamedImports( - node, - nodesVisitor(node.elements, visitor, isImportSpecifier) - ); + return context.factory.updateNamedImports(node, nodesVisitor(node.elements, visitor, isImportSpecifier)); }, [276 /* ImportSpecifier */]: function visitEachChildOfImportSpecifier(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateImportSpecifier( - node, - node.isTypeOnly, - nodeVisitor(node.propertyName, visitor, isIdentifier), - Debug.checkDefined(nodeVisitor(node.name, visitor, isIdentifier)) - ); + return context.factory.updateImportSpecifier(node, node.isTypeOnly, nodeVisitor(node.propertyName, visitor, isIdentifier), Debug.checkDefined(nodeVisitor(node.name, visitor, isIdentifier))); }, [277 /* ExportAssignment */]: function visitEachChildOfExportAssignment(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateExportAssignment( - node, - nodesVisitor(node.modifiers, visitor, isModifierLike), - Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)) - ); + return context.factory.updateExportAssignment(node, nodesVisitor(node.modifiers, visitor, isModifierLike), Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression))); }, [278 /* ExportDeclaration */]: function visitEachChildOfExportDeclaration(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateExportDeclaration( - node, - nodesVisitor(node.modifiers, visitor, isModifierLike), - node.isTypeOnly, - nodeVisitor(node.exportClause, visitor, isNamedExportBindings), - nodeVisitor(node.moduleSpecifier, visitor, isExpression), - nodeVisitor(node.attributes, visitor, isImportAttributes) - ); + return context.factory.updateExportDeclaration(node, nodesVisitor(node.modifiers, visitor, isModifierLike), node.isTypeOnly, nodeVisitor(node.exportClause, visitor, isNamedExportBindings), nodeVisitor(node.moduleSpecifier, visitor, isExpression), nodeVisitor(node.attributes, visitor, isImportAttributes)); }, [279 /* NamedExports */]: function visitEachChildOfNamedExports(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) { - return context.factory.updateNamedExports( - node, - nodesVisitor(node.elements, visitor, isExportSpecifier) - ); + return context.factory.updateNamedExports(node, nodesVisitor(node.elements, visitor, isExportSpecifier)); }, [281 /* ExportSpecifier */]: function visitEachChildOfExportSpecifier(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateExportSpecifier( - node, - node.isTypeOnly, - nodeVisitor(node.propertyName, visitor, isIdentifier), - Debug.checkDefined(nodeVisitor(node.name, visitor, isIdentifier)) - ); + return context.factory.updateExportSpecifier(node, node.isTypeOnly, nodeVisitor(node.propertyName, visitor, isIdentifier), Debug.checkDefined(nodeVisitor(node.name, visitor, isIdentifier))); }, // Module references [283 /* ExternalModuleReference */]: function visitEachChildOfExternalModuleReference(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateExternalModuleReference( - node, - Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)) - ); + return context.factory.updateExternalModuleReference(node, Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression))); }, // JSX [284 /* JsxElement */]: function visitEachChildOfJsxElement(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateJsxElement( - node, - Debug.checkDefined(nodeVisitor(node.openingElement, visitor, isJsxOpeningElement)), - nodesVisitor(node.children, visitor, isJsxChild), - Debug.checkDefined(nodeVisitor(node.closingElement, visitor, isJsxClosingElement)) - ); + return context.factory.updateJsxElement(node, Debug.checkDefined(nodeVisitor(node.openingElement, visitor, isJsxOpeningElement)), nodesVisitor(node.children, visitor, isJsxChild), Debug.checkDefined(nodeVisitor(node.closingElement, visitor, isJsxClosingElement))); }, [285 /* JsxSelfClosingElement */]: function visitEachChildOfJsxSelfClosingElement(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateJsxSelfClosingElement( - node, - Debug.checkDefined(nodeVisitor(node.tagName, visitor, isJsxTagNameExpression)), - nodesVisitor(node.typeArguments, visitor, isTypeNode), - Debug.checkDefined(nodeVisitor(node.attributes, visitor, isJsxAttributes)) - ); + return context.factory.updateJsxSelfClosingElement(node, Debug.checkDefined(nodeVisitor(node.tagName, visitor, isJsxTagNameExpression)), nodesVisitor(node.typeArguments, visitor, isTypeNode), Debug.checkDefined(nodeVisitor(node.attributes, visitor, isJsxAttributes))); }, [286 /* JsxOpeningElement */]: function visitEachChildOfJsxOpeningElement(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateJsxOpeningElement( - node, - Debug.checkDefined(nodeVisitor(node.tagName, visitor, isJsxTagNameExpression)), - nodesVisitor(node.typeArguments, visitor, isTypeNode), - Debug.checkDefined(nodeVisitor(node.attributes, visitor, isJsxAttributes)) - ); + return context.factory.updateJsxOpeningElement(node, Debug.checkDefined(nodeVisitor(node.tagName, visitor, isJsxTagNameExpression)), nodesVisitor(node.typeArguments, visitor, isTypeNode), Debug.checkDefined(nodeVisitor(node.attributes, visitor, isJsxAttributes))); }, [287 /* JsxClosingElement */]: function visitEachChildOfJsxClosingElement(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateJsxClosingElement( - node, - Debug.checkDefined(nodeVisitor(node.tagName, visitor, isJsxTagNameExpression)) - ); + return context.factory.updateJsxClosingElement(node, Debug.checkDefined(nodeVisitor(node.tagName, visitor, isJsxTagNameExpression))); }, [295 /* JsxNamespacedName */]: function forEachChildInJsxNamespacedName2(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateJsxNamespacedName( - node, - Debug.checkDefined(nodeVisitor(node.namespace, visitor, isIdentifier)), - Debug.checkDefined(nodeVisitor(node.name, visitor, isIdentifier)) - ); + return context.factory.updateJsxNamespacedName(node, Debug.checkDefined(nodeVisitor(node.namespace, visitor, isIdentifier)), Debug.checkDefined(nodeVisitor(node.name, visitor, isIdentifier))); }, [288 /* JsxFragment */]: function visitEachChildOfJsxFragment(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateJsxFragment( - node, - Debug.checkDefined(nodeVisitor(node.openingFragment, visitor, isJsxOpeningFragment)), - nodesVisitor(node.children, visitor, isJsxChild), - Debug.checkDefined(nodeVisitor(node.closingFragment, visitor, isJsxClosingFragment)) - ); + return context.factory.updateJsxFragment(node, Debug.checkDefined(nodeVisitor(node.openingFragment, visitor, isJsxOpeningFragment)), nodesVisitor(node.children, visitor, isJsxChild), Debug.checkDefined(nodeVisitor(node.closingFragment, visitor, isJsxClosingFragment))); }, [291 /* JsxAttribute */]: function visitEachChildOfJsxAttribute(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateJsxAttribute( - node, - Debug.checkDefined(nodeVisitor(node.name, visitor, isJsxAttributeName)), - nodeVisitor(node.initializer, visitor, isStringLiteralOrJsxExpression) - ); + return context.factory.updateJsxAttribute(node, Debug.checkDefined(nodeVisitor(node.name, visitor, isJsxAttributeName)), nodeVisitor(node.initializer, visitor, isStringLiteralOrJsxExpression)); }, [292 /* JsxAttributes */]: function visitEachChildOfJsxAttributes(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) { - return context.factory.updateJsxAttributes( - node, - nodesVisitor(node.properties, visitor, isJsxAttributeLike) - ); + return context.factory.updateJsxAttributes(node, nodesVisitor(node.properties, visitor, isJsxAttributeLike)); }, [293 /* JsxSpreadAttribute */]: function visitEachChildOfJsxSpreadAttribute(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateJsxSpreadAttribute( - node, - Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)) - ); + return context.factory.updateJsxSpreadAttribute(node, Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression))); }, [294 /* JsxExpression */]: function visitEachChildOfJsxExpression(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateJsxExpression( - node, - nodeVisitor(node.expression, visitor, isExpression) - ); + return context.factory.updateJsxExpression(node, nodeVisitor(node.expression, visitor, isExpression)); }, // Clauses [296 /* CaseClause */]: function visitEachChildOfCaseClause(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateCaseClause( - node, - Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)), - nodesVisitor(node.statements, visitor, isStatement) - ); + return context.factory.updateCaseClause(node, Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)), nodesVisitor(node.statements, visitor, isStatement)); }, [297 /* DefaultClause */]: function visitEachChildOfDefaultClause(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) { - return context.factory.updateDefaultClause( - node, - nodesVisitor(node.statements, visitor, isStatement) - ); + return context.factory.updateDefaultClause(node, nodesVisitor(node.statements, visitor, isStatement)); }, [298 /* HeritageClause */]: function visitEachChildOfHeritageClause(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) { - return context.factory.updateHeritageClause( - node, - nodesVisitor(node.types, visitor, isExpressionWithTypeArguments) - ); + return context.factory.updateHeritageClause(node, nodesVisitor(node.types, visitor, isExpressionWithTypeArguments)); }, [299 /* CatchClause */]: function visitEachChildOfCatchClause(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateCatchClause( - node, - nodeVisitor(node.variableDeclaration, visitor, isVariableDeclaration), - Debug.checkDefined(nodeVisitor(node.block, visitor, isBlock)) - ); + return context.factory.updateCatchClause(node, nodeVisitor(node.variableDeclaration, visitor, isVariableDeclaration), Debug.checkDefined(nodeVisitor(node.block, visitor, isBlock))); }, // Property assignments [303 /* PropertyAssignment */]: function visitEachChildOfPropertyAssignment(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updatePropertyAssignment( - node, - Debug.checkDefined(nodeVisitor(node.name, visitor, isPropertyName)), - Debug.checkDefined(nodeVisitor(node.initializer, visitor, isExpression)) - ); + return context.factory.updatePropertyAssignment(node, Debug.checkDefined(nodeVisitor(node.name, visitor, isPropertyName)), Debug.checkDefined(nodeVisitor(node.initializer, visitor, isExpression))); }, [304 /* ShorthandPropertyAssignment */]: function visitEachChildOfShorthandPropertyAssignment(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateShorthandPropertyAssignment( - node, - Debug.checkDefined(nodeVisitor(node.name, visitor, isIdentifier)), - nodeVisitor(node.objectAssignmentInitializer, visitor, isExpression) - ); + return context.factory.updateShorthandPropertyAssignment(node, Debug.checkDefined(nodeVisitor(node.name, visitor, isIdentifier)), nodeVisitor(node.objectAssignmentInitializer, visitor, isExpression)); }, [305 /* SpreadAssignment */]: function visitEachChildOfSpreadAssignment(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateSpreadAssignment( - node, - Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)) - ); + return context.factory.updateSpreadAssignment(node, Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression))); }, // Enum [306 /* EnumMember */]: function visitEachChildOfEnumMember(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateEnumMember( - node, - Debug.checkDefined(nodeVisitor(node.name, visitor, isPropertyName)), - nodeVisitor(node.initializer, visitor, isExpression) - ); + return context.factory.updateEnumMember(node, Debug.checkDefined(nodeVisitor(node.name, visitor, isPropertyName)), nodeVisitor(node.initializer, visitor, isExpression)); }, // Top-level nodes [312 /* SourceFile */]: function visitEachChildOfSourceFile(node, visitor, context, _nodesVisitor, _nodeVisitor, _tokenVisitor) { - return context.factory.updateSourceFile( - node, - visitLexicalEnvironment(node.statements, visitor, context) - ); + return context.factory.updateSourceFile(node, visitLexicalEnvironment(node.statements, visitor, context)); }, // Transformation nodes [360 /* PartiallyEmittedExpression */]: function visitEachChildOfPartiallyEmittedExpression(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updatePartiallyEmittedExpression( - node, - Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)) - ); + return context.factory.updatePartiallyEmittedExpression(node, Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression))); }, [361 /* CommaListExpression */]: function visitEachChildOfCommaListExpression(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) { - return context.factory.updateCommaListExpression( - node, - nodesVisitor(node.elements, visitor, isExpression) - ); + return context.factory.updateCommaListExpression(node, nodesVisitor(node.elements, visitor, isExpression)); } }; } @@ -88466,10 +81365,13 @@ ${lanes.join("\n")} // src/compiler/sourcemap.ts function createSourceMapGenerator(host, file, sourceRoot, sourcesDirectoryPath, generatorOptions) { - var { enter, exit } = generatorOptions.extendedDiagnostics ? createTimer("Source Map", "beforeSourcemap", "afterSourcemap") : nullTimer; + var { + enter, + exit + } = generatorOptions.extendedDiagnostics ? createTimer("Source Map", "beforeSourcemap", "afterSourcemap") : nullTimer; var rawSources = []; var sources = []; - var sourceToSourceIndexMap = /* @__PURE__ */ new Map(); + var sourceToSourceIndexMap = /* @__PURE__ */new Map(); var sourcesContent; var names = []; var nameToNameIndexMap; @@ -88503,14 +81405,8 @@ ${lanes.join("\n")} }; function addSource(fileName) { enter(); - const source = getRelativePathToDirectoryOrUrl( - sourcesDirectoryPath, - fileName, - host.getCurrentDirectory(), - host.getCanonicalFileName, - /*isAbsolutePathAnUrl*/ - true - ); + const source = getRelativePathToDirectoryOrUrl(sourcesDirectoryPath, fileName, host.getCurrentDirectory(), host.getCanonicalFileName, /*isAbsolutePathAnUrl*/ + true); let sourceIndex = sourceToSourceIndexMap.get(source); if (sourceIndex === void 0) { sourceIndex = sources.length; @@ -88524,8 +81420,7 @@ ${lanes.join("\n")} function setSourceContent(sourceIndex, content) { enter(); if (content !== null) { - if (!sourcesContent) - sourcesContent = []; + if (!sourcesContent) sourcesContent = []; while (sourcesContent.length < sourceIndex) { sourcesContent.push(null); } @@ -88535,8 +81430,7 @@ ${lanes.join("\n")} } 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; @@ -88611,8 +81505,7 @@ ${lanes.join("\n")} 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]); @@ -88653,6 +81546,7 @@ ${lanes.join("\n")} appendMappingCharCode(44 /* comma */); } } + appendBase64VLQ(pendingGeneratedCharacter - lastGeneratedCharacter); lastGeneratedCharacter = pendingGeneratedCharacter; if (hasPendingSource) { @@ -88708,7 +81602,7 @@ ${lanes.join("\n")} function getLineInfo(text, lineStarts) { return { getLineCount: () => lineStarts.length, - getLineText: (line) => text.substring(lineStarts[line], lineStarts[line + 1]) + getLineText: line => text.substring(lineStarts[line], lineStarts[line + 1]) }; } function tryGetSourceMappingURL(lineInfo) { @@ -88734,8 +81628,7 @@ ${lanes.join("\n")} if (isRawSourceMap(parsed)) { return parsed; } - } catch { - } + } catch {} return void 0; } function decodeMappings(mappings) { @@ -88756,12 +81649,9 @@ ${lanes.join("\n")} return error2; }, get state() { - return captureMapping( - /*hasSource*/ - true, - /*hasName*/ - true - ); + return captureMapping( /*hasSource*/ + true, /*hasName*/ + true); }, next() { while (!done && pos < mappings.length) { @@ -88779,43 +81669,33 @@ ${lanes.join("\n")} 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 }; + return { + value: captureMapping(hasSource, hasName), + done + }; } return stopIterating(); }, @@ -88835,7 +81715,10 @@ ${lanes.join("\n")} } function stopIterating() { done = true; - return { value: void 0, done: true }; + return { + value: void 0, + done: true + }; } function setError(message) { if (error2 === void 0) { @@ -88852,16 +81735,15 @@ ${lanes.join("\n")} function isSourceMappingSegmentEnd() { return pos === mappings.length || mappings.charCodeAt(pos) === 44 /* comma */ || mappings.charCodeAt(pos) === 59 /* semicolon */; } + function base64VLQFormatDecode() { let moreDigits = true; 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; @@ -88911,7 +81793,7 @@ ${lanes.join("\n")} const sourceRoot = map2.sourceRoot ? getNormalizedAbsolutePath(map2.sourceRoot, mapDirectory) : mapDirectory; const generatedAbsoluteFilePath = getNormalizedAbsolutePath(map2.file, mapDirectory); const generatedFile = host.getSourceFileLike(generatedAbsoluteFilePath); - const sourceFileAbsolutePaths = map2.sources.map((source) => getNormalizedAbsolutePath(source, sourceRoot)); + const sourceFileAbsolutePaths = map2.sources.map(source => getNormalizedAbsolutePath(source, sourceRoot)); const sourceToSourceIndexMap = new Map(sourceFileAbsolutePaths.map((source, i) => [host.getCanonicalFileName(source), i])); let decodedMappings; let generatedMappings; @@ -88921,25 +81803,15 @@ ${lanes.join("\n")} getGeneratedPosition }; function processMapping(mapping) { - const generatedPosition = generatedFile !== void 0 ? getPositionOfLineAndCharacter( - generatedFile, - mapping.generatedLine, - mapping.generatedCharacter, - /*allowEdits*/ - true - ) : -1; + const generatedPosition = generatedFile !== void 0 ? getPositionOfLineAndCharacter(generatedFile, mapping.generatedLine, mapping.generatedCharacter, /*allowEdits*/ + true) : -1; let source; let sourcePosition; if (isSourceMapping(mapping)) { const sourceFile = host.getSourceFileLike(sourceFileAbsolutePaths[mapping.sourceIndex]); source = map2.sources[mapping.sourceIndex]; - sourcePosition = sourceFile !== void 0 ? getPositionOfLineAndCharacter( - sourceFile, - mapping.sourceLine, - mapping.sourceCharacter, - /*allowEdits*/ - true - ) : -1; + sourcePosition = sourceFile !== void 0 ? getPositionOfLineAndCharacter(sourceFile, mapping.sourceLine, mapping.sourceCharacter, /*allowEdits*/ + true) : -1; } return { generatedPosition, @@ -88968,14 +81840,12 @@ ${lanes.join("\n")} 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)); + sourceMappings = lists.map(list => sortAndDeduplicate(list, compareSourcePositions, sameMappedPosition)); } return sourceMappings[sourceIndex]; } @@ -88991,11 +81861,9 @@ ${lanes.join("\n")} } 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; @@ -89004,12 +81872,14 @@ ${lanes.join("\n")} if (mapping === void 0 || mapping.sourceIndex !== sourceIndex) { return loc; } - return { fileName: generatedAbsoluteFilePath, pos: mapping.generatedPosition }; + return { + fileName: generatedAbsoluteFilePath, + pos: mapping.generatedPosition + }; } 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; @@ -89018,13 +81888,17 @@ ${lanes.join("\n")} if (mapping === void 0 || !isSourceMappedPosition(mapping)) { return loc; } - return { fileName: sourceFileAbsolutePaths[mapping.sourceIndex], pos: mapping.sourcePosition }; + return { + fileName: sourceFileAbsolutePaths[mapping.sourceIndex], + pos: mapping.sourcePosition + }; } } var sourceMapCommentRegExpDontCareLineStart, sourceMapCommentRegExp, whitespaceOrMapCommentRegExp, identitySourceMapConsumer; var init_sourcemap = __esm({ "src/compiler/sourcemap.ts"() { "use strict"; + init_ts2(); init_ts_performance(); sourceMapCommentRegExpDontCareLineStart = /\/\/[@#] source[M]appingURL=(.+)\r?\n?$/; @@ -89043,15 +81917,14 @@ ${lanes.join("\n")} return node ? getNodeId(node) : 0; } function containsDefaultReference(node) { - if (!node) - return false; - if (!isNamedImports(node)) - return false; + if (!node) return false; + if (!isNamedImports(node)) return false; return some(node.elements, isNamedDefaultReference); } function isNamedDefaultReference(e) { return e.propertyName !== void 0 && e.propertyName.escapedText === "default" /* Default */; } + function chainBundle(context, transformSourceFile) { return transformSourceFileOrBundle; function transformSourceFileOrBundle(node) { @@ -89072,8 +81945,7 @@ ${lanes.join("\n")} 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)) { @@ -89091,7 +81963,7 @@ ${lanes.join("\n")} const externalImports = []; const exportSpecifiers = new IdentifierNameMultiMap(); const exportedBindings = []; - const uniqueExports = /* @__PURE__ */ new Map(); + const uniqueExports = /* @__PURE__ */new Map(); let exportedNames; let hasExportDefault = false; let exportEquals; @@ -89189,7 +82061,15 @@ ${lanes.join("\n")} if (externalHelpersImportDeclaration) { externalImports.unshift(externalHelpersImportDeclaration); } - return { externalImports, exportSpecifiers, exportEquals, hasExportStarsToExportValues, exportedBindings, exportedNames, externalHelpersImportDeclaration }; + return { + externalImports, + exportSpecifiers, + exportEquals, + hasExportStarsToExportValues, + exportedBindings, + exportedNames, + externalHelpersImportDeclaration + }; function addExportedNamesForExportDeclaration(node) { for (const specifier of cast(node.exportClause, isNamedExports).elements) { if (!uniqueExports.get(idText(specifier.name))) { @@ -89244,6 +82124,7 @@ ${lanes.join("\n")} function isCompoundAssignment(kind) { return kind >= 65 /* FirstCompoundAssignment */ && kind <= 79 /* LastCompoundAssignment */; } + function getNonAssignmentOperatorForCompoundAssignment(kind) { switch (kind) { case 65 /* PlusEqualsToken */: @@ -89278,6 +82159,7 @@ ${lanes.join("\n")} return 61 /* QuestionQuestionToken */; } } + function getSuperCallFromStatement(statement) { if (!isExpressionStatement(statement)) { return void 0; @@ -89304,7 +82186,7 @@ ${lanes.join("\n")} return indices; } function getProperties(node, requireInitializer, isStatic2) { - return filter(node.members, (m) => isInitializedOrStaticProperty(m, requireInitializer, isStatic2)); + return filter(node.members, m => isInitializedOrStaticProperty(m, requireInitializer, isStatic2)); } function isStaticPropertyDeclarationOrClassStaticBlockDeclaration(element) { return isStaticPropertyDeclaration(element) || isClassStaticBlockDeclaration(element); @@ -89374,7 +82256,12 @@ ${lanes.join("\n")} if (!accessor.body) { return void 0; } - const { firstAccessor, secondAccessor, getAccessor, setAccessor } = getAllAccessorDeclarations(parent2.members, accessor); + const { + firstAccessor, + secondAccessor, + getAccessor, + setAccessor + } = getAllAccessorDeclarations(parent2.members, accessor); const firstAccessorWithDecorators = hasDecorators(firstAccessor) ? firstAccessor : secondAccessor && hasDecorators(secondAccessor) ? secondAccessor : void 0; if (!firstAccessorWithDecorators || accessor !== firstAccessorWithDecorators) { return void 0; @@ -89400,25 +82287,31 @@ ${lanes.join("\n")} if (!some(decorators) && !some(parameters)) { return void 0; } - return { decorators, parameters }; + return { + decorators, + parameters + }; } function getAllDecoratorsOfProperty(property) { const decorators = getDecorators(property); if (!some(decorators)) { return void 0; } - return { decorators }; + return { + decorators + }; } 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; } } function newPrivateEnvironment(data) { - return { data }; + return { + data + }; } function getPrivateIdentifier(privateEnv, name) { var _a, _b; @@ -89426,24 +82319,27 @@ ${lanes.join("\n")} } function setPrivateIdentifier(privateEnv, name, entry) { if (isGeneratedPrivateIdentifier(name)) { - privateEnv.generatedIdentifiers ?? (privateEnv.generatedIdentifiers = /* @__PURE__ */ new Map()); + var _privateEnv$generated; + (_privateEnv$generated = privateEnv.generatedIdentifiers) !== null && _privateEnv$generated !== void 0 ? _privateEnv$generated : privateEnv.generatedIdentifiers = /* @__PURE__ */new Map(); privateEnv.generatedIdentifiers.set(getNodeForGeneratedName(name), entry); } else { - privateEnv.identifiers ?? (privateEnv.identifiers = /* @__PURE__ */ new Map()); + var _privateEnv$identifie; + (_privateEnv$identifie = privateEnv.identifiers) !== null && _privateEnv$identifie !== void 0 ? _privateEnv$identifie : privateEnv.identifiers = /* @__PURE__ */new Map(); privateEnv.identifiers.set(name.escapedText, entry); } } function accessPrivateIdentifier(env, name) { - return walkUpLexicalEnvironments(env, (env2) => getPrivateIdentifier(env2.privateEnv, name)); + return walkUpLexicalEnvironments(env, env2 => getPrivateIdentifier(env2.privateEnv, name)); } var IdentifierNameMap, IdentifierNameMultiMap; var init_utilities3 = __esm({ "src/compiler/transformers/utilities.ts"() { "use strict"; + init_ts2(); IdentifierNameMap = class _IdentifierNameMap { constructor() { - this._map = /* @__PURE__ */ new Map(); + this._map = /* @__PURE__ */new Map(); } get size() { return this._map.size; @@ -89459,8 +82355,9 @@ ${lanes.join("\n")} return this; } delete(key) { + var _ref30; var _a; - return ((_a = this._map) == null ? void 0 : _a.delete(_IdentifierNameMap.toKey(key))) ?? false; + return (_ref30 = (_a = this._map) == null ? void 0 : _a.delete(_IdentifierNameMap.toKey(key))) !== null && _ref30 !== void 0 ? _ref30 : false; } clear() { this._map.clear(); @@ -89474,24 +82371,12 @@ ${lanes.join("\n")} if ((autoGenerate.flags & 7 /* KindMask */) === 4 /* Node */) { const node = getNodeForGeneratedName(name); const baseName = isMemberName(node) && node !== name ? _IdentifierNameMap.toKey(node) : `(generated@${getNodeId(node)})`; - return formatGeneratedName( - /*privateName*/ - false, - autoGenerate.prefix, - baseName, - autoGenerate.suffix, - _IdentifierNameMap.toKey - ); + return formatGeneratedName( /*privateName*/ + false, autoGenerate.prefix, baseName, autoGenerate.suffix, _IdentifierNameMap.toKey); } else { const baseName = `(auto@${autoGenerate.id})`; - return formatGeneratedName( - /*privateName*/ - false, - autoGenerate.prefix, - baseName, - autoGenerate.suffix, - _IdentifierNameMap.toKey - ); + return formatGeneratedName( /*privateName*/ + false, autoGenerate.prefix, baseName, autoGenerate.suffix, _IdentifierNameMap.toKey); } } if (isPrivateIdentifier(name)) { @@ -89546,8 +82431,8 @@ ${lanes.join("\n")} hoistTempVariables: true, emitExpression, emitBindingOrAssignment, - createArrayBindingOrAssignmentPattern: (elements) => makeArrayAssignmentPattern(context.factory, elements), - createObjectBindingOrAssignmentPattern: (elements) => makeObjectAssignmentPattern(context.factory, elements), + createArrayBindingOrAssignmentPattern: elements => makeArrayAssignmentPattern(context.factory, elements), + createObjectBindingOrAssignmentPattern: elements => makeObjectAssignmentPattern(context.factory, elements), createArrayBindingOrAssignmentElement: makeAssignmentElement, visitor }; @@ -89555,33 +82440,17 @@ ${lanes.join("\n")} value = visitNode(value, visitor, isExpression); Debug.assert(value); if (isIdentifier(value) && bindingOrAssignmentElementAssignsToName(node, value.escapedText) || bindingOrAssignmentElementContainsNonLiteralComputedName(node)) { - value = ensureIdentifier( - flattenContext, - value, - /*reuseIdentifierExpressions*/ - false, - location - ); + value = ensureIdentifier(flattenContext, value, /*reuseIdentifierExpressions*/ + false, location); } else if (needsValue) { - value = ensureIdentifier( - flattenContext, - value, - /*reuseIdentifierExpressions*/ - true, - location - ); + value = ensureIdentifier(flattenContext, value, /*reuseIdentifierExpressions*/ + true, location); } else if (nodeIsSynthesized(node)) { location = value; } } - flattenBindingOrAssignmentElement( - flattenContext, - node, - value, - location, - /*skipInitializer*/ - isDestructuringAssignment(node) - ); + flattenBindingOrAssignmentElement(flattenContext, node, value, location, /*skipInitializer*/ + isDestructuringAssignment(node)); if (value && needsValue) { if (!some(expressions)) { return value; @@ -89594,10 +82463,7 @@ ${lanes.join("\n")} } function emitBindingOrAssignment(target, value2, location2, original) { Debug.assertNode(target, createAssignmentCallback ? isIdentifier : isExpression); - const expression = createAssignmentCallback ? createAssignmentCallback(target, value2, location2) : setTextRange( - context.factory.createAssignment(Debug.checkDefined(visitNode(target, visitor, isExpression)), value2), - location2 - ); + const expression = createAssignmentCallback ? createAssignmentCallback(target, value2, location2) : setTextRange(context.factory.createAssignment(Debug.checkDefined(visitNode(target, visitor, isExpression)), value2), location2); expression.original = original; emitExpression(expression); } @@ -89642,69 +82508,49 @@ ${lanes.join("\n")} hoistTempVariables, emitExpression, emitBindingOrAssignment, - createArrayBindingOrAssignmentPattern: (elements) => makeArrayBindingPattern(context.factory, elements), - createObjectBindingOrAssignmentPattern: (elements) => makeObjectBindingPattern(context.factory, elements), - createArrayBindingOrAssignmentElement: (name) => makeBindingElement(context.factory, name), + createArrayBindingOrAssignmentPattern: elements => makeArrayBindingPattern(context.factory, elements), + createObjectBindingOrAssignmentPattern: elements => makeObjectBindingPattern(context.factory, elements), + createArrayBindingOrAssignmentElement: name => makeBindingElement(context.factory, name), visitor }; if (isVariableDeclaration(node)) { let initializer = getInitializerOfBindingOrAssignmentElement(node); if (initializer && (isIdentifier(initializer) && bindingOrAssignmentElementAssignsToName(node, initializer.escapedText) || bindingOrAssignmentElementContainsNonLiteralComputedName(node))) { - initializer = ensureIdentifier( - flattenContext, - Debug.checkDefined(visitNode(initializer, flattenContext.visitor, isExpression)), - /*reuseIdentifierExpressions*/ - false, - initializer - ); - node = context.factory.updateVariableDeclaration( - node, - node.name, - /*exclamationToken*/ - void 0, - /*type*/ - void 0, - initializer - ); + initializer = ensureIdentifier(flattenContext, Debug.checkDefined(visitNode(initializer, flattenContext.visitor, isExpression)), /*reuseIdentifierExpressions*/ + false, initializer); + node = context.factory.updateVariableDeclaration(node, node.name, /*exclamationToken*/ + void 0, /*type*/ + void 0, initializer); } } flattenBindingOrAssignmentElement(flattenContext, node, rval, node, skipInitializer); if (pendingExpressions) { - const temp = context.factory.createTempVariable( - /*recordTempVariable*/ - void 0 - ); + const temp = context.factory.createTempVariable( /*recordTempVariable*/ + void 0); if (hoistTempVariables) { const value = context.factory.inlineExpressions(pendingExpressions); pendingExpressions = void 0; - emitBindingOrAssignment( - temp, - value, - /*location*/ - void 0, - /*original*/ - void 0 - ); + emitBindingOrAssignment(temp, value, /*location*/ + void 0, /*original*/ + void 0); } else { context.hoistVariableDeclaration(temp); const pendingDeclaration = last(pendingDeclarations); - pendingDeclaration.pendingExpressions = append( - pendingDeclaration.pendingExpressions, - context.factory.createAssignment(temp, pendingDeclaration.value) - ); + pendingDeclaration.pendingExpressions = append(pendingDeclaration.pendingExpressions, context.factory.createAssignment(temp, pendingDeclaration.value)); addRange(pendingDeclaration.pendingExpressions, pendingExpressions); pendingDeclaration.value = temp; } } - for (const { pendingExpressions: pendingExpressions2, name, value, location, original } of pendingDeclarations) { - const variable = context.factory.createVariableDeclaration( - name, - /*exclamationToken*/ - void 0, - /*type*/ - void 0, - pendingExpressions2 ? context.factory.inlineExpressions(append(pendingExpressions2, value)) : value - ); + for (const { + pendingExpressions: pendingExpressions2, + name, + value, + location, + original + } of pendingDeclarations) { + const variable = context.factory.createVariableDeclaration(name, /*exclamationToken*/ + void 0, /*type*/ + void 0, pendingExpressions2 ? context.factory.inlineExpressions(append(pendingExpressions2, value)) : value); variable.original = original; setTextRange(variable, location); declarations.push(variable); @@ -89719,7 +82565,13 @@ ${lanes.join("\n")} value = context.factory.inlineExpressions(append(pendingExpressions, value)); pendingExpressions = void 0; } - pendingDeclarations.push({ pendingExpressions, name: target, value, location, original }); + pendingDeclarations.push({ + pendingExpressions, + name: target, + value, + location, + original + }); } } function flattenBindingOrAssignmentElement(flattenContext, element, value, location, skipInitializer) { @@ -89730,13 +82582,8 @@ ${lanes.join("\n")} if (value) { value = createDefaultValueCheck(flattenContext, value, initializer, location); if (!isSimpleInlineableExpression(initializer) && isBindingOrAssignmentPattern(bindingTarget)) { - value = ensureIdentifier( - flattenContext, - value, - /*reuseIdentifierExpressions*/ - true, - location - ); + value = ensureIdentifier(flattenContext, value, /*reuseIdentifierExpressions*/ + true, location); } } else { value = initializer; @@ -89750,13 +82597,8 @@ ${lanes.join("\n")} } else if (isArrayBindingOrAssignmentPattern(bindingTarget)) { flattenArrayBindingOrAssignmentPattern(flattenContext, element, bindingTarget, value, location); } else { - flattenContext.emitBindingOrAssignment( - bindingTarget, - value, - location, - /*original*/ - element - ); + flattenContext.emitBindingOrAssignment(bindingTarget, value, location, /*original*/ + element); } } function flattenObjectBindingOrAssignmentPattern(flattenContext, parent2, pattern, value, location) { @@ -89783,13 +82625,8 @@ ${lanes.join("\n")} if (isComputedPropertyName(propertyName)) { computedTempVariables = append(computedTempVariables, rhsValue.argumentExpression); } - flattenBindingOrAssignmentElement( - flattenContext, - element, - rhsValue, - /*location*/ - element - ); + flattenBindingOrAssignmentElement(flattenContext, element, rhsValue, /*location*/ + element); } } else if (i === numElements - 1) { if (bindingElements) { @@ -89808,19 +82645,8 @@ ${lanes.join("\n")} const elements = getElementsOfBindingOrAssignmentPattern(pattern); const numElements = elements.length; if (flattenContext.level < 1 /* ObjectRest */ && flattenContext.downlevelIteration) { - value = ensureIdentifier( - flattenContext, - setTextRange( - flattenContext.context.getEmitHelperFactory().createReadHelper( - value, - numElements > 0 && getRestIndicatorOfBindingOrAssignmentElement(elements[numElements - 1]) ? void 0 : numElements - ), - location - ), - /*reuseIdentifierExpressions*/ - false, - location - ); + value = ensureIdentifier(flattenContext, setTextRange(flattenContext.context.getEmitHelperFactory().createReadHelper(value, numElements > 0 && getRestIndicatorOfBindingOrAssignmentElement(elements[numElements - 1]) ? void 0 : numElements), location), /*reuseIdentifierExpressions*/ + false, location); } else if (numElements !== 1 && (flattenContext.level < 1 /* ObjectRest */ || numElements === 0) || every(elements, isOmittedExpression)) { const reuseIdentifierExpressions = !isDeclarationBindingElement(parent2) || numElements !== 0; value = ensureIdentifier(flattenContext, value, reuseIdentifierExpressions, location); @@ -89832,10 +82658,8 @@ ${lanes.join("\n")} if (flattenContext.level >= 1 /* ObjectRest */) { if (element.transformFlags & 65536 /* ContainsObjectRestOrSpread */ || flattenContext.hasTransformedPriorElement && !isSimpleBindingOrAssignmentElement(element)) { flattenContext.hasTransformedPriorElement = true; - const temp = flattenContext.context.factory.createTempVariable( - /*recordTempVariable*/ - void 0 - ); + const temp = flattenContext.context.factory.createTempVariable( /*recordTempVariable*/ + void 0); if (flattenContext.hoistTempVariables) { flattenContext.context.hoistVariableDeclaration(temp); } @@ -89848,22 +82672,12 @@ ${lanes.join("\n")} continue; } else if (!getRestIndicatorOfBindingOrAssignmentElement(element)) { const rhsValue = flattenContext.context.factory.createElementAccessExpression(value, i); - flattenBindingOrAssignmentElement( - flattenContext, - element, - rhsValue, - /*location*/ - element - ); + flattenBindingOrAssignmentElement(flattenContext, element, rhsValue, /*location*/ + element); } else if (i === numElements - 1) { const rhsValue = flattenContext.context.factory.createArraySliceCall(value, i); - flattenBindingOrAssignmentElement( - flattenContext, - element, - rhsValue, - /*location*/ - element - ); + flattenBindingOrAssignmentElement(flattenContext, element, rhsValue, /*location*/ + element); } } if (bindingElements) { @@ -89877,47 +82691,29 @@ ${lanes.join("\n")} } 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) { - value = ensureIdentifier( - flattenContext, - value, - /*reuseIdentifierExpressions*/ - true, - location - ); - return flattenContext.context.factory.createConditionalExpression( - flattenContext.context.factory.createTypeCheck(value, "undefined"), - /*questionToken*/ - void 0, - defaultValue, - /*colonToken*/ - void 0, - value - ); + value = ensureIdentifier(flattenContext, value, /*reuseIdentifierExpressions*/ + true, location); + return flattenContext.context.factory.createConditionalExpression(flattenContext.context.factory.createTypeCheck(value, "undefined"), /*questionToken*/ + void 0, defaultValue, /*colonToken*/ + void 0, value); } function createDestructuringPropertyAccess(flattenContext, value, propertyName) { - const { factory: factory2 } = flattenContext.context; + const { + factory: factory2 + } = flattenContext.context; if (isComputedPropertyName(propertyName)) { - const argumentExpression = ensureIdentifier( - flattenContext, - Debug.checkDefined(visitNode(propertyName.expression, flattenContext.visitor, isExpression)), - /*reuseIdentifierExpressions*/ - false, - /*location*/ - propertyName - ); + const argumentExpression = ensureIdentifier(flattenContext, Debug.checkDefined(visitNode(propertyName.expression, flattenContext.visitor, isExpression)), /*reuseIdentifierExpressions*/ + false, /*location*/ + propertyName); return flattenContext.context.factory.createElementAccessExpression(value, argumentExpression); } else if (isStringOrNumericLiteralLike(propertyName)) { const argumentExpression = factory2.cloneNode(propertyName); @@ -89931,21 +82727,14 @@ ${lanes.join("\n")} if (isIdentifier(value) && reuseIdentifierExpressions) { return value; } else { - const temp = flattenContext.context.factory.createTempVariable( - /*recordTempVariable*/ - void 0 - ); + const temp = flattenContext.context.factory.createTempVariable( /*recordTempVariable*/ + void 0); if (flattenContext.hoistTempVariables) { flattenContext.context.hoistVariableDeclaration(temp); flattenContext.emitExpression(setTextRange(flattenContext.context.factory.createAssignment(temp, value), location)); } else { - flattenContext.emitBindingOrAssignment( - temp, - value, - location, - /*original*/ - void 0 - ); + flattenContext.emitBindingOrAssignment(temp, value, location, /*original*/ + void 0); } return temp; } @@ -89967,13 +82756,9 @@ ${lanes.join("\n")} return factory2.createObjectLiteralExpression(map(elements, factory2.converters.convertToObjectAssignmentElement)); } function makeBindingElement(factory2, name) { - return factory2.createBindingElement( - /*dotDotDotToken*/ - void 0, - /*propertyName*/ - void 0, - name - ); + return factory2.createBindingElement( /*dotDotDotToken*/ + void 0, /*propertyName*/ + void 0, name); } function makeAssignmentElement(name) { return name; @@ -89982,8 +82767,9 @@ ${lanes.join("\n")} var init_destructuring = __esm({ "src/compiler/transformers/destructuring.ts"() { "use strict"; + init_ts2(); - FlattenLevel = /* @__PURE__ */ ((FlattenLevel2) => { + FlattenLevel = /* @__PURE__ */(FlattenLevel2 => { FlattenLevel2[FlattenLevel2["All"] = 0] = "All"; FlattenLevel2[FlattenLevel2["ObjectRest"] = 1] = "ObjectRest"; return FlattenLevel2; @@ -89995,11 +82781,8 @@ ${lanes.join("\n")} function createClassThisAssignmentBlock(factory2, classThis, thisExpression = factory2.createThis()) { const expression = factory2.createAssignment(classThis, thisExpression); const statement = factory2.createExpressionStatement(expression); - const body = factory2.createBlock( - [statement], - /*multiLine*/ - false - ); + const body = factory2.createBlock([statement], /*multiLine*/ + false); const block = factory2.createClassStaticBlockDeclaration(body); getOrCreateEmitNode(block).classThis = classThis; return block; @@ -90010,12 +82793,10 @@ ${lanes.join("\n")} return false; } const statement = node.body.statements[0]; - return isExpressionStatement(statement) && isAssignmentExpression( - statement.expression, - /*excludeCompoundAssignment*/ - true - ) && isIdentifier(statement.expression.left) && ((_a = node.emitNode) == null ? void 0 : _a.classThis) === statement.expression.left && statement.expression.right.kind === 110 /* ThisKeyword */; + return isExpressionStatement(statement) && isAssignmentExpression(statement.expression, /*excludeCompoundAssignment*/ + true) && isIdentifier(statement.expression.left) && ((_a = node.emitNode) == null ? void 0 : _a.classThis) === statement.expression.left && statement.expression.right.kind === 110 /* ThisKeyword */; } + function classHasClassThisAssignment(node) { var _a; return !!((_a = node.emitNode) == null ? void 0 : _a.classThis) && some(node.members, isClassThisAssignmentBlock); @@ -90030,27 +82811,14 @@ ${lanes.join("\n")} } const members = factory2.createNodeArray([staticBlock, ...node.members]); setTextRange(members, node.members); - const updatedNode = isClassDeclaration(node) ? factory2.updateClassDeclaration( - node, - node.modifiers, - node.name, - node.typeParameters, - node.heritageClauses, - members - ) : factory2.updateClassExpression( - node, - node.modifiers, - node.name, - node.typeParameters, - node.heritageClauses, - members - ); + const updatedNode = isClassDeclaration(node) ? factory2.updateClassDeclaration(node, node.modifiers, node.name, node.typeParameters, node.heritageClauses, members) : factory2.updateClassExpression(node, node.modifiers, node.name, node.typeParameters, node.heritageClauses, members); getOrCreateEmitNode(updatedNode).classThis = classThis; return updatedNode; } var init_classThis = __esm({ "src/compiler/transformers/classThis.ts"() { "use strict"; + init_ts2(); } }); @@ -90064,35 +82832,48 @@ ${lanes.join("\n")} return factory2.createStringLiteralFromNode(name); } function getAssignedNameOfPropertyName(context, name, assignedNameText) { - const { factory: factory2 } = context; + const { + factory: factory2 + } = context; if (assignedNameText !== void 0) { const assignedName2 = factory2.createStringLiteral(assignedNameText); - return { assignedName: assignedName2, name }; + return { + assignedName: assignedName2, + name + }; } if (isPropertyNameLiteral(name) || isPrivateIdentifier(name)) { const assignedName2 = factory2.createStringLiteralFromNode(name); - return { assignedName: assignedName2, name }; + return { + assignedName: assignedName2, + name + }; } if (isPropertyNameLiteral(name.expression) && !isIdentifier(name.expression)) { const assignedName2 = factory2.createStringLiteralFromNode(name.expression); - return { assignedName: assignedName2, name }; + return { + assignedName: assignedName2, + name + }; } const assignedName = factory2.getGeneratedNameForNode(name); context.hoistVariableDeclaration(assignedName); const key = context.getEmitHelperFactory().createPropKeyHelper(name.expression); const assignment = factory2.createAssignment(assignedName, key); const updatedName = factory2.updateComputedPropertyName(name, assignment); - return { assignedName, name: updatedName }; + return { + assignedName, + name: updatedName + }; } function createClassNamedEvaluationHelperBlock(context, assignedName, thisExpression = context.factory.createThis()) { - const { factory: factory2 } = context; + const { + factory: factory2 + } = context; const expression = context.getEmitHelperFactory().createSetFunctionNameHelper(thisExpression, assignedName); const statement = factory2.createExpressionStatement(expression); - const body = factory2.createBlock( - [statement], - /*multiLine*/ - false - ); + const body = factory2.createBlock([statement], /*multiLine*/ + false); const block = factory2.createClassStaticBlockDeclaration(body); getOrCreateEmitNode(block).assignedName = assignedName; return block; @@ -90116,7 +82897,9 @@ ${lanes.join("\n")} if (classHasExplicitlyAssignedName(node)) { return node; } - const { factory: factory2 } = context; + const { + factory: factory2 + } = context; const namedEvaluationBlock = createClassNamedEvaluationHelperBlock(context, assignedName, thisExpression); if (node.name) { setSourceMapRange(namedEvaluationBlock.body.statements[0], node.name); @@ -90126,21 +82909,7 @@ ${lanes.join("\n")} const trailing = node.members.slice(insertionIndex); const members = factory2.createNodeArray([...leading, namedEvaluationBlock, ...trailing]); setTextRange(members, node.members); - node = isClassDeclaration(node) ? factory2.updateClassDeclaration( - node, - node.modifiers, - node.name, - node.typeParameters, - node.heritageClauses, - members - ) : factory2.updateClassExpression( - node, - node.modifiers, - node.name, - node.typeParameters, - node.heritageClauses, - members - ); + node = isClassDeclaration(node) ? factory2.updateClassDeclaration(node, node.modifiers, node.name, node.typeParameters, node.heritageClauses, members) : factory2.updateClassExpression(node, node.modifiers, node.name, node.typeParameters, node.heritageClauses, members); getOrCreateEmitNode(node).assignedName = assignedName; return node; } @@ -90148,102 +82917,83 @@ ${lanes.join("\n")} if (ignoreEmptyStringLiteral && isStringLiteral(assignedName) && isEmptyStringLiteral(assignedName)) { return expression; } - const { factory: factory2 } = context; + const { + factory: factory2 + } = context; const innerExpression = skipOuterExpressions(expression); const updatedExpression = isClassExpression(innerExpression) ? cast(injectClassNamedEvaluationHelperBlockIfMissing(context, innerExpression, assignedName), isClassExpression) : context.getEmitHelperFactory().createSetFunctionNameHelper(innerExpression, assignedName); return factory2.restoreOuterExpressions(expression, updatedExpression); } function transformNamedEvaluationOfPropertyAssignment(context, node, ignoreEmptyStringLiteral, assignedNameText) { - const { factory: factory2 } = context; - const { assignedName, name } = getAssignedNameOfPropertyName(context, node.name, assignedNameText); + const { + factory: factory2 + } = context; + const { + assignedName, + name + } = getAssignedNameOfPropertyName(context, node.name, assignedNameText); const initializer = finishTransformNamedEvaluation(context, node.initializer, assignedName, ignoreEmptyStringLiteral); - return factory2.updatePropertyAssignment( - node, - name, - initializer - ); + return factory2.updatePropertyAssignment(node, name, initializer); } function transformNamedEvaluationOfShorthandAssignmentProperty(context, node, ignoreEmptyStringLiteral, assignedNameText) { - const { factory: factory2 } = context; + const { + factory: factory2 + } = context; const assignedName = assignedNameText !== void 0 ? factory2.createStringLiteral(assignedNameText) : getAssignedNameOfIdentifier(factory2, node.name, node.objectAssignmentInitializer); const objectAssignmentInitializer = finishTransformNamedEvaluation(context, node.objectAssignmentInitializer, assignedName, ignoreEmptyStringLiteral); - return factory2.updateShorthandPropertyAssignment( - node, - node.name, - objectAssignmentInitializer - ); + return factory2.updateShorthandPropertyAssignment(node, node.name, objectAssignmentInitializer); } function transformNamedEvaluationOfVariableDeclaration(context, node, ignoreEmptyStringLiteral, assignedNameText) { - const { factory: factory2 } = context; + const { + factory: factory2 + } = context; const assignedName = assignedNameText !== void 0 ? factory2.createStringLiteral(assignedNameText) : getAssignedNameOfIdentifier(factory2, node.name, node.initializer); const initializer = finishTransformNamedEvaluation(context, node.initializer, assignedName, ignoreEmptyStringLiteral); - return factory2.updateVariableDeclaration( - node, - node.name, - node.exclamationToken, - node.type, - initializer - ); + return factory2.updateVariableDeclaration(node, node.name, node.exclamationToken, node.type, initializer); } function transformNamedEvaluationOfParameterDeclaration(context, node, ignoreEmptyStringLiteral, assignedNameText) { - const { factory: factory2 } = context; + const { + factory: factory2 + } = context; const assignedName = assignedNameText !== void 0 ? factory2.createStringLiteral(assignedNameText) : getAssignedNameOfIdentifier(factory2, node.name, node.initializer); const initializer = finishTransformNamedEvaluation(context, node.initializer, assignedName, ignoreEmptyStringLiteral); - return factory2.updateParameterDeclaration( - node, - node.modifiers, - node.dotDotDotToken, - node.name, - node.questionToken, - node.type, - initializer - ); + return factory2.updateParameterDeclaration(node, node.modifiers, node.dotDotDotToken, node.name, node.questionToken, node.type, initializer); } function transformNamedEvaluationOfBindingElement(context, node, ignoreEmptyStringLiteral, assignedNameText) { - const { factory: factory2 } = context; + const { + factory: factory2 + } = context; const assignedName = assignedNameText !== void 0 ? factory2.createStringLiteral(assignedNameText) : getAssignedNameOfIdentifier(factory2, node.name, node.initializer); const initializer = finishTransformNamedEvaluation(context, node.initializer, assignedName, ignoreEmptyStringLiteral); - return factory2.updateBindingElement( - node, - node.dotDotDotToken, - node.propertyName, - node.name, - initializer - ); + return factory2.updateBindingElement(node, node.dotDotDotToken, node.propertyName, node.name, initializer); } function transformNamedEvaluationOfPropertyDeclaration(context, node, ignoreEmptyStringLiteral, assignedNameText) { - const { factory: factory2 } = context; - const { assignedName, name } = getAssignedNameOfPropertyName(context, node.name, assignedNameText); + var _node$questionToken7; + const { + factory: factory2 + } = context; + const { + assignedName, + name + } = getAssignedNameOfPropertyName(context, node.name, assignedNameText); const initializer = finishTransformNamedEvaluation(context, node.initializer, assignedName, ignoreEmptyStringLiteral); - return factory2.updatePropertyDeclaration( - node, - node.modifiers, - name, - node.questionToken ?? node.exclamationToken, - node.type, - initializer - ); + return factory2.updatePropertyDeclaration(node, node.modifiers, name, (_node$questionToken7 = node.questionToken) !== null && _node$questionToken7 !== void 0 ? _node$questionToken7 : node.exclamationToken, node.type, initializer); } function transformNamedEvaluationOfAssignmentExpression(context, node, ignoreEmptyStringLiteral, assignedNameText) { - const { factory: factory2 } = context; + const { + factory: factory2 + } = context; const assignedName = assignedNameText !== void 0 ? factory2.createStringLiteral(assignedNameText) : getAssignedNameOfIdentifier(factory2, node.left, node.right); const right = finishTransformNamedEvaluation(context, node.right, assignedName, ignoreEmptyStringLiteral); - return factory2.updateBinaryExpression( - node, - node.left, - node.operatorToken, - right - ); + return factory2.updateBinaryExpression(node, node.left, node.operatorToken, right); } function transformNamedEvaluationOfExportAssignment(context, node, ignoreEmptyStringLiteral, assignedNameText) { - const { factory: factory2 } = context; + const { + factory: factory2 + } = context; const assignedName = assignedNameText !== void 0 ? factory2.createStringLiteral(assignedNameText) : factory2.createStringLiteral(node.isExportEquals ? "" : "default"); const expression = finishTransformNamedEvaluation(context, node.expression, assignedName, ignoreEmptyStringLiteral); - return factory2.updateExportAssignment( - node, - node.modifiers, - expression - ); + return factory2.updateExportAssignment(node, node.modifiers, expression); } function transformNamedEvaluation(context, node, ignoreEmptyStringLiteral, assignedName) { switch (node.kind) { @@ -90268,6 +83018,7 @@ ${lanes.join("\n")} var init_namedEvaluation = __esm({ "src/compiler/transformers/namedEvaluation.ts"() { "use strict"; + init_ts2(); } }); @@ -90283,7 +83034,9 @@ ${lanes.join("\n")} if (level === 0 /* LiftRestriction */ && !hasInvalidEscape(template)) { return visitEachChild(node, visitor, context); } - const { factory: factory2 } = context; + const { + factory: factory2 + } = context; if (isNoSubstitutionTemplateLiteral(template)) { cookedStrings.push(createTemplateCooked(factory2, template)); rawStrings.push(getRawLiteral(factory2, template, currentSourceFile)); @@ -90296,29 +83049,16 @@ ${lanes.join("\n")} templateArguments.push(Debug.checkDefined(visitNode(templateSpan.expression, visitor, isExpression))); } } - const helperCall = context.getEmitHelperFactory().createTemplateObjectHelper( - factory2.createArrayLiteralExpression(cookedStrings), - factory2.createArrayLiteralExpression(rawStrings) - ); + const helperCall = context.getEmitHelperFactory().createTemplateObjectHelper(factory2.createArrayLiteralExpression(cookedStrings), factory2.createArrayLiteralExpression(rawStrings)); if (isExternalModule(currentSourceFile)) { const tempVar = factory2.createUniqueName("templateObject"); recordTaggedTemplateString(tempVar); - templateArguments[0] = factory2.createLogicalOr( - tempVar, - factory2.createAssignment( - tempVar, - helperCall - ) - ); + templateArguments[0] = factory2.createLogicalOr(tempVar, factory2.createAssignment(tempVar, helperCall)); } else { templateArguments[0] = helperCall; } - return factory2.createCallExpression( - tag, - /*typeArguments*/ - void 0, - templateArguments - ); + return factory2.createCallExpression(tag, /*typeArguments*/ + void 0, templateArguments); } function createTemplateCooked(factory2, template) { return template.templateFlags & 26656 /* IsInvalid */ ? factory2.createVoidZero() : factory2.createStringLiteral(template.text); @@ -90338,8 +83078,9 @@ ${lanes.join("\n")} var init_taggedTemplate = __esm({ "src/compiler/transformers/taggedTemplate.ts"() { "use strict"; + init_ts2(); - ProcessLevel = /* @__PURE__ */ ((ProcessLevel2) => { + ProcessLevel = /* @__PURE__ */(ProcessLevel2 => { ProcessLevel2[ProcessLevel2["LiftRestriction"] = 0] = "LiftRestriction"; ProcessLevel2[ProcessLevel2["All"] = 1] = "All"; return ProcessLevel2; @@ -90385,15 +83126,12 @@ ${lanes.join("\n")} return transformSourceFile(node); } function transformBundle(node) { - return factory2.createBundle( - node.sourceFiles.map(transformSourceFile), - mapDefined(node.prepends, (prepend) => { - if (prepend.kind === 315 /* InputFiles */) { - return createUnparsedSourceFile(prepend, "js"); - } - return prepend; - }) - ); + return factory2.createBundle(node.sourceFiles.map(transformSourceFile), mapDefined(node.prepends, prepend => { + if (prepend.kind === 315 /* InputFiles */) { + return createUnparsedSourceFile(prepend, "js"); + } + return prepend; + })); } function transformSourceFile(node) { if (node.isDeclarationFile) { @@ -90437,6 +83175,7 @@ ${lanes.join("\n")} } else { Debug.assert(node.kind === 263 /* ClassDeclaration */ || hasSyntacticModifier(node, 2048 /* Default */)); } + break; } } @@ -90496,7 +83235,7 @@ ${lanes.join("\n")} return node; } function getClassElementVisitor(parent2) { - return (node) => saveStateAndInvoke(node, (n) => classElementVisitorWorker(n, parent2)); + return node => saveStateAndInvoke(node, n => classElementVisitorWorker(n, parent2)); } function classElementVisitorWorker(node, parent2) { switch (node.kind) { @@ -90521,7 +83260,7 @@ ${lanes.join("\n")} } } function getObjectLiteralElementVisitor(parent2) { - return (node) => saveStateAndInvoke(node, (n) => objectLiteralElementVisitorWorker(n, parent2)); + return node => saveStateAndInvoke(node, n => objectLiteralElementVisitorWorker(n, parent2)); } function objectLiteralElementVisitorWorker(node, parent2) { switch (node.kind) { @@ -90546,8 +83285,7 @@ ${lanes.join("\n")} 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 */) { @@ -90669,68 +83407,38 @@ ${lanes.join("\n")} } function visitSourceFile(node) { const alwaysStrict = getStrictOptionValue(compilerOptions, "alwaysStrict") && !(isExternalModule(node) && moduleKind >= 5 /* ES2015 */) && !isJsonSourceFile(node); - return factory2.updateSourceFile( - node, - visitLexicalEnvironment( - node.statements, - sourceElementVisitor, - context, - /*start*/ - 0, - alwaysStrict - ) - ); + return factory2.updateSourceFile(node, visitLexicalEnvironment(node.statements, sourceElementVisitor, context, /*start*/ + 0, alwaysStrict)); } function visitObjectLiteralExpression(node) { - return factory2.updateObjectLiteralExpression( - node, - visitNodes2(node.properties, getObjectLiteralElementVisitor(node), isObjectLiteralElementLike) - ); + return factory2.updateObjectLiteralExpression(node, visitNodes2(node.properties, getObjectLiteralElementVisitor(node), isObjectLiteralElementLike)); } function getClassFacts(node) { let facts = 0 /* None */; - if (some(getProperties( - node, - /*requireInitializer*/ - true, - /*isStatic*/ - true - ))) - facts |= 1 /* HasStaticInitializedProperties */; + if (some(getProperties(node, /*requireInitializer*/ + true, /*isStatic*/ + true))) facts |= 1 /* HasStaticInitializedProperties */; const extendsClauseElement = getEffectiveBaseTypeNode(node); - if (extendsClauseElement && skipOuterExpressions(extendsClauseElement.expression).kind !== 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) { return !!(node.transformFlags & 8192 /* ContainsTypeScriptClassSyntax */); } + function isClassLikeDeclarationWithTypeScriptSyntax(node) { return hasDecorators(node) || some(node.typeParameters) || some(node.heritageClauses, hasTypeScriptClassSyntax) || some(node.members, hasTypeScriptClassSyntax); } function visitClassDeclaration(node) { + var _node$name; const facts = getClassFacts(node); const promoteToIIFE = languageVersion <= 1 /* ES5 */ && !!(facts & 7 /* MayNeedImmediatelyInvokedFunctionExpression */); if (!isClassLikeDeclarationWithTypeScriptSyntax(node) && !classOrConstructorParameterIsDecorated(legacyDecorators, node) && !isExportOfNamespace(node)) { - return factory2.updateClassDeclaration( - node, - visitNodes2(node.modifiers, modifierVisitor, isModifier), - node.name, - /*typeParameters*/ - void 0, - visitNodes2(node.heritageClauses, visitor, isHeritageClause), - visitNodes2(node.members, getClassElementVisitor(node), isClassElement) - ); + return factory2.updateClassDeclaration(node, visitNodes2(node.modifiers, modifierVisitor, isModifier), node.name, /*typeParameters*/ + void 0, visitNodes2(node.heritageClauses, visitor, isHeritageClause), visitNodes2(node.members, getClassElementVisitor(node), isClassElement)); } if (promoteToIIFE) { context.startLexicalEnvironment(); @@ -90741,20 +83449,14 @@ ${lanes.join("\n")} modifiers = injectClassTypeMetadata(modifiers, node); } const needsName = moveModifiers && !node.name || facts & 4 /* HasMemberDecorators */ || facts & 1 /* HasStaticInitializedProperties */; - const name = needsName ? node.name ?? factory2.getGeneratedNameForNode(node) : node.name; - const classDeclaration = factory2.updateClassDeclaration( - node, - modifiers, - name, - /*typeParameters*/ - void 0, - visitNodes2(node.heritageClauses, visitor, isHeritageClause), - transformClassMembers(node) - ); + const name = needsName ? (_node$name = node.name) !== null && _node$name !== void 0 ? _node$name : factory2.getGeneratedNameForNode(node) : node.name; + const classDeclaration = factory2.updateClassDeclaration(node, modifiers, name, /*typeParameters*/ + void 0, visitNodes2(node.heritageClauses, visitor, isHeritageClause), transformClassMembers(node)); let emitFlags = getEmitFlags(node); if (facts & 1 /* HasStaticInitializedProperties */) { emitFlags |= 64 /* NoTrailingSourceMap */; } + setEmitFlags(classDeclaration, emitFlags); let statement; if (promoteToIIFE) { @@ -90771,26 +83473,15 @@ ${lanes.join("\n")} insertStatementsAfterStandardPrologue(statements, context.endLexicalEnvironment()); const iife = factory2.createImmediatelyInvokedArrowFunction(statements); setInternalEmitFlags(iife, 1 /* TypeScriptClassWrapper */); - const varDecl = factory2.createVariableDeclaration( - factory2.getLocalName( - node, - /*allowComments*/ - false, - /*allowSourceMaps*/ - false - ), - /*exclamationToken*/ - void 0, - /*type*/ - void 0, - iife - ); + const varDecl = factory2.createVariableDeclaration(factory2.getLocalName(node, /*allowComments*/ + false, /*allowSourceMaps*/ + false), /*exclamationToken*/ + void 0, /*type*/ + void 0, iife); setOriginalNode(varDecl, node); - const varStatement = factory2.createVariableStatement( - /*modifiers*/ - void 0, - factory2.createVariableDeclarationList([varDecl], 1 /* Let */) - ); + const varStatement = factory2.createVariableStatement( /*modifiers*/ + void 0, factory2.createVariableDeclarationList([varDecl], 1 /* Let */)); + setOriginalNode(varStatement, node); setCommentRange(varStatement, node); setSourceMapRange(varStatement, moveRangePastDecorators(node)); @@ -90801,34 +83492,17 @@ ${lanes.join("\n")} } if (moveModifiers) { if (facts & 8 /* IsExportOfNamespace */) { - return [ - statement, - createExportMemberAssignmentStatement(node) - ]; + return [statement, createExportMemberAssignmentStatement(node)]; } if (facts & 32 /* IsDefaultExternalExport */) { - return [ - statement, - factory2.createExportDefault(factory2.getLocalName( - node, - /*allowComments*/ - false, - /*allowSourceMaps*/ - true - )) - ]; + return [statement, factory2.createExportDefault(factory2.getLocalName(node, /*allowComments*/ + false, /*allowSourceMaps*/ + true))]; } if (facts & 16 /* IsNamedExternalExport */) { - return [ - statement, - factory2.createExternalModuleExport(factory2.getDeclarationName( - node, - /*allowComments*/ - false, - /*allowSourceMaps*/ - true - )) - ]; + return [statement, factory2.createExternalModuleExport(factory2.getDeclarationName(node, /*allowComments*/ + false, /*allowSourceMaps*/ + true))]; } } return statement; @@ -90838,45 +83512,29 @@ ${lanes.join("\n")} if (classOrConstructorParameterIsDecorated(legacyDecorators, node)) { modifiers = injectClassTypeMetadata(modifiers, node); } - return factory2.updateClassExpression( - node, - modifiers, - node.name, - /*typeParameters*/ - void 0, - visitNodes2(node.heritageClauses, visitor, isHeritageClause), - transformClassMembers(node) - ); + return factory2.updateClassExpression(node, modifiers, node.name, /*typeParameters*/ + void 0, visitNodes2(node.heritageClauses, visitor, isHeritageClause), transformClassMembers(node)); } function transformClassMembers(node) { const members = visitNodes2(node.members, getClassElementVisitor(node), isClassElement); let newMembers; const constructor = getFirstConstructorWithBody(node); - const parametersWithPropertyAssignments = constructor && filter(constructor.parameters, (p) => isParameterPropertyDeclaration(p, constructor)); + const parametersWithPropertyAssignments = constructor && filter(constructor.parameters, p => isParameterPropertyDeclaration(p, constructor)); if (parametersWithPropertyAssignments) { for (const parameter of parametersWithPropertyAssignments) { - const parameterProperty = factory2.createPropertyDeclaration( - /*modifiers*/ - void 0, - parameter.name, - /*questionOrExclamationToken*/ - void 0, - /*type*/ - void 0, - /*initializer*/ - void 0 - ); + const parameterProperty = factory2.createPropertyDeclaration( /*modifiers*/ + void 0, parameter.name, /*questionOrExclamationToken*/ + void 0, /*type*/ + void 0, /*initializer*/ + void 0); setOriginalNode(parameterProperty, parameter); newMembers = append(newMembers, parameterProperty); } } if (newMembers) { newMembers = addRange(newMembers, members); - return setTextRange( - factory2.createNodeArray(newMembers), - /*location*/ - node.members - ); + return setTextRange(factory2.createNodeArray(newMembers), /*location*/ + node.members); } return members; } @@ -90906,23 +83564,31 @@ ${lanes.join("\n")} 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) { if (typeSerializer) { let decorators; if (shouldAddTypeMetadata(node)) { - const typeMetadata = emitHelpers().createMetadataHelper("design:type", typeSerializer.serializeTypeOfNode({ currentLexicalScope, currentNameScope: container }, node)); + const typeMetadata = emitHelpers().createMetadataHelper("design:type", typeSerializer.serializeTypeOfNode({ + currentLexicalScope, + currentNameScope: container + }, node)); decorators = append(decorators, factory2.createDecorator(typeMetadata)); } if (shouldAddParamTypesMetadata(node)) { - const paramTypesMetadata = emitHelpers().createMetadataHelper("design:paramtypes", typeSerializer.serializeParameterTypesOfNode({ currentLexicalScope, currentNameScope: container }, node, container)); + const paramTypesMetadata = emitHelpers().createMetadataHelper("design:paramtypes", typeSerializer.serializeParameterTypesOfNode({ + currentLexicalScope, + currentNameScope: container + }, node, container)); decorators = append(decorators, factory2.createDecorator(paramTypesMetadata)); } if (shouldAddReturnTypeMetadata(node)) { - const returnTypeMetadata = emitHelpers().createMetadataHelper("design:returntype", typeSerializer.serializeReturnTypeOfNode({ currentLexicalScope, currentNameScope: container }, node)); + const returnTypeMetadata = emitHelpers().createMetadataHelper("design:returntype", typeSerializer.serializeReturnTypeOfNode({ + currentLexicalScope, + currentNameScope: container + }, node)); decorators = append(decorators, factory2.createDecorator(returnTypeMetadata)); } return decorators; @@ -90932,53 +83598,38 @@ ${lanes.join("\n")} if (typeSerializer) { let properties; if (shouldAddTypeMetadata(node)) { - const typeProperty = factory2.createPropertyAssignment("type", factory2.createArrowFunction( - /*modifiers*/ - void 0, - /*typeParameters*/ - void 0, - [], - /*type*/ - void 0, - factory2.createToken(39 /* EqualsGreaterThanToken */), - typeSerializer.serializeTypeOfNode({ currentLexicalScope, currentNameScope: container }, node) - )); + const typeProperty = factory2.createPropertyAssignment("type", factory2.createArrowFunction( /*modifiers*/ + void 0, /*typeParameters*/ + void 0, [], /*type*/ + void 0, factory2.createToken(39 /* EqualsGreaterThanToken */), typeSerializer.serializeTypeOfNode({ + currentLexicalScope, + currentNameScope: container + }, node))); properties = append(properties, typeProperty); } if (shouldAddParamTypesMetadata(node)) { - const paramTypeProperty = factory2.createPropertyAssignment("paramTypes", factory2.createArrowFunction( - /*modifiers*/ - void 0, - /*typeParameters*/ - void 0, - [], - /*type*/ - void 0, - factory2.createToken(39 /* EqualsGreaterThanToken */), - typeSerializer.serializeParameterTypesOfNode({ currentLexicalScope, currentNameScope: container }, node, container) - )); + const paramTypeProperty = factory2.createPropertyAssignment("paramTypes", factory2.createArrowFunction( /*modifiers*/ + void 0, /*typeParameters*/ + void 0, [], /*type*/ + void 0, factory2.createToken(39 /* EqualsGreaterThanToken */), typeSerializer.serializeParameterTypesOfNode({ + currentLexicalScope, + currentNameScope: container + }, node, container))); properties = append(properties, paramTypeProperty); } if (shouldAddReturnTypeMetadata(node)) { - const returnTypeProperty = factory2.createPropertyAssignment("returnType", factory2.createArrowFunction( - /*modifiers*/ - void 0, - /*typeParameters*/ - void 0, - [], - /*type*/ - void 0, - factory2.createToken(39 /* EqualsGreaterThanToken */), - typeSerializer.serializeReturnTypeOfNode({ currentLexicalScope, currentNameScope: container }, node) - )); + const returnTypeProperty = factory2.createPropertyAssignment("returnType", factory2.createArrowFunction( /*modifiers*/ + void 0, /*typeParameters*/ + void 0, [], /*type*/ + void 0, factory2.createToken(39 /* EqualsGreaterThanToken */), typeSerializer.serializeReturnTypeOfNode({ + currentLexicalScope, + currentNameScope: container + }, node))); properties = append(properties, returnTypeProperty); } if (properties) { - const typeInfoMetadata = emitHelpers().createMetadataHelper("design:typeinfo", factory2.createObjectLiteralExpression( - properties, - /*multiLine*/ - true - )); + const typeInfoMetadata = emitHelpers().createMetadataHelper("design:typeinfo", factory2.createObjectLiteralExpression(properties, /*multiLine*/ + true)); return [factory2.createDecorator(typeInfoMetadata)]; } } @@ -90987,9 +83638,11 @@ ${lanes.join("\n")} const kind = node.kind; return kind === 174 /* MethodDeclaration */ || kind === 177 /* GetAccessor */ || kind === 178 /* SetAccessor */ || kind === 172 /* PropertyDeclaration */; } + function shouldAddReturnTypeMetadata(node) { return node.kind === 174 /* MethodDeclaration */; } + function shouldAddParamTypesMetadata(node) { switch (node.kind) { case 263 /* ClassDeclaration */: @@ -91035,12 +83688,8 @@ ${lanes.join("\n")} return visitEachChild(node, visitor, context); } function visitExpressionWithTypeArguments(node) { - return factory2.updateExpressionWithTypeArguments( - node, - Debug.checkDefined(visitNode(node.expression, visitor, isLeftHandSideExpression)), - /*typeArguments*/ - void 0 - ); + return factory2.updateExpressionWithTypeArguments(node, Debug.checkDefined(visitNode(node.expression, visitor, isLeftHandSideExpression)), /*typeArguments*/ + void 0); } function shouldEmitFunctionLikeDeclaration(node) { return !nodeIsMissing(node.body); @@ -91053,40 +83702,21 @@ ${lanes.join("\n")} let modifiers = isClassLike(parent2) ? !isAmbient ? visitNodes2(node.modifiers, visitor, isModifierLike) : visitNodes2(node.modifiers, modifierElidingVisitor, isModifierLike) : visitNodes2(node.modifiers, decoratorElidingVisitor, isModifierLike); modifiers = injectClassElementTypeMetadata(modifiers, node, parent2); if (isAmbient) { - return factory2.updatePropertyDeclaration( - node, - concatenate(modifiers, factory2.createModifiersFromModifierFlags(128 /* Ambient */)), - Debug.checkDefined(visitNode(node.name, visitor, isPropertyName)), - /*questionOrExclamationToken*/ - void 0, - /*type*/ - void 0, - /*initializer*/ - void 0 - ); + return factory2.updatePropertyDeclaration(node, concatenate(modifiers, factory2.createModifiersFromModifierFlags(128 /* Ambient */)), Debug.checkDefined(visitNode(node.name, visitor, isPropertyName)), /*questionOrExclamationToken*/ + void 0, /*type*/ + void 0, /*initializer*/ + void 0); } - return factory2.updatePropertyDeclaration( - node, - modifiers, - visitPropertyNameOfClassElement(node), - /*questionOrExclamationToken*/ - void 0, - /*type*/ - void 0, - visitNode(node.initializer, visitor, isExpression) - ); + return factory2.updatePropertyDeclaration(node, modifiers, visitPropertyNameOfClassElement(node), /*questionOrExclamationToken*/ + void 0, /*type*/ + void 0, visitNode(node.initializer, visitor, isExpression)); } function visitConstructor(node) { if (!shouldEmitFunctionLikeDeclaration(node)) { return void 0; } - return factory2.updateConstructorDeclaration( - node, - /*modifiers*/ - void 0, - visitParameterList(node.parameters, visitor, context), - transformConstructorBody(node.body, node) - ); + return factory2.updateConstructorDeclaration(node, /*modifiers*/ + void 0, visitParameterList(node.parameters, visitor, context), transformConstructorBody(node.body, node)); } function transformConstructorBodyWorker(statementsOut, statementsIn, statementOffset, superPath, superPathDepth, initializerStatements) { const superStatementIndex = superPath[superPathDepth]; @@ -91094,23 +83724,11 @@ ${lanes.join("\n")} addRange(statementsOut, visitNodes2(statementsIn, visitor, isStatement, statementOffset, superStatementIndex - statementOffset)); if (isTryStatement(superStatement)) { const tryBlockStatements = []; - transformConstructorBodyWorker( - tryBlockStatements, - superStatement.tryBlock.statements, - /*statementOffset*/ - 0, - superPath, - superPathDepth + 1, - initializerStatements - ); + transformConstructorBodyWorker(tryBlockStatements, superStatement.tryBlock.statements, /*statementOffset*/ + 0, superPath, superPathDepth + 1, initializerStatements); const tryBlockStatementsArray = factory2.createNodeArray(tryBlockStatements); setTextRange(tryBlockStatementsArray, superStatement.tryBlock.statements); - statementsOut.push(factory2.updateTryStatement( - superStatement, - factory2.updateBlock(superStatement.tryBlock, tryBlockStatements), - visitNode(superStatement.catchClause, visitor, isCatchClause), - visitNode(superStatement.finallyBlock, visitor, isBlock) - )); + statementsOut.push(factory2.updateTryStatement(superStatement, factory2.updateBlock(superStatement.tryBlock, tryBlockStatements), visitNode(superStatement.catchClause, visitor, isCatchClause), visitNode(superStatement.finallyBlock, visitor, isBlock))); } else { addRange(statementsOut, visitNodes2(statementsIn, visitor, isStatement, superStatementIndex, 1)); addRange(statementsOut, initializerStatements); @@ -91118,46 +83736,28 @@ ${lanes.join("\n")} addRange(statementsOut, visitNodes2(statementsIn, visitor, isStatement, superStatementIndex + 1)); } function transformConstructorBody(body, constructor) { - const parametersWithPropertyAssignments = constructor && filter(constructor.parameters, (p) => isParameterPropertyDeclaration(p, constructor)); + const parametersWithPropertyAssignments = constructor && filter(constructor.parameters, p => isParameterPropertyDeclaration(p, constructor)); if (!some(parametersWithPropertyAssignments)) { return visitFunctionBody(body, visitor, context); } let statements = []; resumeLexicalEnvironment(); - const prologueStatementCount = factory2.copyPrologue( - body.statements, - statements, - /*ensureUseStrict*/ - false, - visitor - ); + const prologueStatementCount = factory2.copyPrologue(body.statements, statements, /*ensureUseStrict*/ + false, visitor); const superPath = findSuperStatementIndexPath(body.statements, prologueStatementCount); const parameterPropertyAssignments = mapDefined(parametersWithPropertyAssignments, transformParameterWithPropertyAssignment); if (superPath.length) { - transformConstructorBodyWorker( - statements, - body.statements, - prologueStatementCount, - superPath, - /*superPathDepth*/ - 0, - parameterPropertyAssignments - ); + transformConstructorBodyWorker(statements, body.statements, prologueStatementCount, superPath, /*superPathDepth*/ + 0, parameterPropertyAssignments); } else { addRange(statements, parameterPropertyAssignments); addRange(statements, visitNodes2(body.statements, visitor, isStatement, prologueStatementCount)); } statements = factory2.mergeLexicalEnvironment(statements, endLexicalEnvironment()); - const block = factory2.createBlock( - setTextRange(factory2.createNodeArray(statements), body.statements), - /*multiLine*/ - true - ); - setTextRange( - block, - /*location*/ - body - ); + const block = factory2.createBlock(setTextRange(factory2.createNodeArray(statements), body.statements), /*multiLine*/ + true); + setTextRange(block, /*location*/ + body); setOriginalNode(block, body); return block; } @@ -91170,28 +83770,7 @@ ${lanes.join("\n")} setEmitFlags(propertyName, 3072 /* NoComments */ | 96 /* NoSourceMap */); const localName = setParent(setTextRange(factory2.cloneNode(name), name), name.parent); setEmitFlags(localName, 3072 /* NoComments */); - return startOnNewLine( - removeAllComments( - setTextRange( - setOriginalNode( - factory2.createExpressionStatement( - factory2.createAssignment( - setTextRange( - factory2.createPropertyAccessExpression( - factory2.createThis(), - propertyName - ), - node.name - ), - localName - ) - ), - node - ), - moveRangePos(node, -1) - ) - ) - ); + return startOnNewLine(removeAllComments(setTextRange(setOriginalNode(factory2.createExpressionStatement(factory2.createAssignment(setTextRange(factory2.createPropertyAccessExpression(factory2.createThis(), propertyName), node.name), localName)), node), moveRangePos(node, -1)))); } function visitMethodDeclaration(node, parent2) { if (!(node.transformFlags & 1 /* ContainsTypeScript */)) { @@ -91202,24 +83781,15 @@ ${lanes.join("\n")} } let modifiers = isClassLike(parent2) ? visitNodes2(node.modifiers, visitor, isModifierLike) : visitNodes2(node.modifiers, decoratorElidingVisitor, isModifierLike); modifiers = injectClassElementTypeMetadata(modifiers, node, parent2); - return factory2.updateMethodDeclaration( - node, - modifiers, - node.asteriskToken, - visitPropertyNameOfClassElement(node), - /*questionToken*/ - void 0, - /*typeParameters*/ - void 0, - visitParameterList(node.parameters, visitor, context), - /*type*/ - void 0, - visitFunctionBody(node.body, visitor, context) - ); + return factory2.updateMethodDeclaration(node, modifiers, node.asteriskToken, visitPropertyNameOfClassElement(node), /*questionToken*/ + void 0, /*typeParameters*/ + void 0, visitParameterList(node.parameters, visitor, context), /*type*/ + void 0, visitFunctionBody(node.body, visitor, context)); } function shouldEmitAccessorDeclaration(node) { return !(nodeIsMissing(node.body) && hasSyntacticModifier(node, 64 /* Abstract */)); } + function visitGetAccessor(node, parent2) { if (!(node.transformFlags & 1 /* ContainsTypeScript */)) { return node; @@ -91229,15 +83799,8 @@ ${lanes.join("\n")} } let modifiers = isClassLike(parent2) ? visitNodes2(node.modifiers, visitor, isModifierLike) : visitNodes2(node.modifiers, decoratorElidingVisitor, isModifierLike); modifiers = injectClassElementTypeMetadata(modifiers, node, parent2); - return factory2.updateGetAccessorDeclaration( - node, - modifiers, - visitPropertyNameOfClassElement(node), - visitParameterList(node.parameters, visitor, context), - /*type*/ - void 0, - visitFunctionBody(node.body, visitor, context) || factory2.createBlock([]) - ); + return factory2.updateGetAccessorDeclaration(node, modifiers, visitPropertyNameOfClassElement(node), visitParameterList(node.parameters, visitor, context), /*type*/ + void 0, visitFunctionBody(node.body, visitor, context) || factory2.createBlock([])); } function visitSetAccessor(node, parent2) { if (!(node.transformFlags & 1 /* ContainsTypeScript */)) { @@ -91248,30 +83811,15 @@ ${lanes.join("\n")} } let modifiers = isClassLike(parent2) ? visitNodes2(node.modifiers, visitor, isModifierLike) : visitNodes2(node.modifiers, decoratorElidingVisitor, isModifierLike); modifiers = injectClassElementTypeMetadata(modifiers, node, parent2); - return factory2.updateSetAccessorDeclaration( - node, - modifiers, - visitPropertyNameOfClassElement(node), - visitParameterList(node.parameters, visitor, context), - visitFunctionBody(node.body, visitor, context) || factory2.createBlock([]) - ); + return factory2.updateSetAccessorDeclaration(node, modifiers, visitPropertyNameOfClassElement(node), visitParameterList(node.parameters, visitor, context), visitFunctionBody(node.body, visitor, context) || factory2.createBlock([])); } function visitFunctionDeclaration(node) { if (!shouldEmitFunctionLikeDeclaration(node)) { return factory2.createNotEmittedStatement(node); } - const updated = factory2.updateFunctionDeclaration( - node, - visitNodes2(node.modifiers, modifierVisitor, isModifier), - node.asteriskToken, - node.name, - /*typeParameters*/ - void 0, - visitParameterList(node.parameters, visitor, context), - /*type*/ - void 0, - visitFunctionBody(node.body, visitor, context) || factory2.createBlock([]) - ); + const updated = factory2.updateFunctionDeclaration(node, visitNodes2(node.modifiers, modifierVisitor, isModifier), node.asteriskToken, node.name, /*typeParameters*/ + void 0, visitParameterList(node.parameters, visitor, context), /*type*/ + void 0, visitFunctionBody(node.body, visitor, context) || factory2.createBlock([])); if (isExportOfNamespace(node)) { const statements = [updated]; addExportMemberAssignment(statements, node); @@ -91283,55 +83831,31 @@ ${lanes.join("\n")} if (!shouldEmitFunctionLikeDeclaration(node)) { return factory2.createOmittedExpression(); } - const updated = factory2.updateFunctionExpression( - node, - visitNodes2(node.modifiers, modifierVisitor, isModifier), - node.asteriskToken, - node.name, - /*typeParameters*/ - void 0, - visitParameterList(node.parameters, visitor, context), - /*type*/ - void 0, - visitFunctionBody(node.body, visitor, context) || factory2.createBlock([]) - ); + const updated = factory2.updateFunctionExpression(node, visitNodes2(node.modifiers, modifierVisitor, isModifier), node.asteriskToken, node.name, /*typeParameters*/ + void 0, visitParameterList(node.parameters, visitor, context), /*type*/ + void 0, visitFunctionBody(node.body, visitor, context) || factory2.createBlock([])); return updated; } function visitArrowFunction(node) { - const updated = factory2.updateArrowFunction( - node, - visitNodes2(node.modifiers, modifierVisitor, isModifier), - /*typeParameters*/ - void 0, - visitParameterList(node.parameters, visitor, context), - /*type*/ - void 0, - node.equalsGreaterThanToken, - visitFunctionBody(node.body, visitor, context) - ); + const updated = factory2.updateArrowFunction(node, visitNodes2(node.modifiers, modifierVisitor, isModifier), /*typeParameters*/ + void 0, visitParameterList(node.parameters, visitor, context), /*type*/ + void 0, node.equalsGreaterThanToken, visitFunctionBody(node.body, visitor, context)); return updated; } function visitParameter(node) { if (parameterIsThisKeyword(node)) { return void 0; } - const updated = factory2.updateParameterDeclaration( - node, - visitNodes2(node.modifiers, (node2) => isDecorator(node2) ? visitor(node2) : void 0, isModifierLike), - node.dotDotDotToken, - Debug.checkDefined(visitNode(node.name, visitor, isBindingName)), - /*questionToken*/ - void 0, - /*type*/ - void 0, - visitNode(node.initializer, visitor, isExpression) - ); + const updated = factory2.updateParameterDeclaration(node, visitNodes2(node.modifiers, node2 => isDecorator(node2) ? visitor(node2) : void 0, isModifierLike), node.dotDotDotToken, Debug.checkDefined(visitNode(node.name, visitor, isBindingName)), /*questionToken*/ + void 0, /*type*/ + void 0, visitNode(node.initializer, visitor, isExpression)); if (updated !== node) { setCommentRange(updated, node); setTextRange(updated, moveRangePastModifiers(node)); setSourceMapRange(updated, moveRangePastModifiers(node)); setEmitFlags(updated.name, 64 /* NoTrailingSourceMap */); } + return updated; } function visitVariableStatement(node) { @@ -91340,14 +83864,7 @@ ${lanes.join("\n")} if (variables.length === 0) { return void 0; } - return setTextRange( - factory2.createExpressionStatement( - factory2.inlineExpressions( - map(variables, transformInitializedVariable) - ) - ), - node - ); + return setTextRange(factory2.createExpressionStatement(factory2.inlineExpressions(map(variables, transformInitializedVariable))), node); } else { return visitEachChild(node, visitor, context); } @@ -91355,36 +83872,17 @@ ${lanes.join("\n")} function transformInitializedVariable(node) { const name = node.name; if (isBindingPattern(name)) { - return flattenDestructuringAssignment( - node, - visitor, - context, - 0 /* All */, - /*needsValue*/ - false, - createNamespaceExportExpression - ); + return flattenDestructuringAssignment(node, visitor, context, 0 /* All */, /*needsValue*/ + false, createNamespaceExportExpression); } else { - return setTextRange( - factory2.createAssignment( - getNamespaceMemberNameWithSourceMapsAndWithoutComments(name), - Debug.checkDefined(visitNode(node.initializer, visitor, isExpression)) - ), - /*location*/ - node - ); + return setTextRange(factory2.createAssignment(getNamespaceMemberNameWithSourceMapsAndWithoutComments(name), Debug.checkDefined(visitNode(node.initializer, visitor, isExpression))), /*location*/ + node); } } function visitVariableDeclaration(node) { - const updated = factory2.updateVariableDeclaration( - node, - Debug.checkDefined(visitNode(node.name, visitor, isBindingName)), - /*exclamationToken*/ - void 0, - /*type*/ - void 0, - visitNode(node.initializer, visitor, isExpression) - ); + const updated = factory2.updateVariableDeclaration(node, Debug.checkDefined(visitNode(node.name, visitor, isBindingName)), /*exclamationToken*/ + void 0, /*type*/ + void 0, visitNode(node.initializer, visitor, isExpression)); if (node.type) { setTypeNode(updated.name, node.type); } @@ -91415,49 +83913,24 @@ ${lanes.join("\n")} return factory2.createPartiallyEmittedExpression(expression, node); } function visitCallExpression(node) { - return factory2.updateCallExpression( - node, - Debug.checkDefined(visitNode(node.expression, visitor, isExpression)), - /*typeArguments*/ - void 0, - visitNodes2(node.arguments, visitor, isExpression) - ); + return factory2.updateCallExpression(node, Debug.checkDefined(visitNode(node.expression, visitor, isExpression)), /*typeArguments*/ + void 0, visitNodes2(node.arguments, visitor, isExpression)); } function visitNewExpression(node) { - return factory2.updateNewExpression( - node, - Debug.checkDefined(visitNode(node.expression, visitor, isExpression)), - /*typeArguments*/ - void 0, - visitNodes2(node.arguments, visitor, isExpression) - ); + return factory2.updateNewExpression(node, Debug.checkDefined(visitNode(node.expression, visitor, isExpression)), /*typeArguments*/ + void 0, visitNodes2(node.arguments, visitor, isExpression)); } function visitTaggedTemplateExpression(node) { - return factory2.updateTaggedTemplateExpression( - node, - Debug.checkDefined(visitNode(node.tag, visitor, isExpression)), - /*typeArguments*/ - void 0, - Debug.checkDefined(visitNode(node.template, visitor, isTemplateLiteral)) - ); + return factory2.updateTaggedTemplateExpression(node, Debug.checkDefined(visitNode(node.tag, visitor, isExpression)), /*typeArguments*/ + void 0, Debug.checkDefined(visitNode(node.template, visitor, isTemplateLiteral))); } function visitJsxSelfClosingElement(node) { - return factory2.updateJsxSelfClosingElement( - node, - Debug.checkDefined(visitNode(node.tagName, visitor, isJsxTagNameExpression)), - /*typeArguments*/ - void 0, - Debug.checkDefined(visitNode(node.attributes, visitor, isJsxAttributes)) - ); + return factory2.updateJsxSelfClosingElement(node, Debug.checkDefined(visitNode(node.tagName, visitor, isJsxTagNameExpression)), /*typeArguments*/ + void 0, Debug.checkDefined(visitNode(node.attributes, visitor, isJsxAttributes))); } function visitJsxJsxOpeningElement(node) { - return factory2.updateJsxOpeningElement( - node, - Debug.checkDefined(visitNode(node.tagName, visitor, isJsxTagNameExpression)), - /*typeArguments*/ - void 0, - Debug.checkDefined(visitNode(node.attributes, visitor, isJsxAttributes)) - ); + return factory2.updateJsxOpeningElement(node, Debug.checkDefined(visitNode(node.tagName, visitor, isJsxTagNameExpression)), /*typeArguments*/ + void 0, Debug.checkDefined(visitNode(node.attributes, visitor, isJsxAttributes))); } function shouldEmitEnumDeclaration(node) { return !isEnumConst(node) || shouldPreserveConstEnums(compilerOptions); @@ -91474,66 +83947,30 @@ ${lanes.join("\n")} emitFlags |= 1024 /* NoLeadingComments */; } } + const parameterName = getNamespaceParameterName(node); const containerName = getNamespaceContainerName(node); - const exportName = isExportOfNamespace(node) ? factory2.getExternalModuleOrNamespaceExportName( - currentNamespaceContainerName, - node, - /*allowComments*/ - false, - /*allowSourceMaps*/ - true - ) : factory2.getDeclarationName( - node, - /*allowComments*/ - false, - /*allowSourceMaps*/ - true - ); - let moduleArg = factory2.createLogicalOr( - exportName, - factory2.createAssignment( - exportName, - factory2.createObjectLiteralExpression() - ) - ); + const exportName = isExportOfNamespace(node) ? factory2.getExternalModuleOrNamespaceExportName(currentNamespaceContainerName, node, /*allowComments*/ + false, /*allowSourceMaps*/ + true) : factory2.getDeclarationName(node, /*allowComments*/ + false, /*allowSourceMaps*/ + true); + let moduleArg = factory2.createLogicalOr(exportName, factory2.createAssignment(exportName, factory2.createObjectLiteralExpression())); if (isExportOfNamespace(node)) { - const localName = factory2.getLocalName( - node, - /*allowComments*/ - false, - /*allowSourceMaps*/ - true - ); + const localName = factory2.getLocalName(node, /*allowComments*/ + false, /*allowSourceMaps*/ + true); moduleArg = factory2.createAssignment(localName, moduleArg); } - const enumStatement = factory2.createExpressionStatement( - factory2.createCallExpression( - factory2.createFunctionExpression( - /*modifiers*/ - void 0, - /*asteriskToken*/ - void 0, - /*name*/ - void 0, - /*typeParameters*/ - void 0, - [factory2.createParameterDeclaration( - /*modifiers*/ - void 0, - /*dotDotDotToken*/ - void 0, - parameterName - )], - /*type*/ - void 0, - transformEnumBody(node, containerName) - ), - /*typeArguments*/ - void 0, - [moduleArg] - ) - ); + const enumStatement = factory2.createExpressionStatement(factory2.createCallExpression(factory2.createFunctionExpression( /*modifiers*/ + void 0, /*asteriskToken*/ + void 0, /*name*/ + void 0, /*typeParameters*/ + void 0, [factory2.createParameterDeclaration( /*modifiers*/ + void 0, /*dotDotDotToken*/ + void 0, parameterName)], /*type*/ + void 0, transformEnumBody(node, containerName)), /*typeArguments*/ + void 0, [moduleArg])); setOriginalNode(enumStatement, node); if (varAdded) { setSyntheticLeadingComments(enumStatement, void 0); @@ -91553,46 +83990,17 @@ ${lanes.join("\n")} insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment()); addRange(statements, members); currentNamespaceContainerName = savedCurrentNamespaceLocalName; - return factory2.createBlock( - setTextRange( - factory2.createNodeArray(statements), - /*location*/ - node.members - ), - /*multiLine*/ - true - ); + return factory2.createBlock(setTextRange(factory2.createNodeArray(statements), /*location*/ + node.members), /*multiLine*/ + true); } function transformEnumMember(member) { - const name = getExpressionForPropertyName( - member, - /*generateNameForComputedPropertyName*/ - false - ); + const name = getExpressionForPropertyName(member, /*generateNameForComputedPropertyName*/ + false); const valueExpression = transformEnumMemberDeclarationValue(member); - const innerAssignment = factory2.createAssignment( - factory2.createElementAccessExpression( - currentNamespaceContainerName, - name - ), - valueExpression - ); - const outerAssignment = valueExpression.kind === 11 /* StringLiteral */ ? innerAssignment : factory2.createAssignment( - factory2.createElementAccessExpression( - currentNamespaceContainerName, - innerAssignment - ), - name - ); - return setTextRange( - factory2.createExpressionStatement( - setTextRange( - outerAssignment, - member - ) - ), - member - ); + const innerAssignment = factory2.createAssignment(factory2.createElementAccessExpression(currentNamespaceContainerName, name), valueExpression); + const outerAssignment = valueExpression.kind === 11 /* StringLiteral */ ? innerAssignment : factory2.createAssignment(factory2.createElementAccessExpression(currentNamespaceContainerName, innerAssignment), name); + return setTextRange(factory2.createExpressionStatement(setTextRange(outerAssignment, member)), member); } function transformEnumMemberDeclarationValue(member) { const value = resolver.getConstantValue(member); @@ -91616,7 +84024,7 @@ ${lanes.join("\n")} } function recordEmittedDeclarationInScope(node) { if (!currentScopeFirstDeclarationsOfName) { - currentScopeFirstDeclarationsOfName = /* @__PURE__ */ new Map(); + currentScopeFirstDeclarationsOfName = /* @__PURE__ */new Map(); } const name = declaredNameInScope(node); if (!currentScopeFirstDeclarationsOfName.has(name)) { @@ -91635,18 +84043,11 @@ ${lanes.join("\n")} return node.name.escapedText; } function addVarForEnumOrModuleDeclaration(statements, node) { - const varDecl = factory2.createVariableDeclaration(factory2.getLocalName( - node, - /*allowComments*/ - false, - /*allowSourceMaps*/ - true - )); + const varDecl = factory2.createVariableDeclaration(factory2.getLocalName(node, /*allowComments*/ + false, /*allowSourceMaps*/ + true)); const varFlags = currentLexicalScope.kind === 312 /* SourceFile */ ? 0 /* None */ : 1 /* Let */; - const statement = factory2.createVariableStatement( - visitNodes2(node.modifiers, modifierVisitor, isModifier), - factory2.createVariableDeclarationList([varDecl], varFlags) - ); + const statement = factory2.createVariableStatement(visitNodes2(node.modifiers, modifierVisitor, isModifier), factory2.createVariableDeclarationList([varDecl], varFlags)); setOriginalNode(varDecl, node); setSyntheticLeadingComments(varDecl, void 0); setSyntheticTrailingComments(varDecl, void 0); @@ -91679,66 +84080,30 @@ ${lanes.join("\n")} emitFlags |= 1024 /* NoLeadingComments */; } } + const parameterName = getNamespaceParameterName(node); const containerName = getNamespaceContainerName(node); - const exportName = isExportOfNamespace(node) ? factory2.getExternalModuleOrNamespaceExportName( - currentNamespaceContainerName, - node, - /*allowComments*/ - false, - /*allowSourceMaps*/ - true - ) : factory2.getDeclarationName( - node, - /*allowComments*/ - false, - /*allowSourceMaps*/ - true - ); - let moduleArg = factory2.createLogicalOr( - exportName, - factory2.createAssignment( - exportName, - factory2.createObjectLiteralExpression() - ) - ); + const exportName = isExportOfNamespace(node) ? factory2.getExternalModuleOrNamespaceExportName(currentNamespaceContainerName, node, /*allowComments*/ + false, /*allowSourceMaps*/ + true) : factory2.getDeclarationName(node, /*allowComments*/ + false, /*allowSourceMaps*/ + true); + let moduleArg = factory2.createLogicalOr(exportName, factory2.createAssignment(exportName, factory2.createObjectLiteralExpression())); if (isExportOfNamespace(node)) { - const localName = factory2.getLocalName( - node, - /*allowComments*/ - false, - /*allowSourceMaps*/ - true - ); + const localName = factory2.getLocalName(node, /*allowComments*/ + false, /*allowSourceMaps*/ + true); moduleArg = factory2.createAssignment(localName, moduleArg); } - const moduleStatement = factory2.createExpressionStatement( - factory2.createCallExpression( - factory2.createFunctionExpression( - /*modifiers*/ - void 0, - /*asteriskToken*/ - void 0, - /*name*/ - void 0, - /*typeParameters*/ - void 0, - [factory2.createParameterDeclaration( - /*modifiers*/ - void 0, - /*dotDotDotToken*/ - void 0, - parameterName - )], - /*type*/ - void 0, - transformModuleBody(node, containerName) - ), - /*typeArguments*/ - void 0, - [moduleArg] - ) - ); + const moduleStatement = factory2.createExpressionStatement(factory2.createCallExpression(factory2.createFunctionExpression( /*modifiers*/ + void 0, /*asteriskToken*/ + void 0, /*name*/ + void 0, /*typeParameters*/ + void 0, [factory2.createParameterDeclaration( /*modifiers*/ + void 0, /*dotDotDotToken*/ + void 0, parameterName)], /*type*/ + void 0, transformModuleBody(node, containerName)), /*typeArguments*/ + void 0, [moduleArg])); setOriginalNode(moduleStatement, node); if (varAdded) { setSyntheticLeadingComments(moduleStatement, void 0); @@ -91762,7 +84127,7 @@ ${lanes.join("\n")} let blockLocation; if (node.body) { if (node.body.kind === 268 /* ModuleBlock */) { - saveStateAndInvoke(node.body, (body) => addRange(statements, visitNodes2(body.statements, namespaceElementVisitor, isStatement))); + saveStateAndInvoke(node.body, body => addRange(statements, visitNodes2(body.statements, namespaceElementVisitor, isStatement))); statementsLocation = node.body.statements; blockLocation = node.body; } else { @@ -91782,19 +84147,14 @@ ${lanes.join("\n")} currentNamespaceContainerName = savedCurrentNamespaceContainerName; currentNamespace = savedCurrentNamespace; currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName; - const block = factory2.createBlock( - setTextRange( - factory2.createNodeArray(statements), - /*location*/ - statementsLocation - ), - /*multiLine*/ - true - ); + const block = factory2.createBlock(setTextRange(factory2.createNodeArray(statements), /*location*/ + statementsLocation), /*multiLine*/ + true); setTextRange(block, blockLocation); if (!node.body || node.body.kind !== 268 /* ModuleBlock */) { setEmitFlags(block, getEmitFlags(block) | 3072 /* NoComments */); } + return block; } function getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration) { @@ -91811,26 +84171,15 @@ ${lanes.join("\n")} return void 0; } const importClause = visitNode(node.importClause, visitImportClause, isImportClause); - return importClause || compilerOptions.importsNotUsedAsValues === 1 /* Preserve */ || compilerOptions.importsNotUsedAsValues === 2 /* Error */ ? factory2.updateImportDeclaration( - node, - /*modifiers*/ - void 0, - importClause, - node.moduleSpecifier, - node.attributes - ) : void 0; + return importClause || compilerOptions.importsNotUsedAsValues === 1 /* Preserve */ || compilerOptions.importsNotUsedAsValues === 2 /* Error */ ? factory2.updateImportDeclaration(node, /*modifiers*/ + void 0, importClause, node.moduleSpecifier, node.attributes) : void 0; } function visitImportClause(node) { Debug.assert(!node.isTypeOnly); const name = shouldEmitAliasDeclaration(node) ? node.name : void 0; const namedBindings = visitNode(node.namedBindings, visitNamedImportBindings, isNamedImportBindings); - return name || namedBindings ? factory2.updateImportClause( - node, - /*isTypeOnly*/ - false, - name, - namedBindings - ) : void 0; + return name || namedBindings ? factory2.updateImportClause(node, /*isTypeOnly*/ + false, name, namedBindings) : void 0; } function visitNamedImportBindings(node) { if (node.kind === 274 /* NamespaceImport */) { @@ -91855,20 +84204,9 @@ ${lanes.join("\n")} return node; } const allowEmpty = compilerOptions.verbatimModuleSyntax || !!node.moduleSpecifier && (compilerOptions.importsNotUsedAsValues === 1 /* Preserve */ || compilerOptions.importsNotUsedAsValues === 2 /* Error */); - const exportClause = visitNode( - node.exportClause, - (bindings) => visitNamedExportBindings(bindings, allowEmpty), - isNamedExportBindings - ); - return exportClause ? factory2.updateExportDeclaration( - node, - /*modifiers*/ - void 0, - node.isTypeOnly, - exportClause, - node.moduleSpecifier, - node.attributes - ) : void 0; + const exportClause = visitNode(node.exportClause, bindings => visitNamedExportBindings(bindings, allowEmpty), isNamedExportBindings); + return exportClause ? factory2.updateExportDeclaration(node, /*modifiers*/ + void 0, node.isTypeOnly, exportClause, node.moduleSpecifier, node.attributes) : void 0; } function visitNamedExports(node, allowEmpty) { const elements = visitNodes2(node.elements, visitExportSpecifier, isExportSpecifier); @@ -91893,21 +84231,10 @@ ${lanes.join("\n")} if (isExternalModuleImportEqualsDeclaration(node)) { const isReferenced = shouldEmitAliasDeclaration(node); if (!isReferenced && compilerOptions.importsNotUsedAsValues === 1 /* Preserve */) { - return setOriginalNode( - setTextRange( - factory2.createImportDeclaration( - /*modifiers*/ - void 0, - /*importClause*/ - void 0, - node.moduleReference.expression, - /*attributes*/ - void 0 - ), - node - ), - node - ); + return setOriginalNode(setTextRange(factory2.createImportDeclaration( /*modifiers*/ + void 0, /*importClause*/ + void 0, node.moduleReference.expression, /*attributes*/ + void 0), node), node); } return isReferenced ? visitEachChild(node, visitor, context) : void 0; } @@ -91917,63 +84244,33 @@ ${lanes.join("\n")} const moduleReference = createExpressionFromEntityName(factory2, node.moduleReference); setEmitFlags(moduleReference, 3072 /* NoComments */ | 4096 /* NoNestedComments */); if (isNamedExternalModuleExport(node) || !isExportOfNamespace(node)) { - return setOriginalNode( - setTextRange( - factory2.createVariableStatement( - visitNodes2(node.modifiers, modifierVisitor, isModifier), - factory2.createVariableDeclarationList([ - setOriginalNode( - factory2.createVariableDeclaration( - node.name, - /*exclamationToken*/ - void 0, - /*type*/ - void 0, - moduleReference - ), - node - ) - ]) - ), - node - ), - node - ); + return setOriginalNode(setTextRange(factory2.createVariableStatement(visitNodes2(node.modifiers, modifierVisitor, isModifier), factory2.createVariableDeclarationList([setOriginalNode(factory2.createVariableDeclaration(node.name, /*exclamationToken*/ + void 0, /*type*/ + void 0, moduleReference), node)])), node), node); } else { - return setOriginalNode( - createNamespaceExport( - node.name, - moduleReference, - node - ), - node - ); + return setOriginalNode(createNamespaceExport(node.name, moduleReference, node), node); } } function isExportOfNamespace(node) { return currentNamespace !== void 0 && hasSyntacticModifier(node, 32 /* Export */); } + function isExternalModuleExport(node) { return currentNamespace === void 0 && hasSyntacticModifier(node, 32 /* Export */); } + function isNamedExternalModuleExport(node) { return isExternalModuleExport(node) && !hasSyntacticModifier(node, 2048 /* Default */); } + function isDefaultExternalModuleExport(node) { return isExternalModuleExport(node) && hasSyntacticModifier(node, 2048 /* Default */); } + function createExportMemberAssignmentStatement(node) { - const expression = factory2.createAssignment( - factory2.getExternalModuleOrNamespaceExportName( - currentNamespaceContainerName, - node, - /*allowComments*/ - false, - /*allowSourceMaps*/ - true - ), - factory2.getLocalName(node) - ); + const expression = factory2.createAssignment(factory2.getExternalModuleOrNamespaceExportName(currentNamespaceContainerName, node, /*allowComments*/ + false, /*allowSourceMaps*/ + true), factory2.getLocalName(node)); setSourceMapRange(expression, createRange(node.name ? node.name.pos : node.pos, node.end)); const statement = factory2.createExpressionStatement(expression); setSourceMapRange(statement, createRange(-1, node.end)); @@ -91983,35 +84280,17 @@ ${lanes.join("\n")} statements.push(createExportMemberAssignmentStatement(node)); } function createNamespaceExport(exportName, exportValue, location) { - return setTextRange( - factory2.createExpressionStatement( - factory2.createAssignment( - factory2.getNamespaceMemberName( - currentNamespaceContainerName, - exportName, - /*allowComments*/ - false, - /*allowSourceMaps*/ - true - ), - exportValue - ) - ), - location - ); + return setTextRange(factory2.createExpressionStatement(factory2.createAssignment(factory2.getNamespaceMemberName(currentNamespaceContainerName, exportName, /*allowComments*/ + false, /*allowSourceMaps*/ + true), exportValue)), location); } function createNamespaceExportExpression(exportName, exportValue, location) { return setTextRange(factory2.createAssignment(getNamespaceMemberNameWithSourceMapsAndWithoutComments(exportName), exportValue), location); } function getNamespaceMemberNameWithSourceMapsAndWithoutComments(name) { - return factory2.getNamespaceMemberName( - currentNamespaceContainerName, - name, - /*allowComments*/ - false, - /*allowSourceMaps*/ - true - ); + return factory2.getNamespaceMemberName(currentNamespaceContainerName, name, /*allowComments*/ + false, /*allowSourceMaps*/ + true); } function getNamespaceParameterName(node) { const name = factory2.getGeneratedNameForNode(node); @@ -92027,6 +84306,7 @@ ${lanes.join("\n")} context.enableSubstitution(80 /* Identifier */); } } + function enableSubstitutionForNamespaceExports() { if ((enabledSubstitutions & 2 /* NamespaceExports */) === 0) { enabledSubstitutions |= 2 /* NamespaceExports */; @@ -92035,12 +84315,15 @@ ${lanes.join("\n")} context.enableEmitNotification(267 /* ModuleDeclaration */); } } + function isTransformedModuleDeclaration(node) { return getOriginalNode(node).kind === 267 /* ModuleDeclaration */; } + function isTransformedEnumDeclaration(node) { return getOriginalNode(node).kind === 266 /* EnumDeclaration */; } + function onEmitNode(hint, node, emitCallback) { const savedApplicableSubstitutions = applicableSubstitutions; const savedCurrentSourceFile = currentSourceFile; @@ -92050,9 +84333,11 @@ ${lanes.join("\n")} if (enabledSubstitutions & 2 /* NamespaceExports */ && isTransformedModuleDeclaration(node)) { applicableSubstitutions |= 2 /* NamespaceExports */; } + if (enabledSubstitutions & 8 /* NonQualifiedEnumMembers */ && isTransformedEnumDeclaration(node)) { applicableSubstitutions |= 8 /* NonQualifiedEnumMembers */; } + previousOnEmitNode(hint, node, emitCallback); applicableSubstitutions = savedApplicableSubstitutions; currentSourceFile = savedCurrentSourceFile; @@ -92096,19 +84381,13 @@ ${lanes.join("\n")} } function trySubstituteNamespaceExportedName(node) { if (enabledSubstitutions & applicableSubstitutions && !isGeneratedIdentifier(node) && !isLocalName(node)) { - const container = resolver.getReferencedExportContainer( - node, - /*prefixLocals*/ - false - ); + const container = resolver.getReferencedExportContainer(node, /*prefixLocals*/ + false); if (container && container.kind !== 312 /* SourceFile */) { const substitute = applicableSubstitutions & 2 /* NamespaceExports */ && container.kind === 267 /* ModuleDeclaration */ || applicableSubstitutions & 8 /* NonQualifiedEnumMembers */ && container.kind === 266 /* EnumDeclaration */; if (substitute) { - return setTextRange( - factory2.createPropertyAccessExpression(factory2.getGeneratedNameForNode(container), node), - /*location*/ - node - ); + return setTextRange(factory2.createPropertyAccessExpression(factory2.getGeneratedNameForNode(container), node), /*location*/ + node); } } } @@ -92150,6 +84429,7 @@ ${lanes.join("\n")} var init_ts = __esm({ "src/compiler/transformers/ts.ts"() { "use strict"; + init_ts2(); USE_NEW_TYPE_METADATA_FORMAT = false; } @@ -92189,8 +84469,8 @@ ${lanes.join("\n")} let pendingExpressions; let pendingStatements; let lexicalEnvironment; - const lexicalEnvironmentMap = /* @__PURE__ */ new Map(); - const noSubstitution = /* @__PURE__ */ new Set(); + const lexicalEnvironmentMap = /* @__PURE__ */new Map(); + const noSubstitution = /* @__PURE__ */new Set(); let currentClassContainer; let currentClassElement; let shouldSubstituteThisWithClassThis = false; @@ -92251,23 +84531,14 @@ ${lanes.join("\n")} return visitElementAccessExpression(node); case 224 /* PrefixUnaryExpression */: case 225 /* PostfixUnaryExpression */: - return visitPreOrPostfixUnaryExpression( - node, - /*discarded*/ - false - ); + return visitPreOrPostfixUnaryExpression(node, /*discarded*/ + false); case 226 /* BinaryExpression */: - return visitBinaryExpression( - node, - /*discarded*/ - false - ); + return visitBinaryExpression(node, /*discarded*/ + false); case 217 /* ParenthesizedExpression */: - return visitParenthesizedExpression( - node, - /*discarded*/ - false - ); + return visitParenthesizedExpression(node, /*discarded*/ + false); case 213 /* CallExpression */: return visitCallExpression(node); case 244 /* ExpressionStatement */: @@ -92280,22 +84551,15 @@ ${lanes.join("\n")} return visitThisExpression(node); case 262 /* FunctionDeclaration */: case 218 /* FunctionExpression */: - return setCurrentClassElementAnd( - /*classElement*/ - void 0, - fallbackVisitor, - node - ); + return setCurrentClassElementAnd( /*classElement*/ + void 0, fallbackVisitor, node); case 176 /* Constructor */: case 174 /* MethodDeclaration */: case 177 /* GetAccessor */: - case 178 /* SetAccessor */: { - return setCurrentClassElementAnd( - node, - fallbackVisitor, - node - ); - } + case 178 /* SetAccessor */: + { + return setCurrentClassElementAnd(node, fallbackVisitor, node); + } default: return fallbackVisitor(node); } @@ -92307,29 +84571,17 @@ ${lanes.join("\n")} switch (node.kind) { case 224 /* PrefixUnaryExpression */: case 225 /* PostfixUnaryExpression */: - return visitPreOrPostfixUnaryExpression( - node, - /*discarded*/ - true - ); + return visitPreOrPostfixUnaryExpression(node, /*discarded*/ + true); case 226 /* BinaryExpression */: - return visitBinaryExpression( - node, - /*discarded*/ - true - ); + return visitBinaryExpression(node, /*discarded*/ + true); case 361 /* CommaListExpression */: - return visitCommaListExpression( - node, - /*discarded*/ - true - ); + return visitCommaListExpression(node, /*discarded*/ + true); case 217 /* ParenthesizedExpression */: - return visitParenthesizedExpression( - node, - /*discarded*/ - true - ); + return visitParenthesizedExpression(node, /*discarded*/ + true); default: return visitor(node); } @@ -92356,31 +84608,15 @@ ${lanes.join("\n")} function classElementVisitor(node) { switch (node.kind) { case 176 /* Constructor */: - return setCurrentClassElementAnd( - node, - visitConstructorDeclaration, - node - ); + return setCurrentClassElementAnd(node, visitConstructorDeclaration, node); case 177 /* GetAccessor */: case 178 /* SetAccessor */: case 174 /* MethodDeclaration */: - return setCurrentClassElementAnd( - node, - visitMethodOrAccessorDeclaration, - node - ); + return setCurrentClassElementAnd(node, visitMethodOrAccessorDeclaration, node); case 172 /* PropertyDeclaration */: - return setCurrentClassElementAnd( - node, - visitPropertyDeclaration, - node - ); + return setCurrentClassElementAnd(node, visitPropertyDeclaration, node); case 175 /* ClassStaticBlockDeclaration */: - return setCurrentClassElementAnd( - node, - visitClassStaticBlockDeclaration, - node - ); + return setCurrentClassElementAnd(node, visitClassStaticBlockDeclaration, node); case 167 /* ComputedPropertyName */: return visitComputedPropertyName(node); case 240 /* SemicolonClassElement */: @@ -92422,10 +84658,7 @@ ${lanes.join("\n")} const info = accessPrivateIdentifier2(node.left); if (info) { const receiver = visitNode(node.right, visitor, isExpression); - return setOriginalNode( - emitHelpers().createClassPrivateFieldInHelper(info.brandCheckIdentifier, receiver), - node - ); + return setOriginalNode(emitHelpers().createClassPrivateFieldInHelper(info.brandCheckIdentifier, receiver), node); } return visitEachChild(node, visitor, context); } @@ -92463,13 +84696,8 @@ ${lanes.join("\n")} } function visitExportAssignment(node) { if (isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)) { - node = transformNamedEvaluation( - context, - node, - /*ignoreEmptyStringLiteral*/ - true, - node.isExportEquals ? "" : "default" - ); + node = transformNamedEvaluation(context, node, /*ignoreEmptyStringLiteral*/ + true, node.isExportEquals ? "" : "default"); } return visitEachChild(node, visitor, context); } @@ -92497,10 +84725,8 @@ ${lanes.join("\n")} 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) { @@ -92515,22 +84741,9 @@ ${lanes.join("\n")} } const functionName = getHoistedFunctionName(node); if (functionName) { - getPendingExpressions().push( - factory2.createAssignment( - functionName, - factory2.createFunctionExpression( - filter(node.modifiers, (m) => isModifier(m) && !isStaticModifier(m) && !isAccessorModifier(m)), - node.asteriskToken, - functionName, - /*typeParameters*/ - void 0, - visitParameterList(node.parameters, visitor, context), - /*type*/ - void 0, - visitFunctionBody(node.body, visitor, context) - ) - ) - ); + getPendingExpressions().push(factory2.createAssignment(functionName, factory2.createFunctionExpression(filter(node.modifiers, m => isModifier(m) && !isStaticModifier(m) && !isAccessorModifier(m)), node.asteriskToken, functionName, /*typeParameters*/ + void 0, visitParameterList(node.parameters, visitor, context), /*type*/ + void 0, visitFunctionBody(node.body, visitor, context)))); } return void 0; } @@ -92561,8 +84774,9 @@ ${lanes.join("\n")} } } function getClassThis() { + var _ref31, _lex$classThis; const lex = getClassLexicalEnvironment(); - const classThis = lex.classThis ?? lex.classConstructor ?? (currentClassContainer == null ? void 0 : currentClassContainer.name); + const classThis = (_ref31 = (_lex$classThis = lex.classThis) !== null && _lex$classThis !== void 0 ? _lex$classThis : lex.classConstructor) !== null && _ref31 !== void 0 ? _ref31 : currentClassContainer == null ? void 0 : currentClassContainer.name; return Debug.checkDefined(classThis); } function transformAutoAccessor(node) { @@ -92613,61 +84827,42 @@ ${lanes.join("\n")} if (info.isStatic && !shouldTransformPrivateElementsOrClassStaticBlocks) { const statement = transformPropertyOrClassStaticBlock(node, factory2.createThis()); if (statement) { - return factory2.createClassStaticBlockDeclaration(factory2.createBlock( - [statement], - /*multiLine*/ - true - )); + return factory2.createClassStaticBlockDeclaration(factory2.createBlock([statement], /*multiLine*/ + true)); } } return void 0; } if (shouldTransformInitializersUsingSet && !isStatic(node) && (lexicalEnvironment == null ? void 0 : lexicalEnvironment.data) && lexicalEnvironment.data.facts & 16 /* WillHoistInitializersToConstructor */) { - return factory2.updatePropertyDeclaration( - node, - visitNodes2(node.modifiers, visitor, isModifierLike), - node.name, - /*questionOrExclamationToken*/ - void 0, - /*type*/ - void 0, - /*initializer*/ - void 0 - ); + return factory2.updatePropertyDeclaration(node, visitNodes2(node.modifiers, visitor, isModifierLike), node.name, /*questionOrExclamationToken*/ + void 0, /*type*/ + void 0, /*initializer*/ + void 0); } if (isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)) { node = transformNamedEvaluation(context, node); } - return factory2.updatePropertyDeclaration( - node, - visitNodes2(node.modifiers, modifierVisitor, isModifier), - visitNode(node.name, propertyNameVisitor, isPropertyName), - /*questionOrExclamationToken*/ - void 0, - /*type*/ - void 0, - visitNode(node.initializer, visitor, isExpression) - ); + return factory2.updatePropertyDeclaration(node, visitNodes2(node.modifiers, modifierVisitor, isModifier), visitNode(node.name, propertyNameVisitor, isPropertyName), /*questionOrExclamationToken*/ + void 0, /*type*/ + void 0, visitNode(node.initializer, visitor, isExpression)); } function transformPublicFieldInitializer(node) { if (shouldTransformInitializers && !isAutoAccessorPropertyDeclaration(node)) { - const expr = getPropertyNameExpressionIfNeeded( - node.name, - /*shouldHoist*/ - !!node.initializer || useDefineForClassFields - ); + const expr = getPropertyNameExpressionIfNeeded(node.name, /*shouldHoist*/ + !!node.initializer || useDefineForClassFields); if (expr) { getPendingExpressions().push(...flattenCommaList(expr)); } if (isStatic(node) && !shouldTransformPrivateElementsOrClassStaticBlocks) { const initializerStatement = transformPropertyOrClassStaticBlock(node, factory2.createThis()); if (initializerStatement) { - const staticBlock = factory2.createClassStaticBlockDeclaration( - factory2.createBlock([initializerStatement]) - ); + const staticBlock = factory2.createClassStaticBlockDeclaration(factory2.createBlock([initializerStatement])); setOriginalNode(staticBlock, node); setCommentRange(staticBlock, node); - setCommentRange(initializerStatement, { pos: -1, end: -1 }); + setCommentRange(initializerStatement, { + pos: -1, + end: -1 + }); setSyntheticLeadingComments(initializerStatement, void 0); setSyntheticTrailingComments(initializerStatement, void 0); return staticBlock; @@ -92675,16 +84870,9 @@ ${lanes.join("\n")} } return void 0; } - return factory2.updatePropertyDeclaration( - node, - visitNodes2(node.modifiers, modifierVisitor, isModifier), - visitNode(node.name, propertyNameVisitor, isPropertyName), - /*questionOrExclamationToken*/ - void 0, - /*type*/ - void 0, - visitNode(node.initializer, visitor, isExpression) - ); + return factory2.updatePropertyDeclaration(node, visitNodes2(node.modifiers, modifierVisitor, isModifier), visitNode(node.name, propertyNameVisitor, isPropertyName), /*questionOrExclamationToken*/ + void 0, /*type*/ + void 0, visitNode(node.initializer, visitor, isExpression)); } function transformFieldInitializer(node) { Debug.assert(!hasDecorators(node), "Decorators should already have been transformed and elided."); @@ -92693,6 +84881,7 @@ ${lanes.join("\n")} function shouldTransformAutoAccessorsInCurrentClass() { return shouldTransformAutoAccessors === -1 /* True */ || shouldTransformAutoAccessors === 3 /* Maybe */ && !!(lexicalEnvironment == null ? void 0 : lexicalEnvironment.data) && !!(lexicalEnvironment.data.facts & 16 /* WillHoistInitializersToConstructor */); } + function visitPropertyDeclaration(node) { if (isAutoAccessorPropertyDeclaration(node) && (shouldTransformAutoAccessorsInCurrentClass() || hasStaticModifier(node) && getInternalEmitFlags(node) & 32 /* TransformPrivateStaticElements */)) { return transformAutoAccessor(node); @@ -92719,26 +84908,11 @@ ${lanes.join("\n")} setCommentRange(receiver, moveRangePos(receiver, -1)); switch (info.kind) { case "a" /* Accessor */: - return emitHelpers().createClassPrivateFieldGetHelper( - receiver, - info.brandCheckIdentifier, - info.kind, - info.getterName - ); + return emitHelpers().createClassPrivateFieldGetHelper(receiver, info.brandCheckIdentifier, info.kind, info.getterName); case "m" /* Method */: - return emitHelpers().createClassPrivateFieldGetHelper( - receiver, - info.brandCheckIdentifier, - info.kind, - info.methodName - ); + return emitHelpers().createClassPrivateFieldGetHelper(receiver, info.brandCheckIdentifier, info.kind, info.methodName); case "f" /* Field */: - return emitHelpers().createClassPrivateFieldGetHelper( - receiver, - info.brandCheckIdentifier, - info.kind, - info.isStatic ? info.variableName : void 0 - ); + return emitHelpers().createClassPrivateFieldGetHelper(receiver, info.brandCheckIdentifier, info.kind, info.isStatic ? info.variableName : void 0); case "untransformed": return Debug.fail("Access helpers should not be created for untransformed private elements"); default: @@ -92749,26 +84923,20 @@ ${lanes.join("\n")} if (isPrivateIdentifier(node.name)) { const privateIdentifierInfo = accessPrivateIdentifier2(node.name); if (privateIdentifierInfo) { - return setTextRange( - setOriginalNode( - createPrivateIdentifierAccess(privateIdentifierInfo, node.expression), - node - ), - node - ); + return setTextRange(setOriginalNode(createPrivateIdentifierAccess(privateIdentifierInfo, node.expression), node), node); } } if (shouldTransformSuperInStaticInitializers && currentClassElement && isSuperProperty(node) && isIdentifier(node.name) && isStaticPropertyDeclarationOrClassStaticBlock(currentClassElement) && (lexicalEnvironment == null ? void 0 : lexicalEnvironment.data)) { - const { classConstructor, superClassReference, facts } = lexicalEnvironment.data; + const { + classConstructor, + superClassReference, + facts + } = lexicalEnvironment.data; if (facts & 1 /* ClassWasDecorated */) { return visitInvalidSuperProperty(node); } if (classConstructor && superClassReference) { - const superProperty = factory2.createReflectGetCall( - superClassReference, - factory2.createStringLiteralFromNode(node.name), - classConstructor - ); + const superProperty = factory2.createReflectGetCall(superClassReference, factory2.createStringLiteralFromNode(node.name), classConstructor); setOriginalNode(superProperty, node.expression); setTextRange(superProperty, node.expression); return superProperty; @@ -92778,16 +84946,16 @@ ${lanes.join("\n")} } function visitElementAccessExpression(node) { if (shouldTransformSuperInStaticInitializers && currentClassElement && isSuperProperty(node) && isStaticPropertyDeclarationOrClassStaticBlock(currentClassElement) && (lexicalEnvironment == null ? void 0 : lexicalEnvironment.data)) { - const { classConstructor, superClassReference, facts } = lexicalEnvironment.data; + const { + classConstructor, + superClassReference, + facts + } = lexicalEnvironment.data; if (facts & 1 /* ClassWasDecorated */) { return visitInvalidSuperProperty(node); } if (classConstructor && superClassReference) { - const superProperty = factory2.createReflectGetCall( - superClassReference, - visitNode(node.argumentExpression, visitor, isExpression), - classConstructor - ); + const superProperty = factory2.createReflectGetCall(superClassReference, visitNode(node.argumentExpression, visitor, isExpression), classConstructor); setOriginalNode(superProperty, node.expression); setTextRange(superProperty, node.expression); return superProperty; @@ -92803,16 +84971,15 @@ ${lanes.join("\n")} if (info = accessPrivateIdentifier2(operand.name)) { const receiver = visitNode(operand.expression, visitor, isExpression); ensureDynamicThisIfNeeded(receiver); - const { readExpression, initializeExpression } = createCopiableReceiverExpr(receiver); + const { + readExpression, + initializeExpression + } = createCopiableReceiverExpr(receiver); let expression = createPrivateIdentifierAccess(info, readExpression); const temp = isPrefixUnaryExpression(node) || discarded ? void 0 : factory2.createTempVariable(hoistVariableDeclaration); expression = expandPreOrPostfixIncrementOrDecrementExpression(factory2, node, expression, hoistVariableDeclaration, temp); - expression = createPrivateIdentifierAssignment( - info, - initializeExpression || readExpression, - expression, - 64 /* EqualsToken */ - ); + expression = createPrivateIdentifierAssignment(info, initializeExpression || readExpression, expression, 64 /* EqualsToken */); + setOriginalNode(expression, node); setTextRange(expression, node); if (temp) { @@ -92822,7 +84989,11 @@ ${lanes.join("\n")} return expression; } } else if (shouldTransformSuperInStaticInitializers && currentClassElement && isSuperProperty(operand) && isStaticPropertyDeclarationOrClassStaticBlock(currentClassElement) && (lexicalEnvironment == null ? void 0 : lexicalEnvironment.data)) { - const { classConstructor, superClassReference, facts } = lexicalEnvironment.data; + const { + classConstructor, + superClassReference, + facts + } = lexicalEnvironment.data; if (facts & 1 /* ClassWasDecorated */) { const expression = visitInvalidSuperProperty(operand); return isPrefixUnaryExpression(node) ? factory2.updatePrefixUnaryExpression(node, expression) : factory2.updatePostfixUnaryExpression(node, expression); @@ -92862,19 +85033,10 @@ ${lanes.join("\n")} return visitEachChild(node, visitor, context); } function visitForStatement(node) { - return factory2.updateForStatement( - node, - visitNode(node.initializer, discardedValueVisitor, isForInitializer), - visitNode(node.condition, visitor, isExpression), - visitNode(node.incrementor, discardedValueVisitor, isExpression), - visitIterationBody(node.statement, visitor, context) - ); + return factory2.updateForStatement(node, visitNode(node.initializer, discardedValueVisitor, isForInitializer), visitNode(node.condition, visitor, isExpression), visitNode(node.incrementor, discardedValueVisitor, isExpression), visitIterationBody(node.statement, visitor, context)); } function visitExpressionStatement(node) { - return factory2.updateExpressionStatement( - node, - visitNode(node.expression, discardedValueVisitor, isExpression) - ); + return factory2.updateExpressionStatement(node, visitNode(node.expression, discardedValueVisitor, isExpression)); } function createCopiableReceiverExpr(receiver) { const clone2 = nodeIsSynthesized(receiver) ? receiver : factory2.cloneNode(receiver); @@ -92882,41 +85044,35 @@ ${lanes.join("\n")} noSubstitution.add(clone2); } if (isSimpleInlineableExpression(receiver)) { - return { readExpression: clone2, initializeExpression: void 0 }; + return { + readExpression: clone2, + initializeExpression: void 0 + }; } const readExpression = factory2.createTempVariable(hoistVariableDeclaration); const initializeExpression = factory2.createAssignment(readExpression, clone2); - return { readExpression, initializeExpression }; + return { + readExpression, + initializeExpression + }; } function visitCallExpression(node) { var _a; if (isPrivateIdentifierPropertyAccessExpression(node.expression) && accessPrivateIdentifier2(node.expression.name)) { - const { thisArg, target } = factory2.createCallBinding(node.expression, hoistVariableDeclaration, languageVersion); + const { + thisArg, + target + } = factory2.createCallBinding(node.expression, hoistVariableDeclaration, languageVersion); if (isCallChain(node)) { - return factory2.updateCallChain( - node, - factory2.createPropertyAccessChain(visitNode(target, visitor, isExpression), node.questionDotToken, "call"), - /*questionDotToken*/ - void 0, - /*typeArguments*/ - void 0, - [visitNode(thisArg, visitor, isExpression), ...visitNodes2(node.arguments, visitor, isExpression)] - ); + return factory2.updateCallChain(node, factory2.createPropertyAccessChain(visitNode(target, visitor, isExpression), node.questionDotToken, "call"), /*questionDotToken*/ + void 0, /*typeArguments*/ + void 0, [visitNode(thisArg, visitor, isExpression), ...visitNodes2(node.arguments, visitor, isExpression)]); } - return factory2.updateCallExpression( - node, - factory2.createPropertyAccessExpression(visitNode(target, visitor, isExpression), "call"), - /*typeArguments*/ - void 0, - [visitNode(thisArg, visitor, isExpression), ...visitNodes2(node.arguments, visitor, isExpression)] - ); + return factory2.updateCallExpression(node, factory2.createPropertyAccessExpression(visitNode(target, visitor, isExpression), "call"), /*typeArguments*/ + void 0, [visitNode(thisArg, visitor, isExpression), ...visitNodes2(node.arguments, visitor, isExpression)]); } if (shouldTransformSuperInStaticInitializers && currentClassElement && isSuperProperty(node.expression) && isStaticPropertyDeclarationOrClassStaticBlock(currentClassElement) && ((_a = lexicalEnvironment == null ? void 0 : lexicalEnvironment.data) == null ? void 0 : _a.classConstructor)) { - const invocation = factory2.createFunctionCallCall( - visitNode(node.expression, visitor, isExpression), - lexicalEnvironment.data.classConstructor, - visitNodes2(node.arguments, visitor, isExpression) - ); + const invocation = factory2.createFunctionCallCall(visitNode(node.expression, visitor, isExpression), lexicalEnvironment.data.classConstructor, visitNodes2(node.arguments, visitor, isExpression)); setOriginalNode(invocation, node); setTextRange(invocation, node); return invocation; @@ -92926,35 +85082,20 @@ ${lanes.join("\n")} function visitTaggedTemplateExpression(node) { var _a; if (isPrivateIdentifierPropertyAccessExpression(node.tag) && accessPrivateIdentifier2(node.tag.name)) { - const { thisArg, target } = factory2.createCallBinding(node.tag, hoistVariableDeclaration, languageVersion); - return factory2.updateTaggedTemplateExpression( - node, - factory2.createCallExpression( - factory2.createPropertyAccessExpression(visitNode(target, visitor, isExpression), "bind"), - /*typeArguments*/ - void 0, - [visitNode(thisArg, visitor, isExpression)] - ), - /*typeArguments*/ - void 0, - visitNode(node.template, visitor, isTemplateLiteral) - ); + const { + thisArg, + target + } = factory2.createCallBinding(node.tag, hoistVariableDeclaration, languageVersion); + return factory2.updateTaggedTemplateExpression(node, factory2.createCallExpression(factory2.createPropertyAccessExpression(visitNode(target, visitor, isExpression), "bind"), /*typeArguments*/ + void 0, [visitNode(thisArg, visitor, isExpression)]), /*typeArguments*/ + void 0, visitNode(node.template, visitor, isTemplateLiteral)); } if (shouldTransformSuperInStaticInitializers && currentClassElement && isSuperProperty(node.tag) && isStaticPropertyDeclarationOrClassStaticBlock(currentClassElement) && ((_a = lexicalEnvironment == null ? void 0 : lexicalEnvironment.data) == null ? void 0 : _a.classConstructor)) { - const invocation = factory2.createFunctionBindCall( - visitNode(node.tag, visitor, isExpression), - lexicalEnvironment.data.classConstructor, - [] - ); + const invocation = factory2.createFunctionBindCall(visitNode(node.tag, visitor, isExpression), lexicalEnvironment.data.classConstructor, []); setOriginalNode(invocation, node); setTextRange(invocation, node); - return factory2.updateTaggedTemplateExpression( - node, - invocation, - /*typeArguments*/ - void 0, - visitNode(node.template, visitor, isTemplateLiteral) - ); + return factory2.updateTaggedTemplateExpression(node, invocation, /*typeArguments*/ + void 0, visitNode(node.template, visitor, isTemplateLiteral)); } return visitEachChild(node, visitor, context); } @@ -92965,11 +85106,8 @@ ${lanes.join("\n")} if (shouldTransformPrivateElementsOrClassStaticBlocks) { if (isClassThisAssignmentBlock(node)) { const result = visitNode(node.body.statements[0].expression, visitor, isExpression); - if (isAssignmentExpression( - result, - /*excludeCompoundAssignment*/ - true - ) && result.left === result.right) { + if (isAssignmentExpression(result, /*excludeCompoundAssignment*/ + true) && result.left === result.right) { return void 0; } return result; @@ -92978,11 +85116,7 @@ ${lanes.join("\n")} return visitNode(node.body.statements[0].expression, visitor, isExpression); } startLexicalEnvironment(); - let statements = setCurrentClassElementAnd( - node, - (statements2) => visitNodes2(statements2, visitor, isStatement), - node.body.statements - ); + let statements = setCurrentClassElementAnd(node, statements2 => visitNodes2(statements2, visitor, isStatement), node.body.statements); statements = factory2.mergeLexicalEnvironment(statements, endLexicalEnvironment()); const iife = factory2.createImmediatelyInvokedArrowFunction(statements); setOriginalNode(skipParentheses(iife.expression), node); @@ -92998,7 +85132,7 @@ ${lanes.join("\n")} if (some(staticPropertiesOrClassStaticBlocks, isClassNamedEvaluationHelperBlock)) { return false; } - const hasTransformableStatics = (shouldTransformPrivateElementsOrClassStaticBlocks || !!(getInternalEmitFlags(node) && 32 /* TransformPrivateStaticElements */)) && some(staticPropertiesOrClassStaticBlocks, (node2) => isClassStaticBlockDeclaration(node2) || isPrivateIdentifierClassElementDeclaration(node2) || shouldTransformInitializers && isInitializedProperty(node2)); + const hasTransformableStatics = (shouldTransformPrivateElementsOrClassStaticBlocks || !!(getInternalEmitFlags(node) && 32 /* TransformPrivateStaticElements */)) && some(staticPropertiesOrClassStaticBlocks, node2 => isClassStaticBlockDeclaration(node2) || isPrivateIdentifierClassElementDeclaration(node2) || shouldTransformInitializers && isInitializedProperty(node2)); return hasTransformableStatics; } return false; @@ -93007,12 +85141,7 @@ ${lanes.join("\n")} if (isDestructuringAssignment(node)) { const savedPendingExpressions = pendingExpressions; pendingExpressions = void 0; - node = factory2.updateBinaryExpression( - node, - visitNode(node.left, assignmentTargetVisitor, isExpression), - node.operatorToken, - visitNode(node.right, visitor, isExpression) - ); + node = factory2.updateBinaryExpression(node, visitNode(node.left, assignmentTargetVisitor, isExpression), node.operatorToken, visitNode(node.right, visitor, isExpression)); const expr = some(pendingExpressions) ? factory2.inlineExpressions(compact([...pendingExpressions, node])) : node; pendingExpressions = savedPendingExpressions; return expr; @@ -93026,23 +85155,16 @@ ${lanes.join("\n")} if (isPrivateIdentifierPropertyAccessExpression(left)) { const info = accessPrivateIdentifier2(left.name); if (info) { - return setTextRange( - setOriginalNode( - createPrivateIdentifierAssignment(info, left.expression, node.right, node.operatorToken.kind), - node - ), - node - ); + return setTextRange(setOriginalNode(createPrivateIdentifierAssignment(info, left.expression, node.right, node.operatorToken.kind), node), node); } } else if (shouldTransformSuperInStaticInitializers && currentClassElement && isSuperProperty(node.left) && isStaticPropertyDeclarationOrClassStaticBlock(currentClassElement) && (lexicalEnvironment == null ? void 0 : lexicalEnvironment.data)) { - const { classConstructor, superClassReference, facts } = lexicalEnvironment.data; + const { + classConstructor, + superClassReference, + facts + } = lexicalEnvironment.data; if (facts & 1 /* ClassWasDecorated */) { - return factory2.updateBinaryExpression( - node, - visitInvalidSuperProperty(node.left), - node.operatorToken, - visitNode(node.right, visitor, isExpression) - ); + return factory2.updateBinaryExpression(node, visitInvalidSuperProperty(node.left), node.operatorToken, visitNode(node.right, visitor, isExpression)); } if (classConstructor && superClassReference) { let setterName = isElementAccessExpression(node.left) ? visitNode(node.left.argumentExpression, visitor, isExpression) : isIdentifier(node.left.name) ? factory2.createStringLiteralFromNode(node.left.name) : void 0; @@ -93054,18 +85176,10 @@ ${lanes.join("\n")} getterName = factory2.createTempVariable(hoistVariableDeclaration); setterName = factory2.createAssignment(getterName, setterName); } - const superPropertyGet = factory2.createReflectGetCall( - superClassReference, - getterName, - classConstructor - ); + const superPropertyGet = factory2.createReflectGetCall(superClassReference, getterName, classConstructor); setOriginalNode(superPropertyGet, node.left); setTextRange(superPropertyGet, node.left); - expression = factory2.createBinaryExpression( - superPropertyGet, - getNonAssignmentOperatorForCompoundAssignment(node.operatorToken.kind), - expression - ); + expression = factory2.createBinaryExpression(superPropertyGet, getNonAssignmentOperatorForCompoundAssignment(node.operatorToken.kind), expression); setTextRange(expression, node); } const temp = discarded ? void 0 : factory2.createTempVariable(hoistVariableDeclaration); @@ -93073,12 +85187,7 @@ ${lanes.join("\n")} expression = factory2.createAssignment(temp, expression); setTextRange(temp, node); } - expression = factory2.createReflectSetCall( - superClassReference, - setterName, - expression, - classConstructor - ); + expression = factory2.createReflectSetCall(superClassReference, setterName, expression, classConstructor); setOriginalNode(expression, node); setTextRange(expression, node); if (temp) { @@ -93109,41 +85218,22 @@ ${lanes.join("\n")} right = visitNode(right, visitor, isExpression); ensureDynamicThisIfNeeded(receiver); if (isCompoundAssignment(operator)) { - const { readExpression, initializeExpression } = createCopiableReceiverExpr(receiver); + const { + readExpression, + initializeExpression + } = createCopiableReceiverExpr(receiver); receiver = initializeExpression || readExpression; - right = factory2.createBinaryExpression( - createPrivateIdentifierAccessHelper(info, readExpression), - getNonAssignmentOperatorForCompoundAssignment(operator), - right - ); + right = factory2.createBinaryExpression(createPrivateIdentifierAccessHelper(info, readExpression), getNonAssignmentOperatorForCompoundAssignment(operator), right); } setCommentRange(receiver, moveRangePos(receiver, -1)); switch (info.kind) { case "a" /* Accessor */: - return emitHelpers().createClassPrivateFieldSetHelper( - receiver, - info.brandCheckIdentifier, - right, - info.kind, - info.setterName - ); + return emitHelpers().createClassPrivateFieldSetHelper(receiver, info.brandCheckIdentifier, right, info.kind, info.setterName); case "m" /* Method */: - return emitHelpers().createClassPrivateFieldSetHelper( - receiver, - info.brandCheckIdentifier, - right, - info.kind, - /*f*/ - void 0 - ); + return emitHelpers().createClassPrivateFieldSetHelper(receiver, info.brandCheckIdentifier, right, info.kind, /*f*/ + void 0); case "f" /* Field */: - return emitHelpers().createClassPrivateFieldSetHelper( - receiver, - info.brandCheckIdentifier, - right, - info.kind, - info.isStatic ? info.variableName : void 0 - ); + return emitHelpers().createClassPrivateFieldSetHelper(receiver, info.brandCheckIdentifier, right, info.kind, info.isStatic ? info.variableName : void 0); case "untransformed": return Debug.fail("Access helpers should not be created for untransformed private elements"); default: @@ -93160,9 +85250,11 @@ ${lanes.join("\n")} if (isClassDeclaration(original) && classOrConstructorParameterIsDecorated(legacyDecorators, original)) { facts |= 1 /* ClassWasDecorated */; } + if (shouldTransformPrivateElementsOrClassStaticBlocks && (classHasClassThisAssignment(node) || classHasExplicitlyAssignedName(node))) { facts |= 2 /* NeedsClassConstructorReference */; } + let containsPublicInstanceFields = false; let containsInitializedPublicInstanceFields = false; let containsInstancePrivateElements = false; @@ -93174,6 +85266,7 @@ ${lanes.join("\n")} } else if (isAutoAccessorPropertyDeclaration(member) && shouldTransformAutoAccessors === -1 /* True */ && !node.name && !((_a = node.emitNode) == null ? void 0 : _a.classThis)) { facts |= 2 /* NeedsClassConstructorReference */; } + if (isPropertyDeclaration(member) || isClassStaticBlockDeclaration(member)) { if (shouldTransformThisInStaticInitializers && member.transformFlags & 16384 /* ContainsLexicalThis */) { facts |= 8 /* NeedsSubstitutionForThisInClassStaticField */; @@ -93181,6 +85274,7 @@ ${lanes.join("\n")} facts |= 2 /* NeedsClassConstructorReference */; } } + if (shouldTransformSuperInStaticInitializers && member.transformFlags & 134217728 /* ContainsLexicalSuper */) { if (!(facts & 1 /* ClassWasDecorated */)) { facts |= 2 /* NeedsClassConstructorReference */ | 4 /* NeedsClassSuperReference */; @@ -93206,27 +85300,18 @@ ${lanes.join("\n")} if (willHoistInitializersToConstructor) { facts |= 16 /* WillHoistInitializersToConstructor */; } + return facts; } function visitExpressionWithTypeArgumentsInHeritageClause(node) { var _a; const facts = ((_a = lexicalEnvironment == null ? void 0 : lexicalEnvironment.data) == null ? void 0 : _a.facts) || 0 /* None */; if (facts & 4 /* NeedsClassSuperReference */) { - const temp = factory2.createTempVariable( - hoistVariableDeclaration, - /*reservedInNestedScopes*/ - true - ); + const temp = factory2.createTempVariable(hoistVariableDeclaration, /*reservedInNestedScopes*/ + true); getClassLexicalEnvironment().superClassReference = temp; - return factory2.updateExpressionWithTypeArguments( - node, - factory2.createAssignment( - temp, - visitNode(node.expression, visitor, isExpression) - ), - /*typeArguments*/ - void 0 - ); + return factory2.updateExpressionWithTypeArguments(node, factory2.createAssignment(temp, visitNode(node.expression, visitor, isExpression)), /*typeArguments*/ + void 0); } return visitEachChild(node, visitor, context); } @@ -93257,10 +85342,7 @@ ${lanes.join("\n")} if (shouldTransformPrivateElementsOrClassStaticBlocks) { const privateInstanceMethodsAndAccessors = getPrivateInstanceMethodsAndAccessors(node); if (some(privateInstanceMethodsAndAccessors)) { - getPrivateIdentifierEnvironment().data.weakSetName = createHoistedVariableForClass( - "instances", - privateInstanceMethodsAndAccessors[0].name - ); + getPrivateIdentifierEnvironment().data.weakSetName = createHoistedVariableForClass("instances", privateInstanceMethodsAndAccessors[0].name); } } const facts = getClassFacts(node); @@ -93288,11 +85370,8 @@ ${lanes.join("\n")} getClassLexicalEnvironment().classConstructor = node.emitNode.classThis; pendingClassReferenceAssignment = factory2.createAssignment(node.emitNode.classThis, factory2.getInternalName(node)); } else { - const temp = factory2.createTempVariable( - hoistVariableDeclaration, - /*reservedInNestedScopes*/ - true - ); + const temp = factory2.createTempVariable(hoistVariableDeclaration, /*reservedInNestedScopes*/ + true); getClassLexicalEnvironment().classConstructor = factory2.cloneNode(temp); pendingClassReferenceAssignment = factory2.createAssignment(temp, factory2.getInternalName(node)); } @@ -93305,7 +85384,10 @@ ${lanes.join("\n")} const isDefault = hasSyntacticModifier(node, 2048 /* Default */); let modifiers = visitNodes2(node.modifiers, modifierVisitor, isModifier); const heritageClauses = visitNodes2(node.heritageClauses, heritageClauseVisitor, isHeritageClause); - const { members, prologue } = transformClassMembers(node); + const { + members, + prologue + } = transformClassMembers(node); const statements = []; if (pendingClassReferenceAssignment) { getPendingExpressions().unshift(pendingClassReferenceAssignment); @@ -93320,35 +85402,20 @@ ${lanes.join("\n")} } } if (statements.length > 0 && isExport && isDefault) { - modifiers = visitNodes2(modifiers, (node2) => isExportOrDefaultModifier(node2) ? void 0 : node2, isModifier); - statements.push(factory2.createExportAssignment( - /*modifiers*/ - void 0, - /*isExportEquals*/ - false, - factory2.getLocalName( - node, - /*allowComments*/ - false, - /*allowSourceMaps*/ - true - ) - )); + modifiers = visitNodes2(modifiers, node2 => isExportOrDefaultModifier(node2) ? void 0 : node2, isModifier); + statements.push(factory2.createExportAssignment( /*modifiers*/ + void 0, /*isExportEquals*/ + false, factory2.getLocalName(node, /*allowComments*/ + false, /*allowSourceMaps*/ + true))); } const alias = getClassLexicalEnvironment().classConstructor; if (isClassWithConstructorReference && alias) { enableSubstitutionForClassAliases(); classAliases[getOriginalNodeId(node)] = alias; } - const classDecl = factory2.updateClassDeclaration( - node, - modifiers, - node.name, - /*typeParameters*/ - void 0, - heritageClauses, - members - ); + const classDecl = factory2.updateClassDeclaration(node, modifiers, node.name, /*typeParameters*/ + void 0, heritageClauses, members); statements.unshift(classDecl); if (prologue) { statements.unshift(factory2.createExpressionStatement(prologue)); @@ -93371,11 +85438,8 @@ ${lanes.join("\n")} return getClassLexicalEnvironment().classConstructor = node.emitNode.classThis; } const requiresBlockScopedVar = classCheckFlags & 32768 /* BlockScopedBindingInLoop */; - const temp2 = factory2.createTempVariable( - requiresBlockScopedVar ? addBlockScopedVariable : hoistVariableDeclaration, - /*reservedInNestedScopes*/ - true - ); + const temp2 = factory2.createTempVariable(requiresBlockScopedVar ? addBlockScopedVariable : hoistVariableDeclaration, /*reservedInNestedScopes*/ + true); getClassLexicalEnvironment().classConstructor = factory2.cloneNode(temp2); return temp2; } @@ -93383,25 +85447,22 @@ ${lanes.join("\n")} getClassLexicalEnvironment().classThis = node.emitNode.classThis; } if (facts & 2 /* NeedsClassConstructorReference */) { - temp ?? (temp = createClassTempVar()); + var _temp; + (_temp = temp) !== null && _temp !== void 0 ? _temp : temp = createClassTempVar(); } const modifiers = visitNodes2(node.modifiers, modifierVisitor, isModifier); const heritageClauses = visitNodes2(node.heritageClauses, heritageClauseVisitor, isHeritageClause); - const { members, prologue } = transformClassMembers(node); - const classExpression = factory2.updateClassExpression( - node, - modifiers, - node.name, - /*typeParameters*/ - void 0, - heritageClauses, - members - ); + const { + members, + prologue + } = transformClassMembers(node); + const classExpression = factory2.updateClassExpression(node, modifiers, node.name, /*typeParameters*/ + void 0, heritageClauses, members); const expressions = []; if (prologue) { expressions.push(prologue); } - const hasTransformableStatics = (shouldTransformPrivateElementsOrClassStaticBlocks || getInternalEmitFlags(node) & 32 /* TransformPrivateStaticElements */) && some(staticPropertiesOrClassStaticBlocks, (node2) => isClassStaticBlockDeclaration(node2) || isPrivateIdentifierClassElementDeclaration(node2) || shouldTransformInitializers && isInitializedProperty(node2)); + const hasTransformableStatics = (shouldTransformPrivateElementsOrClassStaticBlocks || getInternalEmitFlags(node) & 32 /* TransformPrivateStaticElements */) && some(staticPropertiesOrClassStaticBlocks, node2 => isClassStaticBlockDeclaration(node2) || isPrivateIdentifierClassElementDeclaration(node2) || shouldTransformInitializers && isInitializedProperty(node2)); if (hasTransformableStatics || some(pendingExpressions)) { if (isDecoratedClassDeclaration) { Debug.assertIsDefined(pendingStatements, "Decorated classes transformed by TypeScript are expected to be within a variable declaration."); @@ -93409,7 +85470,8 @@ ${lanes.join("\n")} addRange(pendingStatements, map(pendingExpressions, factory2.createExpressionStatement)); } if (some(staticPropertiesOrClassStaticBlocks)) { - addPropertyOrClassStaticBlockStatements(pendingStatements, staticPropertiesOrClassStaticBlocks, ((_b = node.emitNode) == null ? void 0 : _b.classThis) ?? factory2.getInternalName(node)); + var _ref32; + addPropertyOrClassStaticBlockStatements(pendingStatements, staticPropertiesOrClassStaticBlocks, (_ref32 = (_b = node.emitNode) == null ? void 0 : _b.classThis) !== null && _ref32 !== void 0 ? _ref32 : factory2.getInternalName(node)); } if (temp) { expressions.push(factory2.createAssignment(temp, classExpression)); @@ -93419,7 +85481,8 @@ ${lanes.join("\n")} expressions.push(classExpression); } } else { - temp ?? (temp = createClassTempVar()); + var _temp2; + (_temp2 = temp) !== null && _temp2 !== void 0 ? _temp2 : temp = createClassTempVar(); if (isClassWithConstructorReference) { enableSubstitutionForClassAliases(); const alias = factory2.cloneNode(temp); @@ -93448,8 +85511,12 @@ ${lanes.join("\n")} } function visitThisExpression(node) { if (shouldTransformThisInStaticInitializers && currentClassElement && isClassStaticBlockDeclaration(currentClassElement) && (lexicalEnvironment == null ? void 0 : lexicalEnvironment.data)) { - const { classThis, classConstructor } = lexicalEnvironment.data; - return classThis ?? classConstructor ?? node; + var _ref33; + const { + classThis, + classConstructor + } = lexicalEnvironment.data; + return (_ref33 = classThis !== null && classThis !== void 0 ? classThis : classConstructor) !== null && _ref33 !== void 0 ? _ref33 : node; } return node; } @@ -93462,7 +85529,9 @@ ${lanes.join("\n")} addPrivateIdentifierToEnvironment(member, member.name, addPrivateIdentifierClassElementToEnvironment); } else { const privateEnv = getPrivateIdentifierEnvironment(); - setPrivateIdentifier(privateEnv, member.name, { kind: "untransformed" }); + setPrivateIdentifier(privateEnv, member.name, { + kind: "untransformed" + }); } } } @@ -93474,17 +85543,15 @@ ${lanes.join("\n")} if (shouldTransformAutoAccessorsInCurrentClass()) { for (const member of node.members) { if (isAutoAccessorPropertyDeclaration(member)) { - const storageName = factory2.getGeneratedPrivateNameForNode( - member.name, - /*prefix*/ - void 0, - "_accessor_storage" - ); + const storageName = factory2.getGeneratedPrivateNameForNode(member.name, /*prefix*/ + void 0, "_accessor_storage"); if (shouldTransformPrivateElementsOrClassStaticBlocks || shouldTransformPrivateStaticElementsInClass && hasStaticModifier(member)) { addPrivateIdentifierToEnvironment(member, storageName, addPrivateIdentifierPropertyDeclarationToEnvironment); } else { const privateEnv = getPrivateIdentifierEnvironment(); - setPrivateIdentifier(privateEnv, storageName, { kind: "untransformed" }); + setPrivateIdentifier(privateEnv, storageName, { + kind: "untransformed" + }); } } } @@ -93493,11 +85560,8 @@ ${lanes.join("\n")} let members = visitNodes2(node.members, classElementVisitor, isClassElement); let syntheticConstructor; if (!some(members, isConstructorDeclaration)) { - syntheticConstructor = transformConstructor( - /*constructor*/ - void 0, - node - ); + syntheticConstructor = transformConstructor( /*constructor*/ + void 0, node); } let prologue; let syntheticStaticBlock; @@ -93505,26 +85569,15 @@ ${lanes.join("\n")} let statement = factory2.createExpressionStatement(factory2.inlineExpressions(pendingExpressions)); if (statement.transformFlags & 134234112 /* ContainsLexicalThisOrSuper */) { const temp = factory2.createTempVariable(hoistVariableDeclaration); - const arrow = factory2.createArrowFunction( - /*modifiers*/ - void 0, - /*typeParameters*/ - void 0, - /*parameters*/ - [], - /*type*/ - void 0, - /*equalsGreaterThanToken*/ - void 0, - factory2.createBlock([statement]) - ); + const arrow = factory2.createArrowFunction( /*modifiers*/ + void 0, /*typeParameters*/ + void 0, /*parameters*/ + [], /*type*/ + void 0, /*equalsGreaterThanToken*/ + void 0, factory2.createBlock([statement])); prologue = factory2.createAssignment(temp, arrow); - statement = factory2.createExpressionStatement(factory2.createCallExpression( - temp, - /*typeArguments*/ - void 0, - [] - )); + statement = factory2.createExpressionStatement(factory2.createCallExpression(temp, /*typeArguments*/ + void 0, [])); } const block = factory2.createBlock([statement]); syntheticStaticBlock = factory2.createClassStaticBlockDeclaration(block); @@ -93538,30 +85591,23 @@ ${lanes.join("\n")} membersArray = append(membersArray, classNamedEvaluationHelperBlock); membersArray = append(membersArray, syntheticConstructor); membersArray = append(membersArray, syntheticStaticBlock); - const remainingMembers = classThisAssignmentBlock || classNamedEvaluationHelperBlock ? filter(members, (member) => member !== classThisAssignmentBlock && member !== classNamedEvaluationHelperBlock) : members; + const remainingMembers = classThisAssignmentBlock || classNamedEvaluationHelperBlock ? filter(members, member => member !== classThisAssignmentBlock && member !== classNamedEvaluationHelperBlock) : members; membersArray = addRange(membersArray, remainingMembers); - members = setTextRange( - factory2.createNodeArray(membersArray), - /*location*/ - node.members - ); + members = setTextRange(factory2.createNodeArray(membersArray), /*location*/ + node.members); } - return { members, prologue }; + return { + members, + prologue + }; } function createBrandCheckWeakSetForPrivateMethods() { - const { weakSetName } = getPrivateIdentifierEnvironment().data; + const { + weakSetName + } = getPrivateIdentifierEnvironment().data; Debug.assert(weakSetName, "weakSetName should be set in private identifier environment"); - getPendingExpressions().push( - factory2.createAssignment( - weakSetName, - factory2.createNewExpression( - factory2.createIdentifier("WeakSet"), - /*typeArguments*/ - void 0, - [] - ) - ) - ); + getPendingExpressions().push(factory2.createAssignment(weakSetName, factory2.createNewExpression(factory2.createIdentifier("WeakSet"), /*typeArguments*/ + void 0, []))); } function transformConstructor(constructor, container) { constructor = visitNode(constructor, visitor, isConstructorDeclaration); @@ -93577,28 +85623,11 @@ ${lanes.join("\n")} } if (constructor) { Debug.assert(parameters); - return factory2.updateConstructorDeclaration( - constructor, - /*modifiers*/ - void 0, - parameters, - body - ); + return factory2.updateConstructorDeclaration(constructor, /*modifiers*/ + void 0, parameters, body); } - return startOnNewLine( - setOriginalNode( - setTextRange( - factory2.createConstructorDeclaration( - /*modifiers*/ - void 0, - parameters ?? [], - body - ), - constructor || container - ), - constructor - ) - ); + return startOnNewLine(setOriginalNode(setTextRange(factory2.createConstructorDeclaration( /*modifiers*/ + void 0, parameters !== null && parameters !== void 0 ? parameters : [], body), constructor || container), constructor)); } function transformConstructorBodyWorker(statementsOut, statementsIn, statementOffset, superPath, superPathDepth, initializerStatements, constructor) { const superStatementIndex = superPath[superPathDepth]; @@ -93607,24 +85636,11 @@ ${lanes.join("\n")} statementOffset = superStatementIndex + 1; if (isTryStatement(superStatement)) { const tryBlockStatements = []; - transformConstructorBodyWorker( - tryBlockStatements, - superStatement.tryBlock.statements, - /*statementOffset*/ - 0, - superPath, - superPathDepth + 1, - initializerStatements, - constructor - ); + transformConstructorBodyWorker(tryBlockStatements, superStatement.tryBlock.statements, /*statementOffset*/ + 0, superPath, superPathDepth + 1, initializerStatements, constructor); const tryBlockStatementsArray = factory2.createNodeArray(tryBlockStatements); setTextRange(tryBlockStatementsArray, superStatement.tryBlock.statements); - statementsOut.push(factory2.updateTryStatement( - superStatement, - factory2.updateBlock(superStatement.tryBlock, tryBlockStatements), - visitNode(superStatement.catchClause, visitor, isCatchClause), - visitNode(superStatement.finallyBlock, visitor, isBlock) - )); + statementsOut.push(factory2.updateTryStatement(superStatement, factory2.updateBlock(superStatement.tryBlock, tryBlockStatements), visitNode(superStatement.catchClause, visitor, isCatchClause), visitNode(superStatement.finallyBlock, visitor, isBlock))); } else { addRange(statementsOut, visitNodes2(statementsIn, visitor, isStatement, superStatementIndex, 1)); while (statementOffset < statementsIn.length) { @@ -93640,26 +85656,19 @@ ${lanes.join("\n")} addRange(statementsOut, visitNodes2(statementsIn, visitor, isStatement, statementOffset)); } function transformConstructorBody(node, constructor, isDerivedClass) { - const instanceProperties = getProperties( - node, - /*requireInitializer*/ - false, - /*isStatic*/ - false - ); + var _constructor$body$mul; + const instanceProperties = getProperties(node, /*requireInitializer*/ + false, /*isStatic*/ + false); let properties = instanceProperties; if (!useDefineForClassFields) { - properties = filter(properties, (property) => !!property.initializer || isPrivateIdentifier(property.name) || hasAccessorModifier(property)); + properties = filter(properties, property => !!property.initializer || isPrivateIdentifier(property.name) || hasAccessorModifier(property)); } const privateMethodsAndAccessors = getPrivateInstanceMethodsAndAccessors(node); const needsConstructorBody = some(properties) || some(privateMethodsAndAccessors); if (!constructor && !needsConstructorBody) { - return visitFunctionBody( - /*node*/ - void 0, - visitor, - context - ); + return visitFunctionBody( /*node*/ + void 0, visitor, context); } resumeLexicalEnvironment(); const needsSyntheticConstructor = !constructor && isDerivedClass; @@ -93669,33 +85678,20 @@ ${lanes.join("\n")} const receiver = factory2.createThis(); addInstanceMethodStatements(initializerStatements, privateMethodsAndAccessors, receiver); if (constructor) { - const parameterProperties = filter(instanceProperties, (prop) => isParameterPropertyDeclaration(getOriginalNode(prop), constructor)); - const nonParameterProperties = filter(properties, (prop) => !isParameterPropertyDeclaration(getOriginalNode(prop), constructor)); + const parameterProperties = filter(instanceProperties, prop => isParameterPropertyDeclaration(getOriginalNode(prop), constructor)); + const nonParameterProperties = filter(properties, prop => !isParameterPropertyDeclaration(getOriginalNode(prop), constructor)); addPropertyOrClassStaticBlockStatements(initializerStatements, parameterProperties, receiver); addPropertyOrClassStaticBlockStatements(initializerStatements, nonParameterProperties, receiver); } else { addPropertyOrClassStaticBlockStatements(initializerStatements, properties, receiver); } if (constructor == null ? void 0 : constructor.body) { - statementOffset = factory2.copyPrologue( - constructor.body.statements, - statements, - /*ensureUseStrict*/ - false, - visitor - ); + statementOffset = factory2.copyPrologue(constructor.body.statements, statements, /*ensureUseStrict*/ + false, visitor); const superStatementIndices = findSuperStatementIndexPath(constructor.body.statements, statementOffset); if (superStatementIndices.length) { - transformConstructorBodyWorker( - statements, - constructor.body.statements, - statementOffset, - superStatementIndices, - /*superPathDepth*/ - 0, - initializerStatements, - constructor - ); + transformConstructorBodyWorker(statements, constructor.body.statements, statementOffset, superStatementIndices, /*superPathDepth*/ + 0, initializerStatements, constructor); } else { while (statementOffset < constructor.body.statements.length) { const statement = constructor.body.statements[statementOffset]; @@ -93710,16 +85706,8 @@ ${lanes.join("\n")} } } else { if (needsSyntheticConstructor) { - statements.push( - factory2.createExpressionStatement( - factory2.createCallExpression( - factory2.createSuper(), - /*typeArguments*/ - void 0, - [factory2.createSpreadElement(factory2.createIdentifier("arguments"))] - ) - ) - ); + statements.push(factory2.createExpressionStatement(factory2.createCallExpression(factory2.createSuper(), /*typeArguments*/ + void 0, [factory2.createSpreadElement(factory2.createIdentifier("arguments"))]))); } addRange(statements, initializerStatements); } @@ -93727,19 +85715,10 @@ ${lanes.join("\n")} if (statements.length === 0 && !constructor) { return void 0; } - const multiLine = (constructor == null ? void 0 : constructor.body) && constructor.body.statements.length >= statements.length ? constructor.body.multiLine ?? statements.length > 0 : statements.length > 0; - return setTextRange( - factory2.createBlock( - setTextRange( - factory2.createNodeArray(statements), - /*location*/ - constructor ? constructor.body.statements : node.members - ), - multiLine - ), - /*location*/ - constructor ? constructor.body : void 0 - ); + const multiLine = (constructor == null ? void 0 : constructor.body) && constructor.body.statements.length >= statements.length ? (_constructor$body$mul = constructor.body.multiLine) !== null && _constructor$body$mul !== void 0 ? _constructor$body$mul : statements.length > 0 : statements.length > 0; + return setTextRange(factory2.createBlock(setTextRange(factory2.createNodeArray(statements), /*location*/ + constructor ? constructor.body.statements : node.members), multiLine), /*location*/ + constructor ? constructor.body : void 0); } function addPropertyOrClassStaticBlockStatements(statements, properties, receiver) { for (const property of properties) { @@ -93774,17 +85753,14 @@ ${lanes.join("\n")} if (hasAccessorModifier(propertyOriginalNode)) { addEmitFlags(statement, 3072 /* NoComments */); } + return statement; } function generateInitializedPropertyExpressionsOrClassStaticBlock(propertiesOrClassStaticBlocks, receiver) { const expressions = []; for (const property of propertiesOrClassStaticBlocks) { - const expression = isClassStaticBlockDeclaration(property) ? setCurrentClassElementAnd(property, transformClassStaticBlockDeclaration, property) : setCurrentClassElementAnd( - property, - () => transformProperty(property, receiver), - /*arg*/ - void 0 - ); + const expression = isClassStaticBlockDeclaration(property) ? setCurrentClassElementAnd(property, transformClassStaticBlockDeclaration, property) : setCurrentClassElementAnd(property, () => transformProperty(property, receiver), /*arg*/ + void 0); if (!expression) { continue; } @@ -93824,18 +85800,9 @@ ${lanes.join("\n")} if (privateIdentifierInfo) { if (privateIdentifierInfo.kind === "f" /* Field */) { if (!privateIdentifierInfo.isStatic) { - return createPrivateInstanceFieldInitializer( - factory2, - receiver, - visitNode(property.initializer, visitor, isExpression), - privateIdentifierInfo.brandCheckIdentifier - ); + return createPrivateInstanceFieldInitializer(factory2, receiver, visitNode(property.initializer, visitor, isExpression), privateIdentifierInfo.brandCheckIdentifier); } else { - return createPrivateStaticFieldInitializer( - factory2, - privateIdentifierInfo.variableName, - visitNode(property.initializer, visitor, isExpression) - ); + return createPrivateStaticFieldInitializer(factory2, privateIdentifierInfo.variableName, visitNode(property.initializer, visitor, isExpression)); } } else { return void 0; @@ -93866,22 +85833,23 @@ ${lanes.join("\n")} setSourceMapRange(localName, propertyOriginalNode.name); setEmitFlags(localName, 3072 /* NoComments */); } else { - initializer ?? (initializer = factory2.createVoidZero()); + var _initializer; + (_initializer = initializer) !== null && _initializer !== void 0 ? _initializer : initializer = factory2.createVoidZero(); } if (emitAssignment || isPrivateIdentifier(propertyName)) { - const memberAccess = createMemberAccessForPropertyName( - factory2, - receiver, - propertyName, - /*location*/ - propertyName - ); + const memberAccess = createMemberAccessForPropertyName(factory2, receiver, propertyName, /*location*/ + propertyName); addEmitFlags(memberAccess, 1024 /* NoLeadingComments */); const expression = factory2.createAssignment(memberAccess, initializer); return expression; } else { const name = isComputedPropertyName(propertyName) ? propertyName.expression : isIdentifier(propertyName) ? factory2.createStringLiteral(unescapeLeadingUnderscores(propertyName.escapedText)) : propertyName; - const descriptor = factory2.createPropertyDescriptor({ value: initializer, configurable: true, writable: true, enumerable: true }); + const descriptor = factory2.createPropertyDescriptor({ + value: initializer, + configurable: true, + writable: true, + enumerable: true + }); return factory2.createObjectDefinePropertyCall(receiver, name, descriptor); } } @@ -93906,28 +85874,19 @@ ${lanes.join("\n")} context.enableEmitNotification(167 /* ComputedPropertyName */); } } + function addInstanceMethodStatements(statements, methods, receiver) { if (!shouldTransformPrivateElementsOrClassStaticBlocks || !some(methods)) { return; } - const { weakSetName } = getPrivateIdentifierEnvironment().data; + const { + weakSetName + } = getPrivateIdentifierEnvironment().data; Debug.assert(weakSetName, "weakSetName should be set in private identifier environment"); - statements.push( - factory2.createExpressionStatement( - createPrivateInstanceMethodInitializer(factory2, receiver, weakSetName) - ) - ); + statements.push(factory2.createExpressionStatement(createPrivateInstanceMethodInitializer(factory2, receiver, weakSetName))); } function visitInvalidSuperProperty(node) { - return isPropertyAccessExpression(node) ? factory2.updatePropertyAccessExpression( - node, - factory2.createVoidZero(), - node.name - ) : factory2.updateElementAccessExpression( - node, - factory2.createVoidZero(), - visitNode(node.argumentExpression, visitor, isExpression) - ); + return isPropertyAccessExpression(node) ? factory2.updatePropertyAccessExpression(node, factory2.createVoidZero(), node.name) : factory2.updateElementAccessExpression(node, factory2.createVoidZero(), visitNode(node.argumentExpression, visitor, isExpression)); } function getPropertyNameExpressionIfNeeded(name, shouldHoist) { if (isComputedPropertyName(name)) { @@ -93949,30 +85908,37 @@ ${lanes.join("\n")} } } function startClassLexicalEnvironment() { - lexicalEnvironment = { previous: lexicalEnvironment, data: void 0 }; + lexicalEnvironment = { + previous: lexicalEnvironment, + data: void 0 + }; } function endClassLexicalEnvironment() { lexicalEnvironment = lexicalEnvironment == null ? void 0 : lexicalEnvironment.previous; } function getClassLexicalEnvironment() { + var _lexicalEnvironment$d; Debug.assert(lexicalEnvironment); - return lexicalEnvironment.data ?? (lexicalEnvironment.data = { + return (_lexicalEnvironment$d = lexicalEnvironment.data) !== null && _lexicalEnvironment$d !== void 0 ? _lexicalEnvironment$d : lexicalEnvironment.data = { facts: 0 /* None */, classConstructor: void 0, classThis: void 0, superClassReference: void 0 // privateIdentifierEnvironment: undefined, - }); + }; } + function getPrivateIdentifierEnvironment() { + var _lexicalEnvironment$p; Debug.assert(lexicalEnvironment); - return lexicalEnvironment.privateEnv ?? (lexicalEnvironment.privateEnv = newPrivateEnvironment({ + return (_lexicalEnvironment$p = lexicalEnvironment.privateEnv) !== null && _lexicalEnvironment$p !== void 0 ? _lexicalEnvironment$p : lexicalEnvironment.privateEnv = newPrivateEnvironment({ className: void 0, weakSetName: void 0 - })); + }); } function getPendingExpressions() { - return pendingExpressions ?? (pendingExpressions = []); + var _pendingExpressions; + return (_pendingExpressions = pendingExpressions) !== null && _pendingExpressions !== void 0 ? _pendingExpressions : pendingExpressions = []; } function addPrivateIdentifierClassElementToEnvironment(node, name, lex, privateEnv, isStatic2, isValid, previousInfo) { if (isAutoAccessorPropertyDeclaration(node)) { @@ -93989,7 +85955,8 @@ ${lanes.join("\n")} } function addPrivateIdentifierPropertyDeclarationToEnvironment(_node, name, lex, privateEnv, isStatic2, isValid, _previousInfo) { if (isStatic2) { - const brandCheckIdentifier = Debug.checkDefined(lex.classThis ?? lex.classConstructor, "classConstructor should be set in private identifier environment"); + var _lex$classThis2; + const brandCheckIdentifier = Debug.checkDefined((_lex$classThis2 = lex.classThis) !== null && _lex$classThis2 !== void 0 ? _lex$classThis2 : lex.classConstructor, "classConstructor should be set in private identifier environment"); const variableName = createHoistedVariableForPrivateName(name); setPrivateIdentifier(privateEnv, name, { kind: "f" /* Field */, @@ -94006,20 +85973,14 @@ ${lanes.join("\n")} brandCheckIdentifier: weakMapName, isValid }); - getPendingExpressions().push(factory2.createAssignment( - weakMapName, - factory2.createNewExpression( - factory2.createIdentifier("WeakMap"), - /*typeArguments*/ - void 0, - [] - ) - )); + getPendingExpressions().push(factory2.createAssignment(weakMapName, factory2.createNewExpression(factory2.createIdentifier("WeakMap"), /*typeArguments*/ + void 0, []))); } } function addPrivateIdentifierMethodDeclarationToEnvironment(_node, name, lex, privateEnv, isStatic2, isValid, _previousInfo) { + var _lex$classThis3; const methodName = createHoistedVariableForPrivateName(name); - const brandCheckIdentifier = isStatic2 ? Debug.checkDefined(lex.classThis ?? lex.classConstructor, "classConstructor should be set in private identifier environment") : Debug.checkDefined(privateEnv.data.weakSetName, "weakSetName should be set in private identifier environment"); + const brandCheckIdentifier = isStatic2 ? Debug.checkDefined((_lex$classThis3 = lex.classThis) !== null && _lex$classThis3 !== void 0 ? _lex$classThis3 : lex.classConstructor, "classConstructor should be set in private identifier environment") : Debug.checkDefined(privateEnv.data.weakSetName, "weakSetName should be set in private identifier environment"); setPrivateIdentifier(privateEnv, name, { kind: "m" /* Method */, methodName, @@ -94029,8 +85990,9 @@ ${lanes.join("\n")} }); } function addPrivateIdentifierGetAccessorDeclarationToEnvironment(_node, name, lex, privateEnv, isStatic2, isValid, previousInfo) { + var _lex$classThis4; const getterName = createHoistedVariableForPrivateName(name, "_get"); - const brandCheckIdentifier = isStatic2 ? Debug.checkDefined(lex.classThis ?? lex.classConstructor, "classConstructor should be set in private identifier environment") : Debug.checkDefined(privateEnv.data.weakSetName, "weakSetName should be set in private identifier environment"); + const brandCheckIdentifier = isStatic2 ? Debug.checkDefined((_lex$classThis4 = lex.classThis) !== null && _lex$classThis4 !== void 0 ? _lex$classThis4 : lex.classConstructor, "classConstructor should be set in private identifier environment") : Debug.checkDefined(privateEnv.data.weakSetName, "weakSetName should be set in private identifier environment"); if ((previousInfo == null ? void 0 : previousInfo.kind) === "a" /* Accessor */ && previousInfo.isStatic === isStatic2 && !previousInfo.getterName) { previousInfo.getterName = getterName; } else { @@ -94045,8 +86007,9 @@ ${lanes.join("\n")} } } function addPrivateIdentifierSetAccessorDeclarationToEnvironment(_node, name, lex, privateEnv, isStatic2, isValid, previousInfo) { + var _lex$classThis5; const setterName = createHoistedVariableForPrivateName(name, "_set"); - const brandCheckIdentifier = isStatic2 ? Debug.checkDefined(lex.classThis ?? lex.classConstructor, "classConstructor should be set in private identifier environment") : Debug.checkDefined(privateEnv.data.weakSetName, "weakSetName should be set in private identifier environment"); + const brandCheckIdentifier = isStatic2 ? Debug.checkDefined((_lex$classThis5 = lex.classThis) !== null && _lex$classThis5 !== void 0 ? _lex$classThis5 : lex.classConstructor, "classConstructor should be set in private identifier environment") : Debug.checkDefined(privateEnv.data.weakSetName, "weakSetName should be set in private identifier environment"); if ((previousInfo == null ? void 0 : previousInfo.kind) === "a" /* Accessor */ && previousInfo.isStatic === isStatic2 && !previousInfo.setterName) { previousInfo.setterName = setterName; } else { @@ -94061,9 +86024,10 @@ ${lanes.join("\n")} } } function addPrivateIdentifierAutoAccessorPropertyDeclarationToEnvironment(_node, name, lex, privateEnv, isStatic2, isValid, _previousInfo) { + var _lex$classThis6; const getterName = createHoistedVariableForPrivateName(name, "_get"); const setterName = createHoistedVariableForPrivateName(name, "_set"); - const brandCheckIdentifier = isStatic2 ? Debug.checkDefined(lex.classThis ?? lex.classConstructor, "classConstructor should be set in private identifier environment") : Debug.checkDefined(privateEnv.data.weakSetName, "weakSetName should be set in private identifier environment"); + const brandCheckIdentifier = isStatic2 ? Debug.checkDefined((_lex$classThis6 = lex.classThis) !== null && _lex$classThis6 !== void 0 ? _lex$classThis6 : lex.classConstructor, "classConstructor should be set in private identifier environment") : Debug.checkDefined(privateEnv.data.weakSetName, "weakSetName should be set in private identifier environment"); setPrivateIdentifier(privateEnv, name, { kind: "a" /* Accessor */, getterName, @@ -94082,16 +86046,17 @@ ${lanes.join("\n")} addDeclaration(node, name, lex, privateEnv, isStatic2, isValid, previousInfo); } function createHoistedVariableForClass(name, node, suffix) { - const { className } = getPrivateIdentifierEnvironment().data; - const prefix = className ? { prefix: "_", node: className, suffix: "_" } : "_"; - const identifier = typeof name === "object" ? factory2.getGeneratedNameForNode(name, 16 /* Optimistic */ | 8 /* ReservedInNestedScopes */, prefix, suffix) : typeof name === "string" ? factory2.createUniqueName(name, 16 /* Optimistic */, prefix, suffix) : factory2.createTempVariable( - /*recordTempVariable*/ - void 0, - /*reservedInNestedScopes*/ - true, - prefix, - suffix - ); + const { + className + } = getPrivateIdentifierEnvironment().data; + const prefix = className ? { + prefix: "_", + node: className, + suffix: "_" + } : "_"; + const identifier = typeof name === "object" ? factory2.getGeneratedNameForNode(name, 16 /* Optimistic */ | 8 /* ReservedInNestedScopes */, prefix, suffix) : typeof name === "string" ? factory2.createUniqueName(name, 16 /* Optimistic */, prefix, suffix) : factory2.createTempVariable( /*recordTempVariable*/ + void 0, /*reservedInNestedScopes*/ + true, prefix, suffix); if (resolver.getNodeCheckFlags(node) & 32768 /* BlockScopedBindingInLoop */) { addBlockScopedVariable(identifier); } else { @@ -94100,8 +86065,9 @@ ${lanes.join("\n")} return identifier; } function createHoistedVariableForPrivateName(name, suffix) { + var _ref34; const text = tryGetTextOfPropertyName(name); - return createHoistedVariableForClass((text == null ? void 0 : text.substring(1)) ?? name, name, suffix); + return createHoistedVariableForClass((_ref34 = text == null ? void 0 : text.substring(1)) !== null && _ref34 !== void 0 ? _ref34 : name, name, suffix); } function accessPrivateIdentifier2(name) { const info = accessPrivateIdentifier(lexicalEnvironment, name); @@ -94115,23 +86081,13 @@ ${lanes.join("\n")} } let receiver = node.expression; if (isThisProperty(node) || isSuperProperty(node) || !isSimpleCopiableExpression(node.expression)) { - receiver = factory2.createTempVariable( - hoistVariableDeclaration, - /*reservedInNestedScopes*/ - true - ); + receiver = factory2.createTempVariable(hoistVariableDeclaration, /*reservedInNestedScopes*/ + true); getPendingExpressions().push(factory2.createBinaryExpression(receiver, 64 /* EqualsToken */, visitNode(node.expression, visitor, isExpression))); } - return factory2.createAssignmentTargetWrapper( - parameter, - createPrivateIdentifierAssignment( - info, - receiver, - parameter, - 64 /* EqualsToken */ - ) - ); + return factory2.createAssignmentTargetWrapper(parameter, createPrivateIdentifierAssignment(info, receiver, parameter, 64 /* EqualsToken */)); } + function visitDestructuringAssignmentTarget(node) { if (isObjectLiteralExpression(node) || isArrayLiteralExpression(node)) { return visitAssignmentPattern(node); @@ -94139,25 +86095,19 @@ ${lanes.join("\n")} if (isPrivateIdentifierPropertyAccessExpression(node)) { return wrapPrivateIdentifierForDestructuringTarget(node); } else if (shouldTransformSuperInStaticInitializers && currentClassElement && isSuperProperty(node) && isStaticPropertyDeclarationOrClassStaticBlock(currentClassElement) && (lexicalEnvironment == null ? void 0 : lexicalEnvironment.data)) { - const { classConstructor, superClassReference, facts } = lexicalEnvironment.data; + const { + classConstructor, + superClassReference, + facts + } = lexicalEnvironment.data; if (facts & 1 /* ClassWasDecorated */) { return visitInvalidSuperProperty(node); } else if (classConstructor && superClassReference) { const name = isElementAccessExpression(node) ? visitNode(node.argumentExpression, visitor, isExpression) : isIdentifier(node.name) ? factory2.createStringLiteralFromNode(node.name) : void 0; if (name) { - const temp = factory2.createTempVariable( - /*recordTempVariable*/ - void 0 - ); - return factory2.createAssignmentTargetWrapper( - temp, - factory2.createReflectSetCall( - superClassReference, - name, - temp, - classConstructor - ) - ); + const temp = factory2.createTempVariable( /*recordTempVariable*/ + void 0); + return factory2.createAssignmentTargetWrapper(temp, factory2.createReflectSetCall(superClassReference, name, temp, classConstructor)); } } } @@ -94167,11 +86117,8 @@ ${lanes.join("\n")} if (isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)) { node = transformNamedEvaluation(context, node); } - if (isAssignmentExpression( - node, - /*excludeCompoundAssignment*/ - true - )) { + if (isAssignmentExpression(node, /*excludeCompoundAssignment*/ + true)) { const left = visitDestructuringAssignmentTarget(node.left); const right = visitNode(node.right, visitor, isExpression); return factory2.updateBinaryExpression(node, left, node.operatorToken, right); @@ -94187,20 +86134,15 @@ ${lanes.join("\n")} } 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); } function visitAssignmentProperty(node) { const name = visitNode(node.name, visitor, isPropertyName); - if (isAssignmentExpression( - node.initializer, - /*excludeCompoundAssignment*/ - true - )) { + if (isAssignmentExpression(node.initializer, /*excludeCompoundAssignment*/ + true)) { const assignmentElement = visitAssignmentElement(node.initializer); return factory2.updatePropertyAssignment(node, name, assignmentElement); } @@ -94225,25 +86167,16 @@ ${lanes.join("\n")} } 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) { if (isArrayLiteralExpression(node)) { - return factory2.updateArrayLiteralExpression( - node, - visitNodes2(node.elements, visitArrayAssignmentElement, isExpression) - ); + return factory2.updateArrayLiteralExpression(node, visitNodes2(node.elements, visitArrayAssignmentElement, isExpression)); } else { - return factory2.updateObjectLiteralExpression( - node, - visitNodes2(node.properties, visitObjectAssignmentElement, isObjectLiteralElementLike) - ); + return factory2.updateObjectLiteralExpression(node, visitNodes2(node.properties, visitObjectAssignmentElement, isObjectLiteralElementLike)); } } function onEmitNode(hint, node, emitCallback) { @@ -94271,28 +86204,30 @@ ${lanes.join("\n")} case 177 /* GetAccessor */: case 178 /* SetAccessor */: case 174 /* MethodDeclaration */: - case 172 /* PropertyDeclaration */: { - const savedLexicalEnvironment = lexicalEnvironment; - const savedPreviousShouldSubstituteThisWithClassThis = previousShouldSubstituteThisWithClassThis; - lexicalEnvironment = void 0; - previousShouldSubstituteThisWithClassThis = shouldSubstituteThisWithClassThis; - shouldSubstituteThisWithClassThis = false; - previousOnEmitNode(hint, node, emitCallback); - shouldSubstituteThisWithClassThis = previousShouldSubstituteThisWithClassThis; - previousShouldSubstituteThisWithClassThis = savedPreviousShouldSubstituteThisWithClassThis; - lexicalEnvironment = savedLexicalEnvironment; - return; - } - case 167 /* ComputedPropertyName */: { - const savedLexicalEnvironment = lexicalEnvironment; - const savedShouldSubstituteThisWithClassThis = shouldSubstituteThisWithClassThis; - lexicalEnvironment = lexicalEnvironment == null ? void 0 : lexicalEnvironment.previous; - shouldSubstituteThisWithClassThis = previousShouldSubstituteThisWithClassThis; - previousOnEmitNode(hint, node, emitCallback); - shouldSubstituteThisWithClassThis = savedShouldSubstituteThisWithClassThis; - lexicalEnvironment = savedLexicalEnvironment; - return; - } + case 172 /* PropertyDeclaration */: + { + const savedLexicalEnvironment = lexicalEnvironment; + const savedPreviousShouldSubstituteThisWithClassThis = previousShouldSubstituteThisWithClassThis; + lexicalEnvironment = void 0; + previousShouldSubstituteThisWithClassThis = shouldSubstituteThisWithClassThis; + shouldSubstituteThisWithClassThis = false; + previousOnEmitNode(hint, node, emitCallback); + shouldSubstituteThisWithClassThis = previousShouldSubstituteThisWithClassThis; + previousShouldSubstituteThisWithClassThis = savedPreviousShouldSubstituteThisWithClassThis; + lexicalEnvironment = savedLexicalEnvironment; + return; + } + case 167 /* ComputedPropertyName */: + { + const savedLexicalEnvironment = lexicalEnvironment; + const savedShouldSubstituteThisWithClassThis = shouldSubstituteThisWithClassThis; + lexicalEnvironment = lexicalEnvironment == null ? void 0 : lexicalEnvironment.previous; + shouldSubstituteThisWithClassThis = previousShouldSubstituteThisWithClassThis; + previousOnEmitNode(hint, node, emitCallback); + shouldSubstituteThisWithClassThis = savedShouldSubstituteThisWithClassThis; + lexicalEnvironment = savedLexicalEnvironment; + return; + } } previousOnEmitNode(hint, node, emitCallback); } @@ -94314,16 +86249,14 @@ ${lanes.join("\n")} } function substituteThisExpression(node) { if (enabledSubstitutions & 2 /* ClassStaticThisOrSuperReference */ && (lexicalEnvironment == null ? void 0 : lexicalEnvironment.data) && !noSubstitution.has(node)) { - const { facts, classConstructor, classThis } = lexicalEnvironment.data; - const substituteThis = shouldSubstituteThisWithClassThis ? classThis ?? classConstructor : classConstructor; + const { + facts, + classConstructor, + classThis + } = lexicalEnvironment.data; + const substituteThis = shouldSubstituteThisWithClassThis ? classThis !== null && classThis !== void 0 ? classThis : classConstructor : classConstructor; if (substituteThis) { - return setTextRange( - setOriginalNode( - factory2.cloneNode(substituteThis), - node - ), - node - ); + return setTextRange(setOriginalNode(factory2.cloneNode(substituteThis), node), node); } if (facts & 1 /* ClassWasDecorated */ && legacyDecorators) { return factory2.createParenthesizedExpression(factory2.createVoidZero()); @@ -94353,28 +86286,15 @@ ${lanes.join("\n")} } } function createPrivateStaticFieldInitializer(factory2, variableName, initializer) { - return factory2.createAssignment( - variableName, - factory2.createObjectLiteralExpression([ - factory2.createPropertyAssignment("value", initializer || factory2.createVoidZero()) - ]) - ); + return factory2.createAssignment(variableName, factory2.createObjectLiteralExpression([factory2.createPropertyAssignment("value", initializer || factory2.createVoidZero())])); } function createPrivateInstanceFieldInitializer(factory2, receiver, initializer, weakMapName) { - return factory2.createCallExpression( - factory2.createPropertyAccessExpression(weakMapName, "set"), - /*typeArguments*/ - void 0, - [receiver, initializer || factory2.createVoidZero()] - ); + return factory2.createCallExpression(factory2.createPropertyAccessExpression(weakMapName, "set"), /*typeArguments*/ + void 0, [receiver, initializer || factory2.createVoidZero()]); } function createPrivateInstanceMethodInitializer(factory2, receiver, weakSetName) { - return factory2.createCallExpression( - factory2.createPropertyAccessExpression(weakSetName, "add"), - /*typeArguments*/ - void 0, - [receiver] - ); + return factory2.createCallExpression(factory2.createPropertyAccessExpression(weakSetName, "add"), /*typeArguments*/ + void 0, [receiver]); } function isReservedPrivateName(node) { return !isGeneratedPrivateIdentifier(node) && node.escapedText === "#constructor"; @@ -94382,6 +86302,7 @@ ${lanes.join("\n")} function isPrivateIdentifierInExpression(node) { return isPrivateIdentifier(node.left) && node.operatorToken.kind === 103 /* InKeyword */; } + function isStaticPropertyDeclaration2(node) { return isPropertyDeclaration(node) && hasStaticModifier(node); } @@ -94391,6 +86312,7 @@ ${lanes.join("\n")} var init_classFields = __esm({ "src/compiler/transformers/classFields.ts"() { "use strict"; + init_ts2(); } }); @@ -94465,7 +86387,9 @@ ${lanes.join("\n")} } function getParametersOfDecoratedDeclaration(node, container) { if (container && node.kind === 177 /* GetAccessor */) { - const { setAccessor } = getAllAccessorDeclarations(container.members, node); + const { + setAccessor + } = getAllAccessorDeclarations(container.members, node); if (setAccessor) { return setAccessor.parameters; } @@ -94516,23 +86440,14 @@ ${lanes.join("\n")} case 183 /* TypeReference */: return serializeTypeReferenceNode(node); case 193 /* IntersectionType */: - return serializeUnionOrIntersectionConstituents( - node.types, - /*isIntersection*/ - true - ); + return serializeUnionOrIntersectionConstituents(node.types, /*isIntersection*/ + true); case 192 /* UnionType */: - return serializeUnionOrIntersectionConstituents( - node.types, - /*isIntersection*/ - false - ); + return serializeUnionOrIntersectionConstituents(node.types, /*isIntersection*/ + false); case 194 /* ConditionalType */: - return serializeUnionOrIntersectionConstituents( - [node.trueType, node.falseType], - /*isIntersection*/ - false - ); + return serializeUnionOrIntersectionConstituents([node.trueType, node.falseType], /*isIntersection*/ + false); case 198 /* TypeOperator */: if (node.operator === 148 /* ReadonlyKeyword */) { return serializeTypeNode(node.type); @@ -94567,16 +86482,17 @@ ${lanes.join("\n")} case 11 /* StringLiteral */: case 15 /* NoSubstitutionTemplateLiteral */: return factory2.createIdentifier("String"); - case 224 /* PrefixUnaryExpression */: { - const operand = node.operand; - switch (operand.kind) { - case 9 /* NumericLiteral */: - case 10 /* BigIntLiteral */: - return serializeLiteralOfLiteralTypeNode(operand); - default: - return Debug.failBadSyntaxKind(operand); + case 224 /* PrefixUnaryExpression */: + { + const operand = node.operand; + switch (operand.kind) { + case 9 /* NumericLiteral */: + case 10 /* BigIntLiteral */: + return serializeLiteralOfLiteralTypeNode(operand); + default: + return Debug.failBadSyntaxKind(operand); + } } - } case 9 /* NumericLiteral */: return factory2.createIdentifier("Number"); case 10 /* BigIntLiteral */: @@ -94591,17 +86507,16 @@ ${lanes.join("\n")} } } function serializeUnionOrIntersectionConstituents(types, isIntersection) { + var _serializedType; let serializedType; 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 */) { @@ -94622,53 +86537,41 @@ ${lanes.join("\n")} serializedType = serializedConstituent; } } - return serializedType ?? factory2.createVoidZero(); + return (_serializedType = serializedType) !== null && _serializedType !== void 0 ? _serializedType : factory2.createVoidZero(); } function equateSerializedTypeNodes(left, right) { return ( // temp vars used in fallback - isGeneratedIdentifier(left) ? isGeneratedIdentifier(right) : ( - // entity names - isIdentifier(left) ? isIdentifier(right) && left.escapedText === right.escapedText : isPropertyAccessExpression(left) ? isPropertyAccessExpression(right) && equateSerializedTypeNodes(left.expression, right.expression) && equateSerializedTypeNodes(left.name, right.name) : ( - // `void 0` - isVoidExpression(left) ? isVoidExpression(right) && isNumericLiteral(left.expression) && left.expression.text === "0" && isNumericLiteral(right.expression) && right.expression.text === "0" : ( - // `"undefined"` or `"function"` in `typeof` checks - isStringLiteral(left) ? isStringLiteral(right) && left.text === right.text : ( - // used in `typeof` checks for fallback - isTypeOfExpression(left) ? isTypeOfExpression(right) && equateSerializedTypeNodes(left.expression, right.expression) : ( - // parens in `typeof` checks with temps - isParenthesizedExpression(left) ? isParenthesizedExpression(right) && equateSerializedTypeNodes(left.expression, right.expression) : ( - // conditionals used in fallback - isConditionalExpression(left) ? isConditionalExpression(right) && equateSerializedTypeNodes(left.condition, right.condition) && equateSerializedTypeNodes(left.whenTrue, right.whenTrue) && equateSerializedTypeNodes(left.whenFalse, right.whenFalse) : ( - // logical binary and assignments used in fallback - isBinaryExpression(left) ? isBinaryExpression(right) && left.operatorToken.kind === right.operatorToken.kind && equateSerializedTypeNodes(left.left, right.left) && equateSerializedTypeNodes(left.right, right.right) : false - ) - ) - ) - ) - ) - ) - ) + isGeneratedIdentifier(left) ? isGeneratedIdentifier(right) : + // entity names + isIdentifier(left) ? isIdentifier(right) && left.escapedText === right.escapedText : isPropertyAccessExpression(left) ? isPropertyAccessExpression(right) && equateSerializedTypeNodes(left.expression, right.expression) && equateSerializedTypeNodes(left.name, right.name) : + // `void 0` + isVoidExpression(left) ? isVoidExpression(right) && isNumericLiteral(left.expression) && left.expression.text === "0" && isNumericLiteral(right.expression) && right.expression.text === "0" : + // `"undefined"` or `"function"` in `typeof` checks + isStringLiteral(left) ? isStringLiteral(right) && left.text === right.text : + // used in `typeof` checks for fallback + isTypeOfExpression(left) ? isTypeOfExpression(right) && equateSerializedTypeNodes(left.expression, right.expression) : + // parens in `typeof` checks with temps + isParenthesizedExpression(left) ? isParenthesizedExpression(right) && equateSerializedTypeNodes(left.expression, right.expression) : + // conditionals used in fallback + isConditionalExpression(left) ? isConditionalExpression(right) && equateSerializedTypeNodes(left.condition, right.condition) && equateSerializedTypeNodes(left.whenTrue, right.whenTrue) && equateSerializedTypeNodes(left.whenFalse, right.whenFalse) : + // logical binary and assignments used in fallback + isBinaryExpression(left) ? isBinaryExpression(right) && left.operatorToken.kind === right.operatorToken.kind && equateSerializedTypeNodes(left.left, right.left) && equateSerializedTypeNodes(left.right, right.right) : false ); } function serializeTypeReferenceNode(node) { - const kind = resolver.getTypeReferenceSerializationKind(node.typeName, currentNameScope ?? currentLexicalScope); + var _currentNameScope; + const kind = resolver.getTypeReferenceSerializationKind(node.typeName, (_currentNameScope = currentNameScope) !== null && _currentNameScope !== void 0 ? _currentNameScope : currentLexicalScope); switch (kind) { case 0 /* Unknown */: - if (findAncestor(node, (n) => n.parent && isConditionalTypeNode(n.parent) && (n.parent.trueType === n || n.parent.falseType === n))) { + if (findAncestor(node, n => n.parent && isConditionalTypeNode(n.parent) && (n.parent.trueType === n || n.parent.falseType === n))) { return factory2.createIdentifier("Object"); } const serialized = serializeEntityNameAsExpressionFallback(node.typeName); const temp = factory2.createTempVariable(hoistVariableDeclaration); - return factory2.createConditionalExpression( - factory2.createTypeCheck(factory2.createAssignment(temp, serialized), "function"), - /*questionToken*/ - void 0, - temp, - /*colonToken*/ - void 0, - factory2.createIdentifier("Object") - ); + return factory2.createConditionalExpression(factory2.createTypeCheck(factory2.createAssignment(temp, serialized), "function"), /*questionToken*/ + void 0, temp, /*colonToken*/ + void 0, factory2.createIdentifier("Object")); case 1 /* TypeWithConstructSignatureAndValue */: return serializeEntityNameAsExpression(node.typeName); case 2 /* VoidNullableOrNeverType */: @@ -94696,10 +86599,7 @@ ${lanes.join("\n")} } } function createCheckedValue(left, right) { - return factory2.createLogicalAnd( - factory2.createStrictInequality(factory2.createTypeOfExpression(left), factory2.createStringLiteral("undefined")), - right - ); + return factory2.createLogicalAnd(factory2.createStrictInequality(factory2.createTypeOfExpression(left), factory2.createStringLiteral("undefined")), right); } function serializeEntityNameAsExpressionFallback(node) { if (node.kind === 80 /* Identifier */) { @@ -94711,13 +86611,7 @@ ${lanes.join("\n")} } const left = serializeEntityNameAsExpressionFallback(node.left); const temp = factory2.createTempVariable(hoistVariableDeclaration); - return factory2.createLogicalAnd( - factory2.createLogicalAnd( - left.left, - factory2.createStrictInequality(factory2.createAssignment(temp, left.right), factory2.createVoidZero()) - ), - factory2.createPropertyAccessExpression(temp, node.right) - ); + return factory2.createLogicalAnd(factory2.createLogicalAnd(left.left, factory2.createStrictInequality(factory2.createAssignment(temp, left.right), factory2.createVoidZero())), factory2.createPropertyAccessExpression(temp, node.right)); } function serializeEntityNameAsExpression(node) { switch (node.kind) { @@ -94734,15 +86628,9 @@ ${lanes.join("\n")} return factory2.createPropertyAccessExpression(serializeEntityNameAsExpression(node.left), node.right); } function getGlobalConstructorWithFallback(name) { - return factory2.createConditionalExpression( - factory2.createTypeCheck(factory2.createIdentifier(name), "function"), - /*questionToken*/ - void 0, - factory2.createIdentifier(name), - /*colonToken*/ - void 0, - factory2.createIdentifier("Object") - ); + return factory2.createConditionalExpression(factory2.createTypeCheck(factory2.createIdentifier(name), "function"), /*questionToken*/ + void 0, factory2.createIdentifier(name), /*colonToken*/ + void 0, factory2.createIdentifier("Object")); } function getGlobalConstructor(name, minLanguageVersion) { return languageVersion < minLanguageVersion ? getGlobalConstructorWithFallback(name) : factory2.createIdentifier(name); @@ -94751,6 +86639,7 @@ ${lanes.join("\n")} var init_typeSerializer = __esm({ "src/compiler/transformers/typeSerializer.ts"() { "use strict"; + init_ts2(); } }); @@ -94805,161 +86694,95 @@ ${lanes.join("\n")} } } function visitClassDeclaration(node) { - if (!(classOrConstructorParameterIsDecorated( - /*useLegacyDecorators*/ - true, - node - ) || childIsDecorated( - /*useLegacyDecorators*/ - true, - node - ))) { + if (!(classOrConstructorParameterIsDecorated( /*useLegacyDecorators*/ + true, node) || childIsDecorated( /*useLegacyDecorators*/ + true, node))) { return visitEachChild(node, visitor, context); } - const statements = classOrConstructorParameterIsDecorated( - /*useLegacyDecorators*/ - true, - node - ) ? transformClassDeclarationWithClassDecorators(node, node.name) : transformClassDeclarationWithoutClassDecorators(node, node.name); + const statements = classOrConstructorParameterIsDecorated( /*useLegacyDecorators*/ + true, node) ? transformClassDeclarationWithClassDecorators(node, node.name) : transformClassDeclarationWithoutClassDecorators(node, node.name); return singleOrMany(statements); } function decoratorContainsPrivateIdentifierInExpression(decorator) { return !!(decorator.transformFlags & 536870912 /* ContainsPrivateIdentifierInExpression */); } + function parameterDecoratorsContainPrivateIdentifierInExpression(parameterDecorators) { return some(parameterDecorators, decoratorContainsPrivateIdentifierInExpression); } function hasClassElementWithDecoratorContainingPrivateIdentifierInExpression(node) { for (const member of node.members) { - 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 (!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; } return false; } function transformDecoratorsOfClassElements(node, members) { let decorationStatements = []; - addClassElementDecorationStatements( - decorationStatements, - node, - /*isStatic*/ - false - ); - addClassElementDecorationStatements( - decorationStatements, - node, - /*isStatic*/ - true - ); + addClassElementDecorationStatements(decorationStatements, node, /*isStatic*/ + false); + addClassElementDecorationStatements(decorationStatements, node, /*isStatic*/ + true); if (hasClassElementWithDecoratorContainingPrivateIdentifierInExpression(node)) { - members = setTextRange( - factory2.createNodeArray([ - ...members, - factory2.createClassStaticBlockDeclaration( - factory2.createBlock( - decorationStatements, - /*multiLine*/ - true - ) - ) - ]), - members - ); + members = setTextRange(factory2.createNodeArray([...members, factory2.createClassStaticBlockDeclaration(factory2.createBlock(decorationStatements, /*multiLine*/ + true))]), members); decorationStatements = void 0; } - return { decorationStatements, members }; + return { + decorationStatements, + members + }; } function transformClassDeclarationWithoutClassDecorators(node, name) { const modifiers = visitNodes2(node.modifiers, modifierVisitor, isModifier); const heritageClauses = visitNodes2(node.heritageClauses, visitor, isHeritageClause); let members = visitNodes2(node.members, visitor, isClassElement); let decorationStatements = []; - ({ members, decorationStatements } = transformDecoratorsOfClassElements(node, members)); - const updated = factory2.updateClassDeclaration( - node, - modifiers, - name, - /*typeParameters*/ - void 0, - heritageClauses, - members - ); + ({ + members, + decorationStatements + } = transformDecoratorsOfClassElements(node, members)); + const updated = factory2.updateClassDeclaration(node, modifiers, name, /*typeParameters*/ + void 0, heritageClauses, members); return addRange([updated], decorationStatements); } function transformClassDeclarationWithClassDecorators(node, name) { const isExport = hasSyntacticModifier(node, 32 /* Export */); const isDefault = hasSyntacticModifier(node, 2048 /* Default */); - const modifiers = visitNodes2(node.modifiers, (node2) => isExportOrDefaultModifier(node2) || isDecorator(node2) ? void 0 : node2, isModifierLike); + const modifiers = visitNodes2(node.modifiers, node2 => isExportOrDefaultModifier(node2) || isDecorator(node2) ? void 0 : node2, isModifierLike); const location = moveRangePastModifiers(node); const classAlias = getClassAliasIfNeeded(node); - const declName = languageVersion < 2 /* ES2015 */ ? factory2.getInternalName( - node, - /*allowComments*/ - false, - /*allowSourceMaps*/ - true - ) : factory2.getLocalName( - node, - /*allowComments*/ - false, - /*allowSourceMaps*/ - true - ); + const declName = languageVersion < 2 /* ES2015 */ ? factory2.getInternalName(node, /*allowComments*/ + false, /*allowSourceMaps*/ + true) : factory2.getLocalName(node, /*allowComments*/ + false, /*allowSourceMaps*/ + true); const heritageClauses = visitNodes2(node.heritageClauses, visitor, isHeritageClause); let members = visitNodes2(node.members, visitor, isClassElement); let decorationStatements = []; - ({ members, decorationStatements } = transformDecoratorsOfClassElements(node, members)); - const assignClassAliasInStaticBlock = languageVersion >= 9 /* ES2022 */ && !!classAlias && some(members, (member) => isPropertyDeclaration(member) && hasSyntacticModifier(member, 256 /* Static */) || isClassStaticBlockDeclaration(member)); + ({ + members, + decorationStatements + } = transformDecoratorsOfClassElements(node, members)); + const assignClassAliasInStaticBlock = languageVersion >= 9 /* ES2022 */ && !!classAlias && some(members, member => isPropertyDeclaration(member) && hasSyntacticModifier(member, 256 /* Static */) || isClassStaticBlockDeclaration(member)); if (assignClassAliasInStaticBlock) { - members = setTextRange( - factory2.createNodeArray([ - factory2.createClassStaticBlockDeclaration( - factory2.createBlock([ - factory2.createExpressionStatement( - factory2.createAssignment(classAlias, factory2.createThis()) - ) - ]) - ), - ...members - ]), - members - ); + members = setTextRange(factory2.createNodeArray([factory2.createClassStaticBlockDeclaration(factory2.createBlock([factory2.createExpressionStatement(factory2.createAssignment(classAlias, factory2.createThis()))])), ...members]), members); } - const classExpression = factory2.createClassExpression( - modifiers, - name && isGeneratedIdentifier(name) ? void 0 : name, - /*typeParameters*/ - void 0, - heritageClauses, - members - ); + const classExpression = factory2.createClassExpression(modifiers, name && isGeneratedIdentifier(name) ? void 0 : name, /*typeParameters*/ + void 0, heritageClauses, members); setOriginalNode(classExpression, node); setTextRange(classExpression, location); const varInitializer = classAlias && !assignClassAliasInStaticBlock ? factory2.createAssignment(classAlias, classExpression) : classExpression; - const varDecl = factory2.createVariableDeclaration( - declName, - /*exclamationToken*/ - void 0, - /*type*/ - void 0, - varInitializer - ); + const varDecl = factory2.createVariableDeclaration(declName, /*exclamationToken*/ + void 0, /*type*/ + void 0, varInitializer); setOriginalNode(varDecl, node); const varDeclList = factory2.createVariableDeclarationList([varDecl], 1 /* Let */); - const varStatement = factory2.createVariableStatement( - /*modifiers*/ - void 0, - varDeclList - ); + const varStatement = factory2.createVariableStatement( /*modifiers*/ + void 0, varDeclList); setOriginalNode(varStatement, node); setTextRange(varStatement, location); setCommentRange(varStatement, node); @@ -94978,23 +86801,11 @@ ${lanes.join("\n")} return statements; } function visitClassExpression(node) { - return factory2.updateClassExpression( - node, - visitNodes2(node.modifiers, modifierVisitor, isModifier), - node.name, - /*typeParameters*/ - void 0, - visitNodes2(node.heritageClauses, visitor, isHeritageClause), - visitNodes2(node.members, visitor, isClassElement) - ); + return factory2.updateClassExpression(node, visitNodes2(node.modifiers, modifierVisitor, isModifier), node.name, /*typeParameters*/ + void 0, visitNodes2(node.heritageClauses, visitor, isHeritageClause), visitNodes2(node.members, visitor, isClassElement)); } function visitConstructorDeclaration(node) { - return factory2.updateConstructorDeclaration( - node, - visitNodes2(node.modifiers, modifierVisitor, isModifier), - visitNodes2(node.parameters, visitor, isParameter), - visitNode(node.body, visitor, isBlock) - ); + return factory2.updateConstructorDeclaration(node, visitNodes2(node.modifiers, modifierVisitor, isModifier), visitNodes2(node.parameters, visitor, isParameter), visitNode(node.body, visitor, isBlock)); } function finishClassElement(updated, original) { if (updated !== original) { @@ -95004,86 +86815,37 @@ ${lanes.join("\n")} return updated; } function visitMethodDeclaration(node) { - return finishClassElement( - factory2.updateMethodDeclaration( - node, - visitNodes2(node.modifiers, modifierVisitor, isModifier), - node.asteriskToken, - Debug.checkDefined(visitNode(node.name, visitor, isPropertyName)), - /*questionToken*/ - void 0, - /*typeParameters*/ - void 0, - visitNodes2(node.parameters, visitor, isParameter), - /*type*/ - void 0, - visitNode(node.body, visitor, isBlock) - ), - node - ); + return finishClassElement(factory2.updateMethodDeclaration(node, visitNodes2(node.modifiers, modifierVisitor, isModifier), node.asteriskToken, Debug.checkDefined(visitNode(node.name, visitor, isPropertyName)), /*questionToken*/ + void 0, /*typeParameters*/ + void 0, visitNodes2(node.parameters, visitor, isParameter), /*type*/ + void 0, visitNode(node.body, visitor, isBlock)), node); } function visitGetAccessorDeclaration(node) { - return finishClassElement( - factory2.updateGetAccessorDeclaration( - node, - visitNodes2(node.modifiers, modifierVisitor, isModifier), - Debug.checkDefined(visitNode(node.name, visitor, isPropertyName)), - visitNodes2(node.parameters, visitor, isParameter), - /*type*/ - void 0, - visitNode(node.body, visitor, isBlock) - ), - node - ); + return finishClassElement(factory2.updateGetAccessorDeclaration(node, visitNodes2(node.modifiers, modifierVisitor, isModifier), Debug.checkDefined(visitNode(node.name, visitor, isPropertyName)), visitNodes2(node.parameters, visitor, isParameter), /*type*/ + void 0, visitNode(node.body, visitor, isBlock)), node); } function visitSetAccessorDeclaration(node) { - return finishClassElement( - factory2.updateSetAccessorDeclaration( - node, - visitNodes2(node.modifiers, modifierVisitor, isModifier), - Debug.checkDefined(visitNode(node.name, visitor, isPropertyName)), - visitNodes2(node.parameters, visitor, isParameter), - visitNode(node.body, visitor, isBlock) - ), - node - ); + return finishClassElement(factory2.updateSetAccessorDeclaration(node, visitNodes2(node.modifiers, modifierVisitor, isModifier), Debug.checkDefined(visitNode(node.name, visitor, isPropertyName)), visitNodes2(node.parameters, visitor, isParameter), visitNode(node.body, visitor, isBlock)), node); } function visitPropertyDeclaration(node) { if (node.flags & 33554432 /* Ambient */ || hasSyntacticModifier(node, 128 /* Ambient */)) { return void 0; } - return finishClassElement( - factory2.updatePropertyDeclaration( - node, - visitNodes2(node.modifiers, modifierVisitor, isModifier), - Debug.checkDefined(visitNode(node.name, visitor, isPropertyName)), - /*questionOrExclamationToken*/ - void 0, - /*type*/ - void 0, - visitNode(node.initializer, visitor, isExpression) - ), - node - ); + return finishClassElement(factory2.updatePropertyDeclaration(node, visitNodes2(node.modifiers, modifierVisitor, isModifier), Debug.checkDefined(visitNode(node.name, visitor, isPropertyName)), /*questionOrExclamationToken*/ + void 0, /*type*/ + void 0, visitNode(node.initializer, visitor, isExpression)), node); } function visitParameterDeclaration(node) { - const updated = factory2.updateParameterDeclaration( - node, - elideNodes(factory2, node.modifiers), - node.dotDotDotToken, - Debug.checkDefined(visitNode(node.name, visitor, isBindingName)), - /*questionToken*/ - void 0, - /*type*/ - void 0, - visitNode(node.initializer, visitor, isExpression) - ); + const updated = factory2.updateParameterDeclaration(node, elideNodes(factory2, node.modifiers), node.dotDotDotToken, Debug.checkDefined(visitNode(node.name, visitor, isBindingName)), /*questionToken*/ + void 0, /*type*/ + void 0, visitNode(node.initializer, visitor, isExpression)); if (updated !== node) { setCommentRange(updated, node); setTextRange(updated, moveRangePastModifiers(node)); setSourceMapRange(updated, moveRangePastModifiers(node)); setEmitFlags(updated.name, 64 /* NoTrailingSourceMap */); } + return updated; } function isSyntheticMetadataDecorator(node) { @@ -95093,7 +86855,10 @@ ${lanes.join("\n")} if (!allDecorators) { return void 0; } - const { false: decorators, true: metadata } = groupBy(allDecorators.decorators, isSyntheticMetadataDecorator); + const { + false: decorators, + true: metadata + } = groupBy(allDecorators.decorators, isSyntheticMetadataDecorator); const decoratorExpressions = []; addRange(decoratorExpressions, map(decorators, transformDecorator)); addRange(decoratorExpressions, flatMap(allDecorators.parameters, transformDecoratorsOfParameter)); @@ -95101,18 +86866,14 @@ ${lanes.join("\n")} return decoratorExpressions; } function addClassElementDecorationStatements(statements, node, isStatic2) { - addRange(statements, map(generateClassElementDecorationExpressions(node, isStatic2), (expr) => factory2.createExpressionStatement(expr))); + addRange(statements, map(generateClassElementDecorationExpressions(node, isStatic2), expr => factory2.createExpressionStatement(expr))); } function isDecoratedClassElement(member, isStaticElement, parent2) { - return nodeOrChildIsDecorated( - /*useLegacyDecorators*/ - true, - member, - parent2 - ) && isStaticElement === isStatic(member); + return nodeOrChildIsDecorated( /*useLegacyDecorators*/ + true, member, parent2) && isStaticElement === isStatic(member); } function getDecoratedClassElements(node, isStatic2) { - return filter(node.members, (m) => isDecoratedClassElement(m, isStatic2, node)); + return filter(node.members, m => isDecoratedClassElement(m, isStatic2, node)); } function generateClassElementDecorationExpressions(node, isStatic2) { const members = getDecoratedClassElements(node, isStatic2); @@ -95123,29 +86884,18 @@ ${lanes.join("\n")} return expressions; } function generateClassElementDecorationExpression(node, member) { - const allDecorators = getAllDecoratorsOfClassElement( - member, - node, - /*useLegacyDecorators*/ - true - ); + const allDecorators = getAllDecoratorsOfClassElement(member, node, /*useLegacyDecorators*/ + true); const decoratorExpressions = transformAllDecoratorsOfDeclaration(allDecorators); if (!decoratorExpressions) { return void 0; } const prefix = getClassMemberPrefix(node, member); - const memberName = getExpressionForPropertyName( - member, - /*generateNameForComputedPropertyName*/ - !hasSyntacticModifier(member, 128 /* Ambient */) - ); + const memberName = getExpressionForPropertyName(member, /*generateNameForComputedPropertyName*/ + !hasSyntacticModifier(member, 128 /* Ambient */)); + const descriptor = languageVersion > 0 /* ES3 */ ? isPropertyDeclaration(member) && !hasAccessorModifier(member) ? factory2.createVoidZero() : factory2.createNull() : void 0; - const helper = emitHelpers().createDecorateHelper( - decoratorExpressions, - prefix, - memberName, - descriptor - ); + const helper = emitHelpers().createDecorateHelper(decoratorExpressions, prefix, memberName, descriptor); setEmitFlags(helper, 3072 /* NoComments */); setSourceMapRange(helper, moveRangePastModifiers(member)); return helper; @@ -95163,19 +86913,11 @@ ${lanes.join("\n")} return void 0; } const classAlias = classAliases && classAliases[getOriginalNodeId(node)]; - const localName = languageVersion < 2 /* ES2015 */ ? factory2.getInternalName( - node, - /*allowComments*/ - false, - /*allowSourceMaps*/ - true - ) : factory2.getDeclarationName( - node, - /*allowComments*/ - false, - /*allowSourceMaps*/ - true - ); + const localName = languageVersion < 2 /* ES2015 */ ? factory2.getInternalName(node, /*allowComments*/ + false, /*allowSourceMaps*/ + true) : factory2.getDeclarationName(node, /*allowComments*/ + false, /*allowSourceMaps*/ + true); const decorate = emitHelpers().createDecorateHelper(decoratorExpressions, localName); const expression = factory2.createAssignment(localName, classAlias ? factory2.createAssignment(classAlias, decorate) : decorate); setEmitFlags(expression, 3072 /* NoComments */); @@ -95190,10 +86932,7 @@ ${lanes.join("\n")} if (decorators) { expressions = []; for (const decorator of decorators) { - const helper = emitHelpers().createParamHelper( - transformDecorator(decorator), - parameterOffset - ); + const helper = emitHelpers().createParamHelper(transformDecorator(decorator), parameterOffset); setTextRange(helper, decorator.expression); setEmitFlags(helper, 3072 /* NoComments */); expressions.push(helper); @@ -95249,7 +86988,8 @@ ${lanes.join("\n")} return node; } function substituteExpressionIdentifier(node) { - return trySubstituteClassAlias(node) ?? node; + var _trySubstituteClassAl; + return (_trySubstituteClassAl = trySubstituteClassAlias(node)) !== null && _trySubstituteClassAl !== void 0 ? _trySubstituteClassAl : node; } function trySubstituteClassAlias(node) { if (classAliases) { @@ -95272,6 +87012,7 @@ ${lanes.join("\n")} var init_legacyDecorators = __esm({ "src/compiler/transformers/legacyDecorators.ts"() { "use strict"; + init_ts2(); } }); @@ -95328,7 +87069,12 @@ ${lanes.join("\n")} } } function enterClass(classInfo2) { - top = { kind: "class", next: top, classInfo: classInfo2, savedPendingExpressions: pendingExpressions }; + top = { + kind: "class", + next: top, + classInfo: classInfo2, + savedPendingExpressions: pendingExpressions + }; pendingExpressions = void 0; updateState(); } @@ -95341,7 +87087,10 @@ ${lanes.join("\n")} function enterClassElement(node) { var _a, _b; Debug.assert((top == null ? void 0 : top.kind) === "class", "Incorrect value for top.kind.", () => `Expected top.kind to be 'class' but got '${top == null ? void 0 : top.kind}' instead.`); - top = { kind: "class-element", next: top }; + top = { + kind: "class-element", + next: top + }; if (isClassStaticBlockDeclaration(node) || isPropertyDeclaration(node) && hasStaticModifier(node)) { top.classThis = (_a = top.next.classInfo) == null ? void 0 : _a.classThis; top.classSuper = (_b = top.next.classInfo) == null ? void 0 : _b.classSuper; @@ -95360,7 +87109,10 @@ ${lanes.join("\n")} } function enterName() { Debug.assert((top == null ? void 0 : top.kind) === "class-element", "Incorrect value for top.kind.", () => `Expected top.kind to be 'class-element' but got '${top == null ? void 0 : top.kind}' instead.`); - top = { kind: "name", next: top }; + top = { + kind: "name", + next: top + }; updateState(); } function exitName() { @@ -95373,7 +87125,12 @@ ${lanes.join("\n")} Debug.assert(!pendingExpressions); top.depth++; } else { - top = { kind: "other", next: top, depth: 0, savedPendingExpressions: pendingExpressions }; + top = { + kind: "other", + next: top, + depth: 0, + savedPendingExpressions: pendingExpressions + }; pendingExpressions = void 0; updateState(); } @@ -95392,6 +87149,7 @@ ${lanes.join("\n")} function shouldVisitNode(node) { return !!(node.transformFlags & 33554432 /* ContainsDecorators */) || !!classThis && !!(node.transformFlags & 16384 /* ContainsLexicalThis */) || !!classThis && !!classSuper && !!(node.transformFlags & 134217728 /* ContainsLexicalSuper */); } + function visitor(node) { if (!shouldVisitNode(node)) { return node; @@ -95410,11 +87168,8 @@ ${lanes.join("\n")} case 169 /* Parameter */: return visitParameterDeclaration(node); case 226 /* BinaryExpression */: - return visitBinaryExpression( - node, - /*discarded*/ - false - ); + return visitBinaryExpression(node, /*discarded*/ + false); case 303 /* PropertyAssignment */: return visitPropertyAssignment(node); case 260 /* VariableDeclaration */: @@ -95430,34 +87185,22 @@ ${lanes.join("\n")} case 244 /* ExpressionStatement */: return visitExpressionStatement(node); case 361 /* CommaListExpression */: - return visitCommaListExpression( - node, - /*discarded*/ - false - ); + return visitCommaListExpression(node, /*discarded*/ + false); case 217 /* ParenthesizedExpression */: - return visitParenthesizedExpression( - node, - /*discarded*/ - false - ); + return visitParenthesizedExpression(node, /*discarded*/ + false); case 360 /* PartiallyEmittedExpression */: - return visitPartiallyEmittedExpression( - node, - /*discarded*/ - false - ); + return visitPartiallyEmittedExpression(node, /*discarded*/ + false); case 213 /* CallExpression */: return visitCallExpression(node); case 215 /* TaggedTemplateExpression */: return visitTaggedTemplateExpression(node); case 224 /* PrefixUnaryExpression */: case 225 /* PostfixUnaryExpression */: - return visitPreOrPostfixUnaryExpression( - node, - /*discarded*/ - false - ); + return visitPreOrPostfixUnaryExpression(node, /*discarded*/ + false); case 211 /* PropertyAccessExpression */: return visitPropertyAccessExpression(node); case 212 /* ElementAccessExpression */: @@ -95468,12 +87211,13 @@ ${lanes.join("\n")} case 178 /* SetAccessor */: case 177 /* GetAccessor */: case 218 /* FunctionExpression */: - case 262 /* FunctionDeclaration */: { - enterOther(); - const result = visitEachChild(node, fallbackVisitor, context); - exitOther(); - return result; - } + case 262 /* FunctionDeclaration */: + { + enterOther(); + const result = visitEachChild(node, fallbackVisitor, context); + exitOther(); + return result; + } default: return visitEachChild(node, fallbackVisitor, context); } @@ -95516,64 +87260,40 @@ ${lanes.join("\n")} switch (node.kind) { case 224 /* PrefixUnaryExpression */: case 225 /* PostfixUnaryExpression */: - return visitPreOrPostfixUnaryExpression( - node, - /*discarded*/ - true - ); + return visitPreOrPostfixUnaryExpression(node, /*discarded*/ + true); case 226 /* BinaryExpression */: - return visitBinaryExpression( - node, - /*discarded*/ - true - ); + return visitBinaryExpression(node, /*discarded*/ + true); case 361 /* CommaListExpression */: - return visitCommaListExpression( - node, - /*discarded*/ - true - ); + return visitCommaListExpression(node, /*discarded*/ + true); case 217 /* ParenthesizedExpression */: - return visitParenthesizedExpression( - node, - /*discarded*/ - true - ); + return visitParenthesizedExpression(node, /*discarded*/ + true); default: return visitor(node); } } 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) { return factory2.createUniqueName(`${getHelperVariableName(node)}_${suffix}`, 16 /* Optimistic */ | 8 /* ReservedInNestedScopes */); } + function createLet(name, initializer) { - return factory2.createVariableStatement( - /*modifiers*/ - void 0, - factory2.createVariableDeclarationList([ - factory2.createVariableDeclaration( - name, - /*exclamationToken*/ - void 0, - /*type*/ - void 0, - initializer - ) - ], 1 /* Let */) - ); + return factory2.createVariableStatement( /*modifiers*/ + void 0, factory2.createVariableDeclarationList([factory2.createVariableDeclaration(name, /*exclamationToken*/ + void 0, /*type*/ + void 0, initializer)], 1 /* Let */)); } + function createClassInfo(node) { const metadataReference = factory2.createUniqueName("_metadata", 16 /* Optimistic */ | 32 /* FileLevel */); let instanceExtraInitializersName; @@ -95582,18 +87302,17 @@ ${lanes.join("\n")} let hasNonAmbientInstanceFields = false; let hasStaticPrivateClassElements = false; for (const member of node.members) { - if (isNamedClassElement(member) && nodeOrChildIsDecorated( - /*useLegacyDecorators*/ - false, - member, - node - )) { + if (isNamedClassElement(member) && nodeOrChildIsDecorated( /*useLegacyDecorators*/ + false, member, node)) { if (hasStaticModifier(member)) { - staticExtraInitializersName ?? (staticExtraInitializersName = factory2.createUniqueName("_staticExtraInitializers", 16 /* Optimistic */ | 32 /* FileLevel */)); + var _staticExtraInitializ; + (_staticExtraInitializ = staticExtraInitializersName) !== null && _staticExtraInitializ !== void 0 ? _staticExtraInitializ : staticExtraInitializersName = factory2.createUniqueName("_staticExtraInitializers", 16 /* Optimistic */ | 32 /* FileLevel */); } else { - instanceExtraInitializersName ?? (instanceExtraInitializersName = factory2.createUniqueName("_instanceExtraInitializers", 16 /* Optimistic */ | 32 /* FileLevel */)); + var _instanceExtraInitial; + (_instanceExtraInitial = instanceExtraInitializersName) !== null && _instanceExtraInitial !== void 0 ? _instanceExtraInitial : instanceExtraInitializersName = factory2.createUniqueName("_instanceExtraInitializers", 16 /* Optimistic */ | 32 /* FileLevel */); } } + if (isClassStaticBlockDeclaration(member)) { if (!isClassNamedEvaluationHelperBlock(member)) { hasStaticInitializers = true; @@ -95623,23 +87342,16 @@ ${lanes.join("\n")} }; } function transformClassLike(node) { + var _classInfo2$classThis; startLexicalEnvironment(); - if (!classHasDeclaredOrExplicitlyAssignedName(node) && classOrConstructorParameterIsDecorated( - /*useLegacyDecorators*/ - false, - node - )) { + if (!classHasDeclaredOrExplicitlyAssignedName(node) && classOrConstructorParameterIsDecorated( /*useLegacyDecorators*/ + false, node)) { node = injectClassNamedEvaluationHelperBlockIfMissing(context, node, factory2.createStringLiteral("")); } - const classReference = factory2.getLocalName( - node, - /*allowComments*/ - false, - /*allowSourceMaps*/ - false, - /*ignoreAssignedName*/ - true - ); + const classReference = factory2.getLocalName(node, /*allowComments*/ + false, /*allowSourceMaps*/ + false, /*ignoreAssignedName*/ + true); const classInfo2 = createClassInfo(node); const classDefinitionStatements = []; let leadingBlockStatements; @@ -95652,17 +87364,10 @@ ${lanes.join("\n")} classInfo2.classDecoratorsName = factory2.createUniqueName("_classDecorators", 16 /* Optimistic */ | 32 /* FileLevel */); classInfo2.classDescriptorName = factory2.createUniqueName("_classDescriptor", 16 /* Optimistic */ | 32 /* FileLevel */); classInfo2.classExtraInitializersName = factory2.createUniqueName("_classExtraInitializers", 16 /* Optimistic */ | 32 /* FileLevel */); - const needsUniqueClassThis = some(node.members, (member) => (isPrivateIdentifierClassElementDeclaration(member) || isAutoAccessorPropertyDeclaration(member)) && hasStaticModifier(member)); - classInfo2.classThis = factory2.createUniqueName( - "_classThis", - needsUniqueClassThis ? 16 /* Optimistic */ | 8 /* ReservedInNestedScopes */ : 16 /* Optimistic */ | 32 /* FileLevel */ - ); - classDefinitionStatements.push( - createLet(classInfo2.classDecoratorsName, factory2.createArrayLiteralExpression(classDecorators)), - createLet(classInfo2.classDescriptorName), - createLet(classInfo2.classExtraInitializersName, factory2.createArrayLiteralExpression()), - createLet(classInfo2.classThis) - ); + const needsUniqueClassThis = some(node.members, member => (isPrivateIdentifierClassElementDeclaration(member) || isAutoAccessorPropertyDeclaration(member)) && hasStaticModifier(member)); + classInfo2.classThis = factory2.createUniqueName("_classThis", needsUniqueClassThis ? 16 /* Optimistic */ | 8 /* ReservedInNestedScopes */ : 16 /* Optimistic */ | 32 /* FileLevel */); + + classDefinitionStatements.push(createLet(classInfo2.classDecoratorsName, factory2.createArrayLiteralExpression(classDecorators)), createLet(classInfo2.classDescriptorName), createLet(classInfo2.classExtraInitializersName, factory2.createArrayLiteralExpression()), createLet(classInfo2.classThis)); if (classInfo2.hasStaticPrivateClassElements) { shouldTransformPrivateStaticElementsInClass = true; shouldTransformPrivateStaticElementsInFile = true; @@ -95676,16 +87381,12 @@ ${lanes.join("\n")} const unwrapped = skipOuterExpressions(extendsExpression); const safeExtendsExpression = isClassExpression(unwrapped) && !unwrapped.name || isFunctionExpression(unwrapped) && !unwrapped.name || isArrowFunction(unwrapped) ? factory2.createComma(factory2.createNumericLiteral(0), extendsExpression) : extendsExpression; classDefinitionStatements.push(createLet(classInfo2.classSuper, safeExtendsExpression)); - const updatedExtendsElement = factory2.updateExpressionWithTypeArguments( - extendsElement, - classInfo2.classSuper, - /*typeArguments*/ - void 0 - ); + const updatedExtendsElement = factory2.updateExpressionWithTypeArguments(extendsElement, classInfo2.classSuper, /*typeArguments*/ + void 0); const updatedExtendsClause = factory2.updateHeritageClause(extendsClause, [updatedExtendsElement]); heritageClauses = factory2.createNodeArray([updatedExtendsClause]); } - const renamedClassThis = classInfo2.classThis ?? factory2.createThis(); + const renamedClassThis = (_classInfo2$classThis = classInfo2.classThis) !== null && _classInfo2$classThis !== void 0 ? _classInfo2$classThis : factory2.createThis(); enterClass(classInfo2); leadingBlockStatements = append(leadingBlockStatements, createMetadata(classInfo2.metadataReference, classInfo2.classSuper)); let members = visitNodes2(node.members, classElementVisitor, isClassElement); @@ -95721,37 +87422,22 @@ ${lanes.join("\n")} const constructorStatements = []; if (isDerivedClass) { const spreadArguments = factory2.createSpreadElement(factory2.createIdentifier("arguments")); - const superCall = factory2.createCallExpression( - factory2.createSuper(), - /*typeArguments*/ - void 0, - [spreadArguments] - ); + const superCall = factory2.createCallExpression(factory2.createSuper(), /*typeArguments*/ + void 0, [spreadArguments]); constructorStatements.push(factory2.createExpressionStatement(superCall)); } addRange(constructorStatements, initializerStatements); - const constructorBody = factory2.createBlock( - constructorStatements, - /*multiLine*/ - true - ); - syntheticConstructor = factory2.createConstructorDeclaration( - /*modifiers*/ - void 0, - [], - constructorBody - ); + const constructorBody = factory2.createBlock(constructorStatements, /*multiLine*/ + true); + syntheticConstructor = factory2.createConstructorDeclaration( /*modifiers*/ + void 0, [], constructorBody); } } if (classInfo2.staticExtraInitializersName) { - classDefinitionStatements.push( - createLet(classInfo2.staticExtraInitializersName, factory2.createArrayLiteralExpression()) - ); + classDefinitionStatements.push(createLet(classInfo2.staticExtraInitializersName, factory2.createArrayLiteralExpression())); } if (classInfo2.instanceExtraInitializersName) { - classDefinitionStatements.push( - createLet(classInfo2.instanceExtraInitializersName, factory2.createArrayLiteralExpression()) - ); + classDefinitionStatements.push(createLet(classInfo2.instanceExtraInitializersName, factory2.createArrayLiteralExpression())); } if (classInfo2.memberInfos) { forEachEntry(classInfo2.memberInfos, (memberInfo, member) => { @@ -95784,19 +87470,17 @@ ${lanes.join("\n")} leadingBlockStatements = addRange(leadingBlockStatements, classInfo2.staticFieldDecorationStatements); leadingBlockStatements = addRange(leadingBlockStatements, classInfo2.nonStaticFieldDecorationStatements); if (classInfo2.classDescriptorName && classInfo2.classDecoratorsName && classInfo2.classExtraInitializersName && classInfo2.classThis) { - leadingBlockStatements ?? (leadingBlockStatements = []); + var _leadingBlockStatemen; + (_leadingBlockStatemen = leadingBlockStatements) !== null && _leadingBlockStatemen !== void 0 ? _leadingBlockStatemen : leadingBlockStatements = []; const valueProperty = factory2.createPropertyAssignment("value", renamedClassThis); const classDescriptor = factory2.createObjectLiteralExpression([valueProperty]); const classDescriptorAssignment = factory2.createAssignment(classInfo2.classDescriptorName, classDescriptor); const classNameReference = factory2.createPropertyAccessExpression(renamedClassThis, "name"); - const esDecorateHelper2 = emitHelpers().createESDecorateHelper( - factory2.createNull(), - classDescriptorAssignment, - classInfo2.classDecoratorsName, - { kind: "class", name: classNameReference, metadata: classInfo2.metadataReference }, - factory2.createNull(), - classInfo2.classExtraInitializersName - ); + const esDecorateHelper2 = emitHelpers().createESDecorateHelper(factory2.createNull(), classDescriptorAssignment, classInfo2.classDecoratorsName, { + kind: "class", + name: classNameReference, + metadata: classInfo2.metadataReference + }, factory2.createNull(), classInfo2.classExtraInitializersName); const esDecorateStatement = factory2.createExpressionStatement(esDecorateHelper2); setSourceMapRange(esDecorateStatement, moveRangePastDecorators(node)); leadingBlockStatements.push(esDecorateStatement); @@ -95807,34 +87491,31 @@ ${lanes.join("\n")} } leadingBlockStatements.push(createSymbolMetadata(renamedClassThis, classInfo2.metadataReference)); if (classInfo2.staticExtraInitializersName) { + var _node$name2; const runStaticInitializersHelper = emitHelpers().createRunInitializersHelper(renamedClassThis, classInfo2.staticExtraInitializersName); const runStaticInitializersStatement = factory2.createExpressionStatement(runStaticInitializersHelper); - setSourceMapRange(runStaticInitializersStatement, node.name ?? moveRangePastDecorators(node)); + setSourceMapRange(runStaticInitializersStatement, (_node$name2 = node.name) !== null && _node$name2 !== void 0 ? _node$name2 : moveRangePastDecorators(node)); leadingBlockStatements = append(leadingBlockStatements, runStaticInitializersStatement); } if (classInfo2.classExtraInitializersName) { + var _node$name3; const runClassInitializersHelper = emitHelpers().createRunInitializersHelper(renamedClassThis, classInfo2.classExtraInitializersName); const runClassInitializersStatement = factory2.createExpressionStatement(runClassInitializersHelper); - setSourceMapRange(runClassInitializersStatement, node.name ?? moveRangePastDecorators(node)); + setSourceMapRange(runClassInitializersStatement, (_node$name3 = node.name) !== null && _node$name3 !== void 0 ? _node$name3 : moveRangePastDecorators(node)); trailingBlockStatements = append(trailingBlockStatements, runClassInitializersStatement); } if (leadingBlockStatements && trailingBlockStatements && !classInfo2.hasStaticInitializers) { addRange(leadingBlockStatements, trailingBlockStatements); trailingBlockStatements = void 0; } - const leadingStaticBlock = leadingBlockStatements && factory2.createClassStaticBlockDeclaration(factory2.createBlock( - leadingBlockStatements, - /*multiLine*/ - true - )); + const leadingStaticBlock = leadingBlockStatements && factory2.createClassStaticBlockDeclaration(factory2.createBlock(leadingBlockStatements, /*multiLine*/ + true)); if (leadingStaticBlock && shouldTransformPrivateStaticElementsInClass) { setInternalEmitFlags(leadingStaticBlock, 32 /* TransformPrivateStaticElements */); } - const trailingStaticBlock = trailingBlockStatements && factory2.createClassStaticBlockDeclaration(factory2.createBlock( - trailingBlockStatements, - /*multiLine*/ - true - )); + + const trailingStaticBlock = trailingBlockStatements && factory2.createClassStaticBlockDeclaration(factory2.createBlock(trailingBlockStatements, /*multiLine*/ + true)); if (leadingStaticBlock || syntheticConstructor || trailingStaticBlock) { const newMembers = []; const existingNamedEvaluationHelperBlockIndex = members.findIndex(isClassNamedEvaluationHelperBlock); @@ -95856,47 +87537,24 @@ ${lanes.join("\n")} const lexicalEnvironment = endLexicalEnvironment(); let classExpression; if (classDecorators) { - classExpression = factory2.createClassExpression( - /*modifiers*/ - void 0, - /*name*/ - void 0, - /*typeParameters*/ - void 0, - heritageClauses, - members - ); + classExpression = factory2.createClassExpression( /*modifiers*/ + void 0, /*name*/ + void 0, /*typeParameters*/ + void 0, heritageClauses, members); if (classInfo2.classThis) { classExpression = injectClassThisAssignmentIfMissing(factory2, classExpression, classInfo2.classThis); } - const classReferenceDeclaration = factory2.createVariableDeclaration( - classReference, - /*exclamationToken*/ - void 0, - /*type*/ - void 0, - classExpression - ); + const classReferenceDeclaration = factory2.createVariableDeclaration(classReference, /*exclamationToken*/ + void 0, /*type*/ + void 0, classExpression); const classReferenceVarDeclList = factory2.createVariableDeclarationList([classReferenceDeclaration]); const returnExpr = classInfo2.classThis ? factory2.createAssignment(classReference, classInfo2.classThis) : classReference; - classDefinitionStatements.push( - factory2.createVariableStatement( - /*modifiers*/ - void 0, - classReferenceVarDeclList - ), - factory2.createReturnStatement(returnExpr) - ); + classDefinitionStatements.push(factory2.createVariableStatement( /*modifiers*/ + void 0, classReferenceVarDeclList), factory2.createReturnStatement(returnExpr)); } else { - classExpression = factory2.createClassExpression( - /*modifiers*/ - void 0, - node.name, - /*typeParameters*/ - void 0, - heritageClauses, - members - ); + classExpression = factory2.createClassExpression( /*modifiers*/ + void 0, node.name, /*typeParameters*/ + void 0, heritageClauses, members); classDefinitionStatements.push(factory2.createReturnStatement(classExpression)); } if (shouldTransformPrivateStaticElementsInClass) { @@ -95907,24 +87565,20 @@ ${lanes.join("\n")} } } } + setOriginalNode(classExpression, node); return factory2.createImmediatelyInvokedArrowFunction(factory2.mergeLexicalEnvironment(classDefinitionStatements, lexicalEnvironment)); } function isDecoratedClassLike(node) { - return classOrConstructorParameterIsDecorated( - /*useLegacyDecorators*/ - false, - node - ) || childIsDecorated( - /*useLegacyDecorators*/ - false, - node - ); + return classOrConstructorParameterIsDecorated( /*useLegacyDecorators*/ + false, node) || childIsDecorated( /*useLegacyDecorators*/ + false, node); } function visitClassDeclaration(node) { if (isDecoratedClassLike(node)) { + var _getOriginalNode; const statements = []; - const originalClass = getOriginalNode(node, isClassLike) ?? node; + const originalClass = (_getOriginalNode = getOriginalNode(node, isClassLike)) !== null && _getOriginalNode !== void 0 ? _getOriginalNode : node; const className = originalClass.name ? factory2.createStringLiteralFromNode(originalClass.name) : factory2.createStringLiteral("default"); const isExport = hasSyntacticModifier(node, 32 /* Export */); const isDefault = hasSyntacticModifier(node, 2048 /* Default */); @@ -95934,21 +87588,13 @@ ${lanes.join("\n")} if (isExport && isDefault) { const iife = transformClassLike(node); if (node.name) { - const varDecl = factory2.createVariableDeclaration( - factory2.getLocalName(node), - /*exclamationToken*/ - void 0, - /*type*/ - void 0, - iife - ); + const varDecl = factory2.createVariableDeclaration(factory2.getLocalName(node), /*exclamationToken*/ + void 0, /*type*/ + void 0, iife); setOriginalNode(varDecl, node); const varDecls = factory2.createVariableDeclarationList([varDecl], 1 /* Let */); - const varStatement = factory2.createVariableStatement( - /*modifiers*/ - void 0, - varDecls - ); + const varStatement = factory2.createVariableStatement( /*modifiers*/ + void 0, varDecls); statements.push(varStatement); const exportStatement = factory2.createExportDefault(factory2.getDeclarationName(node)); setOriginalNode(exportStatement, node); @@ -95965,23 +87611,14 @@ ${lanes.join("\n")} } else { Debug.assertIsDefined(node.name, "A class declaration that is not a default export must have a name."); const iife = transformClassLike(node); - const modifierVisitorNoExport = isExport ? (node2) => isExportModifier(node2) ? void 0 : modifierVisitor(node2) : modifierVisitor; + const modifierVisitorNoExport = isExport ? node2 => isExportModifier(node2) ? void 0 : modifierVisitor(node2) : modifierVisitor; const modifiers = visitNodes2(node.modifiers, modifierVisitorNoExport, isModifier); - const declName = factory2.getLocalName( - node, - /*allowComments*/ - false, - /*allowSourceMaps*/ - true - ); - const varDecl = factory2.createVariableDeclaration( - declName, - /*exclamationToken*/ - void 0, - /*type*/ - void 0, - iife - ); + const declName = factory2.getLocalName(node, /*allowComments*/ + false, /*allowSourceMaps*/ + true); + const varDecl = factory2.createVariableDeclaration(declName, /*exclamationToken*/ + void 0, /*type*/ + void 0, iife); setOriginalNode(varDecl, node); const varDecls = factory2.createVariableDeclarationList([varDecl], 1 /* Let */); const varStatement = factory2.createVariableStatement(modifiers, varDecls); @@ -95998,21 +87635,12 @@ ${lanes.join("\n")} } else { const modifiers = visitNodes2(node.modifiers, modifierVisitor, isModifier); const heritageClauses = visitNodes2(node.heritageClauses, visitor, isHeritageClause); - enterClass( - /*classInfo*/ - void 0 - ); + enterClass( /*classInfo*/ + void 0); const members = visitNodes2(node.members, classElementVisitor, isClassElement); exitClass(); - return factory2.updateClassDeclaration( - node, - modifiers, - node.name, - /*typeParameters*/ - void 0, - heritageClauses, - members - ); + return factory2.updateClassDeclaration(node, modifiers, node.name, /*typeParameters*/ + void 0, heritageClauses, members); } } function visitClassExpression(node) { @@ -96023,34 +87651,18 @@ ${lanes.join("\n")} } else { const modifiers = visitNodes2(node.modifiers, modifierVisitor, isModifier); const heritageClauses = visitNodes2(node.heritageClauses, visitor, isHeritageClause); - enterClass( - /*classInfo*/ - void 0 - ); + enterClass( /*classInfo*/ + void 0); const members = visitNodes2(node.members, classElementVisitor, isClassElement); exitClass(); - return factory2.updateClassExpression( - node, - modifiers, - node.name, - /*typeParameters*/ - void 0, - heritageClauses, - members - ); + return factory2.updateClassExpression(node, modifiers, node.name, /*typeParameters*/ + void 0, heritageClauses, members); } } function prepareConstructor(_parent, classInfo2) { if (classInfo2.instanceExtraInitializersName && !classInfo2.hasNonAmbientInstanceFields) { const statements = []; - statements.push( - factory2.createExpressionStatement( - emitHelpers().createRunInitializersHelper( - factory2.createThis(), - classInfo2.instanceExtraInitializersName - ) - ) - ); + statements.push(factory2.createExpressionStatement(emitHelpers().createRunInitializersHelper(factory2.createThis(), classInfo2.instanceExtraInitializersName))); return statements; } } @@ -96060,23 +87672,11 @@ ${lanes.join("\n")} addRange(statementsOut, visitNodes2(statementsIn, visitor, isStatement, statementOffset, superStatementIndex - statementOffset)); if (isTryStatement(superStatement)) { const tryBlockStatements = []; - transformConstructorBodyWorker( - tryBlockStatements, - superStatement.tryBlock.statements, - /*statementOffset*/ - 0, - superPath, - superPathDepth + 1, - initializerStatements - ); + transformConstructorBodyWorker(tryBlockStatements, superStatement.tryBlock.statements, /*statementOffset*/ + 0, superPath, superPathDepth + 1, initializerStatements); const tryBlockStatementsArray = factory2.createNodeArray(tryBlockStatements); setTextRange(tryBlockStatementsArray, superStatement.tryBlock.statements); - statementsOut.push(factory2.updateTryStatement( - superStatement, - factory2.updateBlock(superStatement.tryBlock, tryBlockStatements), - visitNode(superStatement.catchClause, visitor, isCatchClause), - visitNode(superStatement.finallyBlock, visitor, isBlock) - )); + statementsOut.push(factory2.updateTryStatement(superStatement, factory2.updateBlock(superStatement.tryBlock, tryBlockStatements), visitNode(superStatement.catchClause, visitor, isCatchClause), visitNode(superStatement.finallyBlock, visitor, isBlock))); } else { addRange(statementsOut, visitNodes2(statementsIn, visitor, isStatement, superStatementIndex, 1)); addRange(statementsOut, initializerStatements); @@ -96084,6 +87684,7 @@ ${lanes.join("\n")} addRange(statementsOut, visitNodes2(statementsIn, visitor, isStatement, superStatementIndex + 1)); } function visitConstructorDeclaration(node) { + var _body; enterClassElement(node); const modifiers = visitNodes2(node.modifiers, modifierVisitor, isModifier); const parameters = visitNodes2(node.parameters, visitor, isParameter); @@ -96092,13 +87693,8 @@ ${lanes.join("\n")} const initializerStatements = prepareConstructor(classInfo.class, classInfo); if (initializerStatements) { const statements = []; - const nonPrologueStart = factory2.copyPrologue( - node.body.statements, - statements, - /*ensureUseStrict*/ - false, - visitor - ); + const nonPrologueStart = factory2.copyPrologue(node.body.statements, statements, /*ensureUseStrict*/ + false, visitor); const superStatementIndices = findSuperStatementIndexPath(node.body.statements, nonPrologueStart); if (superStatementIndices.length > 0) { transformConstructorBodyWorker(statements, node.body.statements, nonPrologueStart, superStatementIndices, 0, initializerStatements); @@ -96106,16 +87702,13 @@ ${lanes.join("\n")} addRange(statements, initializerStatements); addRange(statements, visitNodes2(node.body.statements, visitor, isStatement)); } - body = factory2.createBlock( - statements, - /*multiLine*/ - true - ); + body = factory2.createBlock(statements, /*multiLine*/ + true); setOriginalNode(body, node.body); setTextRange(body, node.body); } } - body ?? (body = visitNode(node.body, visitor, isBlock)); + (_body = body) !== null && _body !== void 0 ? _body : body = visitNode(node.body, visitor, isBlock); exitClassElement(); return factory2.updateConstructorDeclaration(node, modifiers, parameters, body); } @@ -96137,39 +87730,60 @@ ${lanes.join("\n")} enterName(); name = visitPropertyName(member.name); exitName(); - return { modifiers: modifiers2, referencedName, name, initializersName, descriptorName, thisArg }; + return { + modifiers: modifiers2, + referencedName, + name, + initializersName, + descriptorName, + thisArg + }; } - const memberDecorators = transformAllDecoratorsOfDeclaration(getAllDecoratorsOfClassElement( - member, - classInfo2.class, - /*useLegacyDecorators*/ - false - )); + const memberDecorators = transformAllDecoratorsOfDeclaration(getAllDecoratorsOfClassElement(member, classInfo2.class, /*useLegacyDecorators*/ + false)); const modifiers = visitNodes2(member.modifiers, modifierVisitor, isModifier); if (memberDecorators) { + var _classInfo2$memberInf, _pendingExpressions2, _classInfo2$staticNon, _classInfo2$nonStatic, _classInfo2$staticFie, _classInfo2$nonStatic2, _classInfo2$staticExt, _classInfo2$instanceE; const memberDecoratorsName = createHelperVariable(member, "decorators"); const memberDecoratorsArray = factory2.createArrayLiteralExpression(memberDecorators); const memberDecoratorsAssignment = factory2.createAssignment(memberDecoratorsName, memberDecoratorsArray); - const memberInfo = { memberDecoratorsName }; - classInfo2.memberInfos ?? (classInfo2.memberInfos = /* @__PURE__ */ new Map()); + const memberInfo = { + memberDecoratorsName + }; + (_classInfo2$memberInf = classInfo2.memberInfos) !== null && _classInfo2$memberInf !== void 0 ? _classInfo2$memberInf : classInfo2.memberInfos = /* @__PURE__ */new Map(); classInfo2.memberInfos.set(member, memberInfo); - pendingExpressions ?? (pendingExpressions = []); + (_pendingExpressions2 = pendingExpressions) !== null && _pendingExpressions2 !== void 0 ? _pendingExpressions2 : pendingExpressions = []; pendingExpressions.push(memberDecoratorsAssignment); - const statements = isMethodOrAccessor(member) || isAutoAccessorPropertyDeclaration(member) ? isStatic(member) ? classInfo2.staticNonFieldDecorationStatements ?? (classInfo2.staticNonFieldDecorationStatements = []) : classInfo2.nonStaticNonFieldDecorationStatements ?? (classInfo2.nonStaticNonFieldDecorationStatements = []) : isPropertyDeclaration(member) && !isAutoAccessorPropertyDeclaration(member) ? isStatic(member) ? classInfo2.staticFieldDecorationStatements ?? (classInfo2.staticFieldDecorationStatements = []) : classInfo2.nonStaticFieldDecorationStatements ?? (classInfo2.nonStaticFieldDecorationStatements = []) : Debug.fail(); + const statements = isMethodOrAccessor(member) || isAutoAccessorPropertyDeclaration(member) ? isStatic(member) ? (_classInfo2$staticNon = classInfo2.staticNonFieldDecorationStatements) !== null && _classInfo2$staticNon !== void 0 ? _classInfo2$staticNon : classInfo2.staticNonFieldDecorationStatements = [] : (_classInfo2$nonStatic = classInfo2.nonStaticNonFieldDecorationStatements) !== null && _classInfo2$nonStatic !== void 0 ? _classInfo2$nonStatic : classInfo2.nonStaticNonFieldDecorationStatements = [] : isPropertyDeclaration(member) && !isAutoAccessorPropertyDeclaration(member) ? isStatic(member) ? (_classInfo2$staticFie = classInfo2.staticFieldDecorationStatements) !== null && _classInfo2$staticFie !== void 0 ? _classInfo2$staticFie : classInfo2.staticFieldDecorationStatements = [] : (_classInfo2$nonStatic2 = classInfo2.nonStaticFieldDecorationStatements) !== null && _classInfo2$nonStatic2 !== void 0 ? _classInfo2$nonStatic2 : classInfo2.nonStaticFieldDecorationStatements = [] : Debug.fail(); const kind = isGetAccessorDeclaration(member) ? "getter" : isSetAccessorDeclaration(member) ? "setter" : isMethodDeclaration(member) ? "method" : isAutoAccessorPropertyDeclaration(member) ? "accessor" : isPropertyDeclaration(member) ? "field" : Debug.fail(); let propertyName; if (isIdentifier(member.name) || isPrivateIdentifier(member.name)) { - propertyName = { computed: false, name: member.name }; + propertyName = { + computed: false, + name: member.name + }; } else if (isPropertyNameLiteral(member.name)) { - propertyName = { computed: true, name: factory2.createStringLiteralFromNode(member.name) }; + propertyName = { + computed: true, + name: factory2.createStringLiteralFromNode(member.name) + }; } else { const expression = member.name.expression; if (isPropertyNameLiteral(expression) && !isIdentifier(expression)) { - propertyName = { computed: true, name: factory2.createStringLiteralFromNode(expression) }; + propertyName = { + computed: true, + name: factory2.createStringLiteralFromNode(expression) + }; } else { enterName(); - ({ referencedName, name } = visitReferencedPropertyName(member.name)); - propertyName = { computed: true, name: referencedName }; + ({ + referencedName, + name + } = visitReferencedPropertyName(member.name)); + propertyName = { + computed: true, + name: referencedName + }; exitName(); } } @@ -96187,41 +87801,33 @@ ${lanes.join("\n")} }, metadata: classInfo2.metadataReference }; - const extraInitializers = isStatic(member) ? classInfo2.staticExtraInitializersName ?? (classInfo2.staticExtraInitializersName = factory2.createUniqueName("_staticExtraInitializers", 16 /* Optimistic */ | 32 /* FileLevel */)) : classInfo2.instanceExtraInitializersName ?? (classInfo2.instanceExtraInitializersName = factory2.createUniqueName("_instanceExtraInitializers", 16 /* Optimistic */ | 32 /* FileLevel */)); + const extraInitializers = isStatic(member) ? (_classInfo2$staticExt = classInfo2.staticExtraInitializersName) !== null && _classInfo2$staticExt !== void 0 ? _classInfo2$staticExt : classInfo2.staticExtraInitializersName = factory2.createUniqueName("_staticExtraInitializers", 16 /* Optimistic */ | 32 /* FileLevel */) : (_classInfo2$instanceE = classInfo2.instanceExtraInitializersName) !== null && _classInfo2$instanceE !== void 0 ? _classInfo2$instanceE : classInfo2.instanceExtraInitializersName = factory2.createUniqueName("_instanceExtraInitializers", 16 /* Optimistic */ | 32 /* FileLevel */); if (isMethodOrAccessor(member)) { + var _descriptor; let descriptor; if (isPrivateIdentifierClassElementDeclaration(member) && createDescriptor) { - descriptor = createDescriptor(member, visitNodes2(modifiers, (node) => tryCast(node, isAsyncModifier), isModifier)); + descriptor = createDescriptor(member, visitNodes2(modifiers, node => tryCast(node, isAsyncModifier), isModifier)); memberInfo.memberDescriptorName = descriptorName = createHelperVariable(member, "descriptor"); descriptor = factory2.createAssignment(descriptorName, descriptor); } - const esDecorateExpression = emitHelpers().createESDecorateHelper(factory2.createThis(), descriptor ?? factory2.createNull(), memberDecoratorsName, context2, factory2.createNull(), extraInitializers); + const esDecorateExpression = emitHelpers().createESDecorateHelper(factory2.createThis(), (_descriptor = descriptor) !== null && _descriptor !== void 0 ? _descriptor : factory2.createNull(), memberDecoratorsName, context2, factory2.createNull(), extraInitializers); const esDecorateStatement = factory2.createExpressionStatement(esDecorateExpression); setSourceMapRange(esDecorateStatement, moveRangePastDecorators(member)); statements.push(esDecorateStatement); } else if (isPropertyDeclaration(member)) { - initializersName = memberInfo.memberInitializersName ?? (memberInfo.memberInitializersName = createHelperVariable(member, "initializers")); + var _memberInfo$memberIni, _descriptor2; + initializersName = (_memberInfo$memberIni = memberInfo.memberInitializersName) !== null && _memberInfo$memberIni !== void 0 ? _memberInfo$memberIni : memberInfo.memberInitializersName = createHelperVariable(member, "initializers"); if (isStatic(member)) { thisArg = classInfo2.classThis; } let descriptor; if (isPrivateIdentifierClassElementDeclaration(member) && hasAccessorModifier(member) && createDescriptor) { - descriptor = createDescriptor( - member, - /*modifiers*/ - void 0 - ); + descriptor = createDescriptor(member, /*modifiers*/ + void 0); memberInfo.memberDescriptorName = descriptorName = createHelperVariable(member, "descriptor"); descriptor = factory2.createAssignment(descriptorName, descriptor); } - const esDecorateExpression = emitHelpers().createESDecorateHelper( - isAutoAccessorPropertyDeclaration(member) ? factory2.createThis() : factory2.createNull(), - descriptor ?? factory2.createNull(), - memberDecoratorsName, - context2, - initializersName, - extraInitializers - ); + const esDecorateExpression = emitHelpers().createESDecorateHelper(isAutoAccessorPropertyDeclaration(member) ? factory2.createThis() : factory2.createNull(), (_descriptor2 = descriptor) !== null && _descriptor2 !== void 0 ? _descriptor2 : factory2.createNull(), memberDecoratorsName, context2, initializersName, extraInitializers); const esDecorateStatement = factory2.createExpressionStatement(esDecorateExpression); setSourceMapRange(esDecorateStatement, moveRangePastDecorators(member)); statements.push(esDecorateStatement); @@ -96235,11 +87841,23 @@ ${lanes.join("\n")} if (!some(modifiers) && (isMethodDeclaration(member) || isPropertyDeclaration(member))) { setEmitFlags(name, 1024 /* NoLeadingComments */); } - return { modifiers, referencedName, name, initializersName, descriptorName, thisArg }; + + return { + modifiers, + referencedName, + name, + initializersName, + descriptorName, + thisArg + }; } function visitMethodDeclaration(node) { enterClassElement(node); - const { modifiers, name, descriptorName } = partialTransformClassElement(node, classInfo, createMethodDescriptorObject); + const { + modifiers, + name, + descriptorName + } = partialTransformClassElement(node, classInfo, createMethodDescriptorObject); if (descriptorName) { exitClassElement(); return finishClassElement(createMethodDescriptorForwarder(modifiers, name, descriptorName), node); @@ -96247,25 +87865,19 @@ ${lanes.join("\n")} const parameters = visitNodes2(node.parameters, visitor, isParameter); const body = visitNode(node.body, visitor, isBlock); exitClassElement(); - return finishClassElement(factory2.updateMethodDeclaration( - node, - modifiers, - node.asteriskToken, - name, - /*questionToken*/ - void 0, - /*typeParameters*/ - void 0, - parameters, - /*type*/ - void 0, - body - ), node); + return finishClassElement(factory2.updateMethodDeclaration(node, modifiers, node.asteriskToken, name, /*questionToken*/ + void 0, /*typeParameters*/ + void 0, parameters, /*type*/ + void 0, body), node); } } function visitGetAccessorDeclaration(node) { enterClassElement(node); - const { modifiers, name, descriptorName } = partialTransformClassElement(node, classInfo, createGetAccessorDescriptorObject); + const { + modifiers, + name, + descriptorName + } = partialTransformClassElement(node, classInfo, createGetAccessorDescriptorObject); if (descriptorName) { exitClassElement(); return finishClassElement(createGetAccessorDescriptorForwarder(modifiers, name, descriptorName), node); @@ -96273,20 +87885,17 @@ ${lanes.join("\n")} const parameters = visitNodes2(node.parameters, visitor, isParameter); const body = visitNode(node.body, visitor, isBlock); exitClassElement(); - return finishClassElement(factory2.updateGetAccessorDeclaration( - node, - modifiers, - name, - parameters, - /*type*/ - void 0, - body - ), node); + return finishClassElement(factory2.updateGetAccessorDeclaration(node, modifiers, name, parameters, /*type*/ + void 0, body), node); } } function visitSetAccessorDeclaration(node) { enterClassElement(node); - const { modifiers, name, descriptorName } = partialTransformClassElement(node, classInfo, createSetAccessorDescriptorObject); + const { + modifiers, + name, + descriptorName + } = partialTransformClassElement(node, classInfo, createSetAccessorDescriptorObject); if (descriptorName) { exitClassElement(); return finishClassElement(createSetAccessorDescriptorForwarder(modifiers, name, descriptorName), node); @@ -96308,8 +87917,7 @@ ${lanes.join("\n")} result = visitEachChild(node, visitor, context); classThis = savedClassThis; } else { - if (classInfo) - classInfo.hasStaticInitializers = true; + if (classInfo) classInfo.hasStaticInitializers = true; result = visitEachChild(node, visitor, context); } exitClassElement(); @@ -96321,36 +87929,31 @@ ${lanes.join("\n")} } enterClassElement(node); Debug.assert(!isAmbientPropertyDeclaration(node), "Not yet implemented."); - const { modifiers, name, initializersName, descriptorName, thisArg } = partialTransformClassElement(node, classInfo, hasAccessorModifier(node) ? createAccessorPropertyDescriptorObject : void 0); + const { + modifiers, + name, + initializersName, + descriptorName, + thisArg + } = partialTransformClassElement(node, classInfo, hasAccessorModifier(node) ? createAccessorPropertyDescriptorObject : void 0); startLexicalEnvironment(); let initializer = visitNode(node.initializer, visitor, isExpression); if (initializersName) { - initializer = emitHelpers().createRunInitializersHelper( - thisArg ?? factory2.createThis(), - initializersName, - initializer ?? factory2.createVoidZero() - ); + var _initializer2; + initializer = emitHelpers().createRunInitializersHelper(thisArg !== null && thisArg !== void 0 ? thisArg : factory2.createThis(), initializersName, (_initializer2 = initializer) !== null && _initializer2 !== void 0 ? _initializer2 : factory2.createVoidZero()); } if (!isStatic(node) && (classInfo == null ? void 0 : classInfo.instanceExtraInitializersName) && !(classInfo == null ? void 0 : classInfo.hasInjectedInstanceInitializers)) { + var _initializer3; classInfo.hasInjectedInstanceInitializers = true; - initializer ?? (initializer = factory2.createVoidZero()); - initializer = factory2.createParenthesizedExpression(factory2.createComma( - emitHelpers().createRunInitializersHelper( - factory2.createThis(), - classInfo.instanceExtraInitializersName - ), - initializer - )); + (_initializer3 = initializer) !== null && _initializer3 !== void 0 ? _initializer3 : initializer = factory2.createVoidZero(); + initializer = factory2.createParenthesizedExpression(factory2.createComma(emitHelpers().createRunInitializersHelper(factory2.createThis(), classInfo.instanceExtraInitializersName), initializer)); } if (isStatic(node) && classInfo && initializer) { classInfo.hasStaticInitializers = true; } const declarations = endLexicalEnvironment(); if (some(declarations)) { - initializer = factory2.createImmediatelyInvokedArrowFunction([ - ...declarations, - factory2.createReturnStatement(initializer) - ]); + initializer = factory2.createImmediatelyInvokedArrowFunction([...declarations, factory2.createReturnStatement(initializer)]); } exitClassElement(); if (hasAccessorModifier(node) && descriptorName) { @@ -96374,7 +87977,7 @@ ${lanes.join("\n")} setterName = factory2.updateComputedPropertyName(name2, temp); } } - const modifiersWithoutAccessor = visitNodes2(modifiers, (node2) => node2.kind !== 129 /* AccessorKeyword */ ? node2 : void 0, isModifier); + const modifiersWithoutAccessor = visitNodes2(modifiers, node2 => node2.kind !== 129 /* AccessorKeyword */ ? node2 : void 0, isModifier); const backingField = createAccessorPropertyBackingField(factory2, node, modifiersWithoutAccessor, initializer); setOriginalNode(backingField, node); setEmitFlags(backingField, 3072 /* NoComments */); @@ -96390,19 +87993,13 @@ ${lanes.join("\n")} setSourceMapRange(setter, sourceMapRange); return [backingField, getter, setter]; } - return finishClassElement(factory2.updatePropertyDeclaration( - node, - modifiers, - name, - /*questionOrExclamationToken*/ - void 0, - /*type*/ - void 0, - initializer - ), node); + return finishClassElement(factory2.updatePropertyDeclaration(node, modifiers, name, /*questionOrExclamationToken*/ + void 0, /*type*/ + void 0, initializer), node); } function visitThisExpression(node) { - return classThis ?? node; + var _classThis; + return (_classThis = classThis) !== null && _classThis !== void 0 ? _classThis : node; } function visitCallExpression(node) { if (isSuperProperty(node.expression) && classThis) { @@ -96422,13 +88019,8 @@ ${lanes.join("\n")} setOriginalNode(boundTag, node); setTextRange(boundTag, node); const template = visitNode(node.template, visitor, isTemplateLiteral); - return factory2.updateTaggedTemplateExpression( - node, - boundTag, - /*typeArguments*/ - void 0, - template - ); + return factory2.updateTaggedTemplateExpression(node, boundTag, /*typeArguments*/ + void 0, template); } return visitEachChild(node, visitor, context); } @@ -96456,24 +88048,17 @@ ${lanes.join("\n")} if (isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)) { node = transformNamedEvaluation(context, node, canIgnoreEmptyStringLiteralInAssignedName(node.initializer)); } - const updated = factory2.updateParameterDeclaration( - node, - /*modifiers*/ - void 0, - node.dotDotDotToken, - visitNode(node.name, visitor, isBindingName), - /*questionToken*/ - void 0, - /*type*/ - void 0, - visitNode(node.initializer, visitor, isExpression) - ); + const updated = factory2.updateParameterDeclaration(node, /*modifiers*/ + void 0, node.dotDotDotToken, visitNode(node.name, visitor, isBindingName), /*questionToken*/ + void 0, /*type*/ + void 0, visitNode(node.initializer, visitor, isExpression)); if (updated !== node) { setCommentRange(updated, node); setTextRange(updated, moveRangePastModifiers(node)); setSourceMapRange(updated, moveRangePastModifiers(node)); setEmitFlags(updated.name, 64 /* NoTrailingSourceMap */); } + return updated; } function isAnonymousClassNeedingAssignedName(node) { @@ -96481,20 +88066,11 @@ ${lanes.join("\n")} } function canIgnoreEmptyStringLiteralInAssignedName(node) { const innerExpression = skipOuterExpressions(node); - return isClassExpression(innerExpression) && !innerExpression.name && !classOrConstructorParameterIsDecorated( - /*useLegacyDecorators*/ - false, - innerExpression - ); + return isClassExpression(innerExpression) && !innerExpression.name && !classOrConstructorParameterIsDecorated( /*useLegacyDecorators*/ + false, innerExpression); } function visitForStatement(node) { - return factory2.updateForStatement( - node, - visitNode(node.initializer, discardedValueVisitor, isForInitializer), - visitNode(node.condition, visitor, isExpression), - visitNode(node.incrementor, discardedValueVisitor, isExpression), - visitIterationBody(node.statement, visitor, context) - ); + return factory2.updateForStatement(node, visitNode(node.initializer, discardedValueVisitor, isForInitializer), visitNode(node.condition, visitor, isExpression), visitNode(node.incrementor, discardedValueVisitor, isExpression), visitIterationBody(node.statement, visitor, context)); } function visitExpressionStatement(node) { return visitEachChild(node, discardedValueVisitor, context); @@ -96520,18 +88096,10 @@ ${lanes.join("\n")} getterName = factory2.createTempVariable(hoistVariableDeclaration); setterName = factory2.createAssignment(getterName, setterName); } - const superPropertyGet = factory2.createReflectGetCall( - classSuper, - getterName, - classThis - ); + const superPropertyGet = factory2.createReflectGetCall(classSuper, getterName, classThis); setOriginalNode(superPropertyGet, node.left); setTextRange(superPropertyGet, node.left); - expression = factory2.createBinaryExpression( - superPropertyGet, - getNonAssignmentOperatorForCompoundAssignment(node.operatorToken.kind), - expression - ); + expression = factory2.createBinaryExpression(superPropertyGet, getNonAssignmentOperatorForCompoundAssignment(node.operatorToken.kind), expression); setTextRange(expression, node); } const temp = discarded ? void 0 : factory2.createTempVariable(hoistVariableDeclaration); @@ -96539,12 +88107,7 @@ ${lanes.join("\n")} expression = factory2.createAssignment(temp, expression); setTextRange(temp, node); } - expression = factory2.createReflectSetCall( - classSuper, - setterName, - expression, - classThis - ); + expression = factory2.createReflectSetCall(classSuper, setterName, expression, classThis); setOriginalNode(expression, node); setTextRange(expression, node); if (temp) { @@ -96599,19 +88162,28 @@ ${lanes.join("\n")} if (isPropertyNameLiteral(node) || isPrivateIdentifier(node)) { const referencedName2 = factory2.createStringLiteralFromNode(node); const name2 = visitNode(node, visitor, isPropertyName); - return { referencedName: referencedName2, name: name2 }; + return { + referencedName: referencedName2, + name: name2 + }; } if (isPropertyNameLiteral(node.expression) && !isIdentifier(node.expression)) { const referencedName2 = factory2.createStringLiteralFromNode(node.expression); const name2 = visitNode(node, visitor, isPropertyName); - return { referencedName: referencedName2, name: name2 }; + return { + referencedName: referencedName2, + name: name2 + }; } const referencedName = factory2.getGeneratedNameForNode(node); hoistVariableDeclaration(referencedName); const key = emitHelpers().createPropKeyHelper(visitNode(node.expression, visitor, isExpression)); const assignment = factory2.createAssignment(referencedName, key); const name = factory2.updateComputedPropertyName(node, injectPendingExpressions(assignment)); - return { referencedName, name }; + return { + referencedName, + name + }; } function visitPropertyName(node) { if (isComputedPropertyName(node)) { @@ -96651,19 +88223,9 @@ ${lanes.join("\n")} if (isSuperProperty(node) && classThis && classSuper) { const propertyName = isElementAccessExpression(node) ? visitNode(node.argumentExpression, visitor, isExpression) : isIdentifier(node.name) ? factory2.createStringLiteralFromNode(node.name) : void 0; if (propertyName) { - const paramName = factory2.createTempVariable( - /*recordTempVariable*/ - void 0 - ); - const expression = factory2.createAssignmentTargetWrapper( - paramName, - factory2.createReflectSetCall( - classSuper, - propertyName, - paramName, - classThis - ) - ); + const paramName = factory2.createTempVariable( /*recordTempVariable*/ + void 0); + const expression = factory2.createAssignmentTargetWrapper(paramName, factory2.createReflectSetCall(classSuper, propertyName, paramName, classThis)); setOriginalNode(expression, node); setTextRange(expression, node); return expression; @@ -96672,11 +88234,8 @@ ${lanes.join("\n")} return visitEachChild(node, visitor, context); } function visitAssignmentElement(node) { - if (isAssignmentExpression( - node, - /*excludeCompoundAssignment*/ - true - )) { + if (isAssignmentExpression(node, /*excludeCompoundAssignment*/ + true)) { if (isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)) { node = transformNamedEvaluation(context, node, canIgnoreEmptyStringLiteralInAssignedName(node.right)); } @@ -96696,19 +88255,14 @@ ${lanes.join("\n")} } 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) { const name = visitNode(node.name, visitor, isPropertyName); - if (isAssignmentExpression( - node.initializer, - /*excludeCompoundAssignment*/ - true - )) { + if (isAssignmentExpression(node.initializer, /*excludeCompoundAssignment*/ + true)) { const assignmentElement = visitAssignmentElement(node.initializer); return factory2.updatePropertyAssignment(node, name, assignmentElement); } @@ -96733,12 +88287,9 @@ ${lanes.join("\n")} } 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) { @@ -96792,39 +88343,26 @@ ${lanes.join("\n")} setEmitFlags(expression, 3072 /* NoComments */); const innerExpression = skipOuterExpressions(expression); if (isAccessExpression(innerExpression)) { - const { target, thisArg } = factory2.createCallBinding( - expression, - hoistVariableDeclaration, - languageVersion, - /*cacheIdentifiers*/ - true - ); + const { + target, + thisArg + } = factory2.createCallBinding(expression, hoistVariableDeclaration, languageVersion, /*cacheIdentifiers*/ + true); return factory2.restoreOuterExpressions(expression, factory2.createFunctionBindCall(target, thisArg, [])); } return expression; } function createDescriptorMethod(original, name, modifiers, asteriskToken, kind, parameters, body) { - const func = factory2.createFunctionExpression( - modifiers, - asteriskToken, - /*name*/ - void 0, - /*typeParameters*/ - void 0, - parameters, - /*type*/ - void 0, - body ?? factory2.createBlock([]) - ); + const func = factory2.createFunctionExpression(modifiers, asteriskToken, /*name*/ + void 0, /*typeParameters*/ + void 0, parameters, /*type*/ + void 0, body !== null && body !== void 0 ? body : factory2.createBlock([])); setOriginalNode(func, original); setSourceMapRange(func, moveRangePastDecorators(original)); setEmitFlags(func, 3072 /* NoComments */); const prefix = kind === "get" || kind === "set" ? kind : void 0; - const functionName = factory2.createStringLiteralFromNode( - name, - /*isSingleQuote*/ - void 0 - ); + const functionName = factory2.createStringLiteralFromNode(name, /*isSingleQuote*/ + void 0); const namedFunction = emitHelpers().createSetFunctionNameHelper(func, functionName, prefix); const method = factory2.createPropertyAssignment(factory2.createIdentifier(kind), namedFunction); setOriginalNode(method, original); @@ -96833,217 +88371,67 @@ ${lanes.join("\n")} return method; } function createMethodDescriptorObject(node, modifiers) { - return factory2.createObjectLiteralExpression([ - createDescriptorMethod( - node, - node.name, - modifiers, - node.asteriskToken, - "value", - visitNodes2(node.parameters, visitor, isParameter), - visitNode(node.body, visitor, isBlock) - ) - ]); + return factory2.createObjectLiteralExpression([createDescriptorMethod(node, node.name, modifiers, node.asteriskToken, "value", visitNodes2(node.parameters, visitor, isParameter), visitNode(node.body, visitor, isBlock))]); } function createGetAccessorDescriptorObject(node, modifiers) { - return factory2.createObjectLiteralExpression([ - createDescriptorMethod( - node, - node.name, - modifiers, - /*asteriskToken*/ - void 0, - "get", - [], - visitNode(node.body, visitor, isBlock) - ) - ]); + return factory2.createObjectLiteralExpression([createDescriptorMethod(node, node.name, modifiers, /*asteriskToken*/ + void 0, "get", [], visitNode(node.body, visitor, isBlock))]); } function createSetAccessorDescriptorObject(node, modifiers) { - return factory2.createObjectLiteralExpression([ - createDescriptorMethod( - node, - node.name, - modifiers, - /*asteriskToken*/ - void 0, - "set", - visitNodes2(node.parameters, visitor, isParameter), - visitNode(node.body, visitor, isBlock) - ) - ]); + return factory2.createObjectLiteralExpression([createDescriptorMethod(node, node.name, modifiers, /*asteriskToken*/ + void 0, "set", visitNodes2(node.parameters, visitor, isParameter), visitNode(node.body, visitor, isBlock))]); } function createAccessorPropertyDescriptorObject(node, modifiers) { - return factory2.createObjectLiteralExpression([ - createDescriptorMethod( - node, - node.name, - modifiers, - /*asteriskToken*/ - void 0, - "get", - [], - factory2.createBlock([ - factory2.createReturnStatement( - factory2.createPropertyAccessExpression( - factory2.createThis(), - factory2.getGeneratedPrivateNameForNode(node.name) - ) - ) - ]) - ), - createDescriptorMethod( - node, - node.name, - modifiers, - /*asteriskToken*/ - void 0, - "set", - [factory2.createParameterDeclaration( - /*modifiers*/ - void 0, - /*dotDotDotToken*/ - void 0, - "value" - )], - factory2.createBlock([ - factory2.createExpressionStatement( - factory2.createAssignment( - factory2.createPropertyAccessExpression( - factory2.createThis(), - factory2.getGeneratedPrivateNameForNode(node.name) - ), - factory2.createIdentifier("value") - ) - ) - ]) - ) - ]); + return factory2.createObjectLiteralExpression([createDescriptorMethod(node, node.name, modifiers, /*asteriskToken*/ + void 0, "get", [], factory2.createBlock([factory2.createReturnStatement(factory2.createPropertyAccessExpression(factory2.createThis(), factory2.getGeneratedPrivateNameForNode(node.name)))])), createDescriptorMethod(node, node.name, modifiers, /*asteriskToken*/ + void 0, "set", [factory2.createParameterDeclaration( /*modifiers*/ + void 0, /*dotDotDotToken*/ + void 0, "value")], factory2.createBlock([factory2.createExpressionStatement(factory2.createAssignment(factory2.createPropertyAccessExpression(factory2.createThis(), factory2.getGeneratedPrivateNameForNode(node.name)), factory2.createIdentifier("value")))]))]); } function createMethodDescriptorForwarder(modifiers, name, descriptorName) { - modifiers = visitNodes2(modifiers, (node) => isStaticModifier(node) ? node : void 0, isModifier); - return factory2.createGetAccessorDeclaration( - modifiers, - name, - [], - /*type*/ - void 0, - factory2.createBlock([ - factory2.createReturnStatement( - factory2.createPropertyAccessExpression( - descriptorName, - factory2.createIdentifier("value") - ) - ) - ]) - ); + modifiers = visitNodes2(modifiers, node => isStaticModifier(node) ? node : void 0, isModifier); + return factory2.createGetAccessorDeclaration(modifiers, name, [], /*type*/ + void 0, factory2.createBlock([factory2.createReturnStatement(factory2.createPropertyAccessExpression(descriptorName, factory2.createIdentifier("value")))])); } function createGetAccessorDescriptorForwarder(modifiers, name, descriptorName) { - modifiers = visitNodes2(modifiers, (node) => isStaticModifier(node) ? node : void 0, isModifier); - return factory2.createGetAccessorDeclaration( - modifiers, - name, - [], - /*type*/ - void 0, - factory2.createBlock([ - factory2.createReturnStatement( - factory2.createFunctionCallCall( - factory2.createPropertyAccessExpression( - descriptorName, - factory2.createIdentifier("get") - ), - factory2.createThis(), - [] - ) - ) - ]) - ); + modifiers = visitNodes2(modifiers, node => isStaticModifier(node) ? node : void 0, isModifier); + return factory2.createGetAccessorDeclaration(modifiers, name, [], /*type*/ + void 0, factory2.createBlock([factory2.createReturnStatement(factory2.createFunctionCallCall(factory2.createPropertyAccessExpression(descriptorName, factory2.createIdentifier("get")), factory2.createThis(), []))])); } function createSetAccessorDescriptorForwarder(modifiers, name, descriptorName) { - modifiers = visitNodes2(modifiers, (node) => isStaticModifier(node) ? node : void 0, isModifier); - return factory2.createSetAccessorDeclaration( - modifiers, - name, - [factory2.createParameterDeclaration( - /*modifiers*/ - void 0, - /*dotDotDotToken*/ - void 0, - "value" - )], - factory2.createBlock([ - factory2.createReturnStatement( - factory2.createFunctionCallCall( - factory2.createPropertyAccessExpression( - descriptorName, - factory2.createIdentifier("set") - ), - factory2.createThis(), - [factory2.createIdentifier("value")] - ) - ) - ]) - ); + modifiers = visitNodes2(modifiers, node => isStaticModifier(node) ? node : void 0, isModifier); + return factory2.createSetAccessorDeclaration(modifiers, name, [factory2.createParameterDeclaration( /*modifiers*/ + void 0, /*dotDotDotToken*/ + void 0, "value")], factory2.createBlock([factory2.createReturnStatement(factory2.createFunctionCallCall(factory2.createPropertyAccessExpression(descriptorName, factory2.createIdentifier("set")), factory2.createThis(), [factory2.createIdentifier("value")]))])); } function createMetadata(name, classSuper2) { - const varDecl = factory2.createVariableDeclaration( - name, - /*exclamationToken*/ - void 0, - /*type*/ - void 0, - factory2.createConditionalExpression( - factory2.createLogicalAnd( - factory2.createTypeCheck(factory2.createIdentifier("Symbol"), "function"), - factory2.createPropertyAccessExpression(factory2.createIdentifier("Symbol"), "metadata") - ), - factory2.createToken(58 /* QuestionToken */), - factory2.createCallExpression( - factory2.createPropertyAccessExpression(factory2.createIdentifier("Object"), "create"), - /*typeArguments*/ - void 0, - [classSuper2 ? createSymbolMetadataReference(classSuper2) : factory2.createNull()] - ), - factory2.createToken(59 /* ColonToken */), - factory2.createVoidZero() - ) - ); - return factory2.createVariableStatement( - /*modifiers*/ - void 0, - factory2.createVariableDeclarationList([varDecl], 2 /* Const */) - ); + const varDecl = factory2.createVariableDeclaration(name, /*exclamationToken*/ + void 0, /*type*/ + void 0, factory2.createConditionalExpression(factory2.createLogicalAnd(factory2.createTypeCheck(factory2.createIdentifier("Symbol"), "function"), factory2.createPropertyAccessExpression(factory2.createIdentifier("Symbol"), "metadata")), factory2.createToken(58 /* QuestionToken */), factory2.createCallExpression(factory2.createPropertyAccessExpression(factory2.createIdentifier("Object"), "create"), /*typeArguments*/ + void 0, [classSuper2 ? createSymbolMetadataReference(classSuper2) : factory2.createNull()]), factory2.createToken(59 /* ColonToken */), factory2.createVoidZero())); + return factory2.createVariableStatement( /*modifiers*/ + void 0, factory2.createVariableDeclarationList([varDecl], 2 /* Const */)); } + function createSymbolMetadata(target, value) { - const defineProperty = factory2.createObjectDefinePropertyCall( - target, - factory2.createPropertyAccessExpression(factory2.createIdentifier("Symbol"), "metadata"), - factory2.createPropertyDescriptor( - { configurable: true, writable: true, enumerable: true, value }, - /*singleLine*/ - true - ) - ); - return setEmitFlags( - factory2.createIfStatement(value, factory2.createExpressionStatement(defineProperty)), - 1 /* SingleLine */ - ); + const defineProperty = factory2.createObjectDefinePropertyCall(target, factory2.createPropertyAccessExpression(factory2.createIdentifier("Symbol"), "metadata"), factory2.createPropertyDescriptor({ + configurable: true, + writable: true, + enumerable: true, + value + }, /*singleLine*/ + true)); + return setEmitFlags(factory2.createIfStatement(value, factory2.createExpressionStatement(defineProperty)), 1 /* SingleLine */); } + function createSymbolMetadataReference(classSuper2) { - return factory2.createBinaryExpression( - factory2.createElementAccessExpression( - classSuper2, - factory2.createPropertyAccessExpression(factory2.createIdentifier("Symbol"), "metadata") - ), - 61 /* QuestionQuestionToken */, - factory2.createNull() - ); + return factory2.createBinaryExpression(factory2.createElementAccessExpression(classSuper2, factory2.createPropertyAccessExpression(factory2.createIdentifier("Symbol"), "metadata")), 61 /* QuestionQuestionToken */, factory2.createNull()); } } var init_esDecorators = __esm({ "src/compiler/transformers/esDecorators.ts"() { "use strict"; + init_ts2(); } }); @@ -97091,23 +88479,19 @@ ${lanes.join("\n")} function inTopLevelContext() { return !inContext(1 /* NonTopLevel */); } + function inHasLexicalThisContext() { return inContext(2 /* HasLexicalThis */); } + function doWithContext(flags, cb, value) { const contextFlagsToSet = flags & ~contextFlags; if (contextFlagsToSet) { - setContextFlag( - contextFlagsToSet, - /*val*/ - true - ); + setContextFlag(contextFlagsToSet, /*val*/ + true); const result = cb(value); - setContextFlag( - contextFlagsToSet, - /*val*/ - false - ); + setContextFlag(contextFlagsToSet, /*val*/ + false); return result; } return cb(value); @@ -97187,7 +88571,7 @@ ${lanes.join("\n")} return visitor(node); } function visitCatchClauseInAsyncBody(node) { - const catchClauseNames = /* @__PURE__ */ new Set(); + const catchClauseNames = /* @__PURE__ */new Set(); recordDeclarationName(node.variableDeclaration, catchClauseNames); let catchClauseUnshadowedNames; catchClauseNames.forEach((_, escapedName) => { @@ -97210,156 +88594,66 @@ ${lanes.join("\n")} } function visitVariableStatementInAsyncBody(node) { if (isVariableDeclarationListWithCollidingName(node.declarationList)) { - const expression = visitVariableDeclarationListWithCollidingNames( - node.declarationList, - /*hasReceiver*/ - false - ); + const expression = visitVariableDeclarationListWithCollidingNames(node.declarationList, /*hasReceiver*/ + false); return expression ? factory2.createExpressionStatement(expression) : void 0; } return visitEachChild(node, visitor, context); } function visitForInStatementInAsyncBody(node) { - return factory2.updateForInStatement( - node, - isVariableDeclarationListWithCollidingName(node.initializer) ? visitVariableDeclarationListWithCollidingNames( - node.initializer, - /*hasReceiver*/ - true - ) : Debug.checkDefined(visitNode(node.initializer, visitor, isForInitializer)), - Debug.checkDefined(visitNode(node.expression, visitor, isExpression)), - visitIterationBody(node.statement, asyncBodyVisitor, context) - ); + return factory2.updateForInStatement(node, isVariableDeclarationListWithCollidingName(node.initializer) ? visitVariableDeclarationListWithCollidingNames(node.initializer, /*hasReceiver*/ + true) : Debug.checkDefined(visitNode(node.initializer, visitor, isForInitializer)), Debug.checkDefined(visitNode(node.expression, visitor, isExpression)), visitIterationBody(node.statement, asyncBodyVisitor, context)); } function visitForOfStatementInAsyncBody(node) { - return factory2.updateForOfStatement( - node, - visitNode(node.awaitModifier, visitor, isAwaitKeyword), - isVariableDeclarationListWithCollidingName(node.initializer) ? visitVariableDeclarationListWithCollidingNames( - node.initializer, - /*hasReceiver*/ - true - ) : Debug.checkDefined(visitNode(node.initializer, visitor, isForInitializer)), - Debug.checkDefined(visitNode(node.expression, visitor, isExpression)), - visitIterationBody(node.statement, asyncBodyVisitor, context) - ); + return factory2.updateForOfStatement(node, visitNode(node.awaitModifier, visitor, isAwaitKeyword), isVariableDeclarationListWithCollidingName(node.initializer) ? visitVariableDeclarationListWithCollidingNames(node.initializer, /*hasReceiver*/ + true) : Debug.checkDefined(visitNode(node.initializer, visitor, isForInitializer)), Debug.checkDefined(visitNode(node.expression, visitor, isExpression)), visitIterationBody(node.statement, asyncBodyVisitor, context)); } function visitForStatementInAsyncBody(node) { const initializer = node.initializer; - return factory2.updateForStatement( - node, - isVariableDeclarationListWithCollidingName(initializer) ? visitVariableDeclarationListWithCollidingNames( - initializer, - /*hasReceiver*/ - false - ) : visitNode(node.initializer, visitor, isForInitializer), - visitNode(node.condition, visitor, isExpression), - visitNode(node.incrementor, visitor, isExpression), - visitIterationBody(node.statement, asyncBodyVisitor, context) - ); + return factory2.updateForStatement(node, isVariableDeclarationListWithCollidingName(initializer) ? visitVariableDeclarationListWithCollidingNames(initializer, /*hasReceiver*/ + false) : visitNode(node.initializer, visitor, isForInitializer), visitNode(node.condition, visitor, isExpression), visitNode(node.incrementor, visitor, isExpression), visitIterationBody(node.statement, asyncBodyVisitor, context)); } function visitAwaitExpression(node) { if (inTopLevelContext()) { return visitEachChild(node, visitor, context); } - return setOriginalNode( - setTextRange( - factory2.createYieldExpression( - /*asteriskToken*/ - void 0, - visitNode(node.expression, visitor, isExpression) - ), - node - ), - node - ); + return setOriginalNode(setTextRange(factory2.createYieldExpression( /*asteriskToken*/ + void 0, visitNode(node.expression, visitor, isExpression)), node), node); } function visitConstructorDeclaration(node) { - return factory2.updateConstructorDeclaration( - node, - visitNodes2(node.modifiers, visitor, isModifier), - visitParameterList(node.parameters, visitor, context), - transformMethodBody(node) - ); + return factory2.updateConstructorDeclaration(node, visitNodes2(node.modifiers, visitor, isModifier), visitParameterList(node.parameters, visitor, context), transformMethodBody(node)); } function visitMethodDeclaration(node) { - return factory2.updateMethodDeclaration( - node, - visitNodes2(node.modifiers, visitor, isModifierLike), - node.asteriskToken, - node.name, - /*questionToken*/ - void 0, - /*typeParameters*/ - void 0, - visitParameterList(node.parameters, visitor, context), - /*type*/ - void 0, - getFunctionFlags(node) & 2 /* Async */ ? transformAsyncFunctionBody(node) : transformMethodBody(node) - ); + return factory2.updateMethodDeclaration(node, visitNodes2(node.modifiers, visitor, isModifierLike), node.asteriskToken, node.name, /*questionToken*/ + void 0, /*typeParameters*/ + void 0, visitParameterList(node.parameters, visitor, context), /*type*/ + void 0, getFunctionFlags(node) & 2 /* Async */ ? transformAsyncFunctionBody(node) : transformMethodBody(node)); } function visitGetAccessorDeclaration(node) { - return factory2.updateGetAccessorDeclaration( - node, - visitNodes2(node.modifiers, visitor, isModifierLike), - node.name, - visitParameterList(node.parameters, visitor, context), - /*type*/ - void 0, - transformMethodBody(node) - ); + return factory2.updateGetAccessorDeclaration(node, visitNodes2(node.modifiers, visitor, isModifierLike), node.name, visitParameterList(node.parameters, visitor, context), /*type*/ + void 0, transformMethodBody(node)); } function visitSetAccessorDeclaration(node) { - return factory2.updateSetAccessorDeclaration( - node, - visitNodes2(node.modifiers, visitor, isModifierLike), - node.name, - visitParameterList(node.parameters, visitor, context), - transformMethodBody(node) - ); + return factory2.updateSetAccessorDeclaration(node, visitNodes2(node.modifiers, visitor, isModifierLike), node.name, visitParameterList(node.parameters, visitor, context), transformMethodBody(node)); } function visitFunctionDeclaration(node) { - return factory2.updateFunctionDeclaration( - node, - visitNodes2(node.modifiers, visitor, isModifierLike), - node.asteriskToken, - node.name, - /*typeParameters*/ - void 0, - visitParameterList(node.parameters, visitor, context), - /*type*/ - void 0, - getFunctionFlags(node) & 2 /* Async */ ? transformAsyncFunctionBody(node) : visitFunctionBody(node.body, visitor, context) - ); + return factory2.updateFunctionDeclaration(node, visitNodes2(node.modifiers, visitor, isModifierLike), node.asteriskToken, node.name, /*typeParameters*/ + void 0, visitParameterList(node.parameters, visitor, context), /*type*/ + void 0, getFunctionFlags(node) & 2 /* Async */ ? transformAsyncFunctionBody(node) : visitFunctionBody(node.body, visitor, context)); } function visitFunctionExpression(node) { - return factory2.updateFunctionExpression( - node, - visitNodes2(node.modifiers, visitor, isModifier), - node.asteriskToken, - node.name, - /*typeParameters*/ - void 0, - visitParameterList(node.parameters, visitor, context), - /*type*/ - void 0, - getFunctionFlags(node) & 2 /* Async */ ? transformAsyncFunctionBody(node) : visitFunctionBody(node.body, visitor, context) - ); + return factory2.updateFunctionExpression(node, visitNodes2(node.modifiers, visitor, isModifier), node.asteriskToken, node.name, /*typeParameters*/ + void 0, visitParameterList(node.parameters, visitor, context), /*type*/ + void 0, getFunctionFlags(node) & 2 /* Async */ ? transformAsyncFunctionBody(node) : visitFunctionBody(node.body, visitor, context)); } function visitArrowFunction(node) { - return factory2.updateArrowFunction( - node, - visitNodes2(node.modifiers, visitor, isModifier), - /*typeParameters*/ - void 0, - visitParameterList(node.parameters, visitor, context), - /*type*/ - void 0, - node.equalsGreaterThanToken, - getFunctionFlags(node) & 2 /* Async */ ? transformAsyncFunctionBody(node) : visitFunctionBody(node.body, visitor, context) - ); + return factory2.updateArrowFunction(node, visitNodes2(node.modifiers, visitor, isModifier), /*typeParameters*/ + void 0, visitParameterList(node.parameters, visitor, context), /*type*/ + void 0, node.equalsGreaterThanToken, getFunctionFlags(node) & 2 /* Async */ ? transformAsyncFunctionBody(node) : visitFunctionBody(node.body, visitor, context)); } - function recordDeclarationName({ name }, names) { + function recordDeclarationName({ + name + }, names) { if (isIdentifier(name)) { names.add(name.escapedText); } else { @@ -97387,7 +88681,9 @@ ${lanes.join("\n")} function hoistVariableDeclarationList(node) { forEach(node.declarations, hoistVariable); } - function hoistVariable({ name }) { + function hoistVariable({ + name + }) { if (isIdentifier(name)) { hoistVariableDeclaration(name); } else { @@ -97399,16 +88695,12 @@ ${lanes.join("\n")} } } function transformInitializedVariable(node) { - const converted = setSourceMapRange( - factory2.createAssignment( - factory2.converters.convertToAssignmentElementTarget(node.name), - node.initializer - ), - node - ); + const converted = setSourceMapRange(factory2.createAssignment(factory2.converters.convertToAssignmentElementTarget(node.name), node.initializer), node); return Debug.checkDefined(visitNode(converted, visitor, isExpression)); } - function collidesWithParameterName({ name }) { + function collidesWithParameterName({ + name + }) { if (isIdentifier(name)) { return enclosingFunctionParameterNames.has(name.escapedText); } else { @@ -97424,7 +88716,7 @@ ${lanes.join("\n")} Debug.assertIsDefined(node.body); const savedCapturedSuperProperties = capturedSuperProperties; const savedHasSuperElementAccess = hasSuperElementAccess; - capturedSuperProperties = /* @__PURE__ */ new Set(); + capturedSuperProperties = /* @__PURE__ */new Set(); hasSuperElementAccess = false; let updated = visitFunctionBody(node.body, visitor, context); const originalMethod = getOriginalNode(node, isFunctionLikeDeclaration); @@ -97458,36 +88750,22 @@ ${lanes.join("\n")} const isArrowFunction2 = node.kind === 219 /* ArrowFunction */; const hasLexicalArguments = (resolver.getNodeCheckFlags(node) & 512 /* CaptureArguments */) !== 0; const savedEnclosingFunctionParameterNames = enclosingFunctionParameterNames; - enclosingFunctionParameterNames = /* @__PURE__ */ new Set(); + enclosingFunctionParameterNames = /* @__PURE__ */new Set(); for (const parameter of node.parameters) { recordDeclarationName(parameter, enclosingFunctionParameterNames); } const savedCapturedSuperProperties = capturedSuperProperties; const savedHasSuperElementAccess = hasSuperElementAccess; if (!isArrowFunction2) { - capturedSuperProperties = /* @__PURE__ */ new Set(); + capturedSuperProperties = /* @__PURE__ */new Set(); hasSuperElementAccess = false; } let result; if (!isArrowFunction2) { const statements = []; - const statementOffset = factory2.copyPrologue( - node.body.statements, - statements, - /*ensureUseStrict*/ - false, - visitor - ); - statements.push( - factory2.createReturnStatement( - emitHelpers().createAwaiterHelper( - inHasLexicalThisContext(), - hasLexicalArguments, - promiseConstructor, - transformAsyncFunctionBodyWorker(node.body, statementOffset) - ) - ) - ); + const statementOffset = factory2.copyPrologue(node.body.statements, statements, /*ensureUseStrict*/ + false, visitor); + statements.push(factory2.createReturnStatement(emitHelpers().createAwaiterHelper(inHasLexicalThisContext(), hasLexicalArguments, promiseConstructor, transformAsyncFunctionBodyWorker(node.body, statementOffset)))); insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment()); const emitSuperHelpers = languageVersion >= 2 /* ES2015 */ && resolver.getNodeCheckFlags(node) & (256 /* MethodWithSuperPropertyAssignmentInAsync */ | 128 /* MethodWithSuperPropertyAccessInAsync */); if (emitSuperHelpers) { @@ -97498,11 +88776,8 @@ ${lanes.join("\n")} insertStatementsAfterStandardPrologue(statements, [variableStatement]); } } - const block = factory2.createBlock( - statements, - /*multiLine*/ - true - ); + const block = factory2.createBlock(statements, /*multiLine*/ + true); setTextRange(block, node.body); if (emitSuperHelpers && hasSuperElementAccess) { if (resolver.getNodeCheckFlags(node) & 256 /* MethodWithSuperPropertyAssignmentInAsync */) { @@ -97513,12 +88788,7 @@ ${lanes.join("\n")} } result = block; } else { - const expression = emitHelpers().createAwaiterHelper( - inHasLexicalThisContext(), - hasLexicalArguments, - promiseConstructor, - transformAsyncFunctionBodyWorker(node.body) - ); + const expression = emitHelpers().createAwaiterHelper(inHasLexicalThisContext(), hasLexicalArguments, promiseConstructor, transformAsyncFunctionBodyWorker(node.body)); const declarations = endLexicalEnvironment(); if (some(declarations)) { const block = factory2.converters.convertToFunctionBlock(expression); @@ -97565,6 +88835,7 @@ ${lanes.join("\n")} context.enableEmitNotification(243 /* VariableStatement */); } } + function onEmitNode(hint, node, emitCallback) { if (enabledSubstitutions & 1 /* AsyncMethodsWithSuper */ && isSuperContainer(node)) { const superContainerFlags = resolver.getNodeCheckFlags(node) & (128 /* MethodWithSuperPropertyAccessInAsync */ | 256 /* MethodWithSuperPropertyAssignmentInAsync */); @@ -97604,22 +88875,13 @@ ${lanes.join("\n")} } function substitutePropertyAccessExpression(node) { if (node.expression.kind === 108 /* SuperKeyword */) { - return setTextRange( - factory2.createPropertyAccessExpression( - factory2.createUniqueName("_super", 16 /* Optimistic */ | 32 /* FileLevel */), - node.name - ), - node - ); + return setTextRange(factory2.createPropertyAccessExpression(factory2.createUniqueName("_super", 16 /* Optimistic */ | 32 /* FileLevel */), node.name), node); } return node; } function substituteElementAccessExpression(node) { if (node.expression.kind === 108 /* SuperKeyword */) { - return createSuperElementAccessInAsyncMethod( - node.argumentExpression, - node - ); + return createSuperElementAccessInAsyncMethod(node.argumentExpression, node); } return node; } @@ -97627,15 +88889,8 @@ ${lanes.join("\n")} const expression = node.expression; if (isSuperProperty(expression)) { const argumentExpression = isPropertyAccessExpression(expression) ? substitutePropertyAccessExpression(expression) : substituteElementAccessExpression(expression); - return factory2.createCallExpression( - factory2.createPropertyAccessExpression(argumentExpression, "call"), - /*typeArguments*/ - void 0, - [ - factory2.createThis(), - ...node.arguments - ] - ); + return factory2.createCallExpression(factory2.createPropertyAccessExpression(argumentExpression, "call"), /*typeArguments*/ + void 0, [factory2.createThis(), ...node.arguments]); } return node; } @@ -97643,30 +88898,14 @@ ${lanes.join("\n")} const kind = node.kind; return kind === 263 /* ClassDeclaration */ || kind === 176 /* Constructor */ || kind === 174 /* MethodDeclaration */ || kind === 177 /* GetAccessor */ || kind === 178 /* SetAccessor */; } + function createSuperElementAccessInAsyncMethod(argumentExpression, location) { if (enclosingSuperContainerFlags & 256 /* MethodWithSuperPropertyAssignmentInAsync */) { - return setTextRange( - factory2.createPropertyAccessExpression( - factory2.createCallExpression( - factory2.createUniqueName("_superIndex", 16 /* Optimistic */ | 32 /* FileLevel */), - /*typeArguments*/ - void 0, - [argumentExpression] - ), - "value" - ), - location - ); + return setTextRange(factory2.createPropertyAccessExpression(factory2.createCallExpression(factory2.createUniqueName("_superIndex", 16 /* Optimistic */ | 32 /* FileLevel */), /*typeArguments*/ + void 0, [argumentExpression]), "value"), location); } else { - return setTextRange( - factory2.createCallExpression( - factory2.createUniqueName("_superIndex", 16 /* Optimistic */ | 32 /* FileLevel */), - /*typeArguments*/ - void 0, - [argumentExpression] - ), - location - ); + return setTextRange(factory2.createCallExpression(factory2.createUniqueName("_superIndex", 16 /* Optimistic */ | 32 /* FileLevel */), /*typeArguments*/ + void 0, [argumentExpression]), location); } } } @@ -97676,120 +88915,40 @@ ${lanes.join("\n")} names.forEach((_, key) => { const name = unescapeLeadingUnderscores(key); const getterAndSetter = []; - getterAndSetter.push(factory2.createPropertyAssignment( - "get", - factory2.createArrowFunction( - /*modifiers*/ - void 0, - /*typeParameters*/ - void 0, - /* parameters */ - [], - /*type*/ - void 0, - /*equalsGreaterThanToken*/ - void 0, - setEmitFlags( - factory2.createPropertyAccessExpression( - setEmitFlags( - factory2.createSuper(), - 8 /* NoSubstitution */ - ), - name - ), - 8 /* NoSubstitution */ - ) - ) - )); + getterAndSetter.push(factory2.createPropertyAssignment("get", factory2.createArrowFunction( /*modifiers*/ + void 0, /*typeParameters*/ + void 0, /* parameters */ + [], /*type*/ + void 0, /*equalsGreaterThanToken*/ + void 0, setEmitFlags(factory2.createPropertyAccessExpression(setEmitFlags(factory2.createSuper(), 8 /* NoSubstitution */), name), 8 /* NoSubstitution */)))); + if (hasBinding) { - getterAndSetter.push( - factory2.createPropertyAssignment( - "set", - factory2.createArrowFunction( - /*modifiers*/ - void 0, - /*typeParameters*/ - void 0, - /* parameters */ - [ - factory2.createParameterDeclaration( - /*modifiers*/ - void 0, - /*dotDotDotToken*/ - void 0, - "v", - /*questionToken*/ - void 0, - /*type*/ - void 0, - /*initializer*/ - void 0 - ) - ], - /*type*/ - void 0, - /*equalsGreaterThanToken*/ - void 0, - factory2.createAssignment( - setEmitFlags( - factory2.createPropertyAccessExpression( - setEmitFlags( - factory2.createSuper(), - 8 /* NoSubstitution */ - ), - name - ), - 8 /* NoSubstitution */ - ), - factory2.createIdentifier("v") - ) - ) - ) - ); + getterAndSetter.push(factory2.createPropertyAssignment("set", factory2.createArrowFunction( /*modifiers*/ + void 0, /*typeParameters*/ + void 0, /* parameters */ + [factory2.createParameterDeclaration( /*modifiers*/ + void 0, /*dotDotDotToken*/ + void 0, "v", /*questionToken*/ + void 0, /*type*/ + void 0, /*initializer*/ + void 0)], /*type*/ + void 0, /*equalsGreaterThanToken*/ + void 0, factory2.createAssignment(setEmitFlags(factory2.createPropertyAccessExpression(setEmitFlags(factory2.createSuper(), 8 /* NoSubstitution */), name), 8 /* NoSubstitution */), factory2.createIdentifier("v"))))); } - accessors.push( - factory2.createPropertyAssignment( - name, - factory2.createObjectLiteralExpression(getterAndSetter) - ) - ); + accessors.push(factory2.createPropertyAssignment(name, factory2.createObjectLiteralExpression(getterAndSetter))); }); - return factory2.createVariableStatement( - /*modifiers*/ - void 0, - factory2.createVariableDeclarationList( - [ - factory2.createVariableDeclaration( - factory2.createUniqueName("_super", 16 /* Optimistic */ | 32 /* FileLevel */), - /*exclamationToken*/ - void 0, - /*type*/ - void 0, - factory2.createCallExpression( - factory2.createPropertyAccessExpression( - factory2.createIdentifier("Object"), - "create" - ), - /*typeArguments*/ - void 0, - [ - factory2.createNull(), - factory2.createObjectLiteralExpression( - accessors, - /*multiLine*/ - true - ) - ] - ) - ) - ], - 2 /* Const */ - ) - ); + return factory2.createVariableStatement( /*modifiers*/ + void 0, factory2.createVariableDeclarationList([factory2.createVariableDeclaration(factory2.createUniqueName("_super", 16 /* Optimistic */ | 32 /* FileLevel */), /*exclamationToken*/ + void 0, /*type*/ + void 0, factory2.createCallExpression(factory2.createPropertyAccessExpression(factory2.createIdentifier("Object"), "create"), /*typeArguments*/ + void 0, [factory2.createNull(), factory2.createObjectLiteralExpression(accessors, /*multiLine*/ + true)]))], 2 /* Const */)); } + var init_es2017 = __esm({ "src/compiler/transformers/es2017.ts"() { "use strict"; + init_ts2(); } }); @@ -97834,10 +88993,7 @@ ${lanes.join("\n")} hierarchyFacts = ancestorFacts; } function recordTaggedTemplateString(temp) { - taggedTemplateStringDeclarations = append( - taggedTemplateStringDeclarations, - factory2.createVariableDeclaration(temp) - ); + taggedTemplateStringDeclarations = append(taggedTemplateStringDeclarations, factory2.createVariableDeclaration(temp)); } function transformSourceFile(node) { if (node.isDeclarationFile) { @@ -97851,18 +89007,12 @@ ${lanes.join("\n")} return visited; } function visitor(node) { - return visitorWorker( - node, - /*expressionResultIsUnused*/ - false - ); + return visitorWorker(node, /*expressionResultIsUnused*/ + false); } function visitorWithUnusedExpressionResult(node) { - return visitorWorker( - node, - /*expressionResultIsUnused*/ - true - ); + return visitorWorker(node, /*expressionResultIsUnused*/ + true); } function visitorNoAsyncModifier(node) { if (node.kind === 134 /* AsyncKeyword */) { @@ -97910,76 +89060,37 @@ ${lanes.join("\n")} case 246 /* DoStatement */: case 247 /* WhileStatement */: case 249 /* ForInStatement */: - return doWithHierarchyFacts( - visitDefault, - node, - 0 /* IterationStatementExcludes */, - 2 /* IterationStatementIncludes */ - ); + return doWithHierarchyFacts(visitDefault, node, 0 /* IterationStatementExcludes */, 2 /* IterationStatementIncludes */); + case 250 /* ForOfStatement */: - return visitForOfStatement( - node, - /*outermostLabeledStatement*/ - void 0 - ); + return visitForOfStatement(node, /*outermostLabeledStatement*/ + void 0); case 248 /* ForStatement */: - return doWithHierarchyFacts( - visitForStatement, - node, - 0 /* IterationStatementExcludes */, - 2 /* IterationStatementIncludes */ - ); + return doWithHierarchyFacts(visitForStatement, node, 0 /* IterationStatementExcludes */, 2 /* IterationStatementIncludes */); + case 222 /* VoidExpression */: return visitVoidExpression(node); case 176 /* Constructor */: - return doWithHierarchyFacts( - visitConstructorDeclaration, - node, - 2 /* ClassOrFunctionExcludes */, - 1 /* ClassOrFunctionIncludes */ - ); + return doWithHierarchyFacts(visitConstructorDeclaration, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */); + case 174 /* MethodDeclaration */: - return doWithHierarchyFacts( - visitMethodDeclaration, - node, - 2 /* ClassOrFunctionExcludes */, - 1 /* ClassOrFunctionIncludes */ - ); + return doWithHierarchyFacts(visitMethodDeclaration, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */); + case 177 /* GetAccessor */: - return doWithHierarchyFacts( - visitGetAccessorDeclaration, - node, - 2 /* ClassOrFunctionExcludes */, - 1 /* ClassOrFunctionIncludes */ - ); + return doWithHierarchyFacts(visitGetAccessorDeclaration, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */); + case 178 /* SetAccessor */: - return doWithHierarchyFacts( - visitSetAccessorDeclaration, - node, - 2 /* ClassOrFunctionExcludes */, - 1 /* ClassOrFunctionIncludes */ - ); + return doWithHierarchyFacts(visitSetAccessorDeclaration, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */); + case 262 /* FunctionDeclaration */: - return doWithHierarchyFacts( - visitFunctionDeclaration, - node, - 2 /* ClassOrFunctionExcludes */, - 1 /* ClassOrFunctionIncludes */ - ); + return doWithHierarchyFacts(visitFunctionDeclaration, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */); + case 218 /* FunctionExpression */: - return doWithHierarchyFacts( - visitFunctionExpression, - node, - 2 /* ClassOrFunctionExcludes */, - 1 /* ClassOrFunctionIncludes */ - ); + return doWithHierarchyFacts(visitFunctionExpression, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */); + case 219 /* ArrowFunction */: - return doWithHierarchyFacts( - visitArrowFunction, - node, - 2 /* ArrowFunctionExcludes */, - 0 /* ArrowFunctionIncludes */ - ); + return doWithHierarchyFacts(visitArrowFunction, node, 2 /* ArrowFunctionExcludes */, 0 /* ArrowFunctionIncludes */); + case 169 /* Parameter */: return visitParameter(node); case 244 /* ExpressionStatement */: @@ -98000,30 +89111,17 @@ ${lanes.join("\n")} return visitEachChild(node, visitor, context); case 263 /* ClassDeclaration */: case 231 /* ClassExpression */: - return doWithHierarchyFacts( - visitDefault, - node, - 2 /* ClassOrFunctionExcludes */, - 1 /* ClassOrFunctionIncludes */ - ); + return doWithHierarchyFacts(visitDefault, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */); + default: return visitEachChild(node, visitor, context); } } function visitAwaitExpression(node) { if (enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */) { - return setOriginalNode( - setTextRange( - factory2.createYieldExpression( - /*asteriskToken*/ - void 0, - emitHelpers().createAwaitHelper(visitNode(node.expression, visitor, isExpression)) - ), - /*location*/ - node - ), - node - ); + return setOriginalNode(setTextRange(factory2.createYieldExpression( /*asteriskToken*/ + void 0, emitHelpers().createAwaitHelper(visitNode(node.expression, visitor, isExpression))), /*location*/ + node), node); } return visitEachChild(node, visitor, context); } @@ -98031,56 +89129,17 @@ ${lanes.join("\n")} if (enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */) { if (node.asteriskToken) { const expression = visitNode(Debug.checkDefined(node.expression), visitor, isExpression); - return setOriginalNode( - setTextRange( - factory2.createYieldExpression( - /*asteriskToken*/ - void 0, - emitHelpers().createAwaitHelper( - factory2.updateYieldExpression( - node, - node.asteriskToken, - setTextRange( - emitHelpers().createAsyncDelegatorHelper( - setTextRange( - emitHelpers().createAsyncValuesHelper(expression), - expression - ) - ), - expression - ) - ) - ) - ), - node - ), - node - ); + return setOriginalNode(setTextRange(factory2.createYieldExpression( /*asteriskToken*/ + void 0, emitHelpers().createAwaitHelper(factory2.updateYieldExpression(node, node.asteriskToken, setTextRange(emitHelpers().createAsyncDelegatorHelper(setTextRange(emitHelpers().createAsyncValuesHelper(expression), expression)), expression)))), node), node); } - return setOriginalNode( - setTextRange( - factory2.createYieldExpression( - /*asteriskToken*/ - void 0, - createDownlevelAwait( - node.expression ? visitNode(node.expression, visitor, isExpression) : factory2.createVoidZero() - ) - ), - node - ), - node - ); + return setOriginalNode(setTextRange(factory2.createYieldExpression( /*asteriskToken*/ + void 0, createDownlevelAwait(node.expression ? visitNode(node.expression, visitor, isExpression) : factory2.createVoidZero())), node), node); } return visitEachChild(node, visitor, context); } function visitReturnStatement(node) { if (enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */) { - return factory2.updateReturnStatement( - node, - createDownlevelAwait( - node.expression ? visitNode(node.expression, visitor, isExpression) : factory2.createVoidZero() - ) - ); + return factory2.updateReturnStatement(node, createDownlevelAwait(node.expression ? visitNode(node.expression, visitor, isExpression) : factory2.createVoidZero())); } return visitEachChild(node, visitor, context); } @@ -98106,10 +89165,7 @@ ${lanes.join("\n")} const target = e.expression; objects.push(visitNode(target, visitor, isExpression)); } else { - chunkObject = append( - chunkObject, - e.kind === 303 /* PropertyAssignment */ ? factory2.createPropertyAssignment(e.name, visitNode(e.initializer, visitor, isExpression)) : visitNode(e, visitor, isObjectLiteralElementLike) - ); + chunkObject = append(chunkObject, e.kind === 303 /* PropertyAssignment */ ? factory2.createPropertyAssignment(e.name, visitNode(e.initializer, visitor, isExpression)) : visitNode(e, visitor, isObjectLiteralElementLike)); } } if (chunkObject) { @@ -98142,53 +89198,26 @@ ${lanes.join("\n")} return visitEachChild(node, expressionResultIsUnused2 ? visitorWithUnusedExpressionResult : visitor, context); } function visitSourceFile(node) { - const ancestorFacts = enterSubtree( - 2 /* SourceFileExcludes */, - isEffectiveStrictModeSourceFile(node, compilerOptions) ? 0 /* StrictModeSourceFileIncludes */ : 1 /* SourceFileIncludes */ - ); + const ancestorFacts = enterSubtree(2 /* SourceFileExcludes */, isEffectiveStrictModeSourceFile(node, compilerOptions) ? 0 /* StrictModeSourceFileIncludes */ : 1 /* SourceFileIncludes */); + exportedVariableStatement = false; const visited = visitEachChild(node, visitor, context); - const statement = concatenate( - visited.statements, - taggedTemplateStringDeclarations && [ - factory2.createVariableStatement( - /*modifiers*/ - void 0, - factory2.createVariableDeclarationList(taggedTemplateStringDeclarations) - ) - ] - ); + const statement = concatenate(visited.statements, taggedTemplateStringDeclarations && [factory2.createVariableStatement( /*modifiers*/ + void 0, factory2.createVariableDeclarationList(taggedTemplateStringDeclarations))]); const result = factory2.updateSourceFile(visited, setTextRange(factory2.createNodeArray(statement), node.statements)); exitSubtree(ancestorFacts); return result; } function visitTaggedTemplateExpression(node) { - return processTaggedTemplateExpression( - context, - node, - visitor, - currentSourceFile, - recordTaggedTemplateString, - 0 /* LiftRestriction */ - ); + return processTaggedTemplateExpression(context, node, visitor, currentSourceFile, recordTaggedTemplateString, 0 /* LiftRestriction */); } + function visitBinaryExpression(node, expressionResultIsUnused2) { if (isDestructuringAssignment(node) && containsObjectRestOrSpread(node.left)) { - return flattenDestructuringAssignment( - node, - visitor, - context, - 1 /* ObjectRest */, - !expressionResultIsUnused2 - ); + return flattenDestructuringAssignment(node, visitor, context, 1 /* ObjectRest */, !expressionResultIsUnused2); } if (node.operatorToken.kind === 28 /* CommaToken */) { - return factory2.updateBinaryExpression( - node, - visitNode(node.left, visitorWithUnusedExpressionResult, isExpression), - node.operatorToken, - visitNode(node.right, expressionResultIsUnused2 ? visitorWithUnusedExpressionResult : visitor, isExpression) - ); + return factory2.updateBinaryExpression(node, visitNode(node.left, visitorWithUnusedExpressionResult, isExpression), node.operatorToken, visitNode(node.right, expressionResultIsUnused2 ? visitorWithUnusedExpressionResult : visitor, isExpression)); } return visitEachChild(node, visitor, context); } @@ -98211,41 +89240,19 @@ ${lanes.join("\n")} function visitCatchClause(node) { if (node.variableDeclaration && isBindingPattern(node.variableDeclaration.name) && node.variableDeclaration.name.transformFlags & 65536 /* ContainsObjectRestOrSpread */) { const name = factory2.getGeneratedNameForNode(node.variableDeclaration.name); - const updatedDecl = factory2.updateVariableDeclaration( - node.variableDeclaration, - node.variableDeclaration.name, - /*exclamationToken*/ - void 0, - /*type*/ - void 0, - name - ); + const updatedDecl = factory2.updateVariableDeclaration(node.variableDeclaration, node.variableDeclaration.name, /*exclamationToken*/ + void 0, /*type*/ + void 0, name); const visitedBindings = flattenDestructuringBinding(updatedDecl, visitor, context, 1 /* ObjectRest */); let block = visitNode(node.block, visitor, isBlock); if (some(visitedBindings)) { - block = factory2.updateBlock(block, [ - factory2.createVariableStatement( - /*modifiers*/ - void 0, - visitedBindings - ), - ...block.statements - ]); + block = factory2.updateBlock(block, [factory2.createVariableStatement( /*modifiers*/ + void 0, visitedBindings), ...block.statements]); } - return factory2.updateCatchClause( - node, - factory2.updateVariableDeclaration( - node.variableDeclaration, - name, - /*exclamationToken*/ - void 0, - /*type*/ - void 0, - /*initializer*/ - void 0 - ), - block - ); + return factory2.updateCatchClause(node, factory2.updateVariableDeclaration(node.variableDeclaration, name, /*exclamationToken*/ + void 0, /*type*/ + void 0, /*initializer*/ + void 0), block); } return visitEachChild(node, visitor, context); } @@ -98263,42 +89270,23 @@ ${lanes.join("\n")} if (exportedVariableStatement) { const savedExportedVariableStatement = exportedVariableStatement; exportedVariableStatement = false; - const visited = visitVariableDeclarationWorker( - node, - /*exportedVariableStatement*/ - true - ); + const visited = visitVariableDeclarationWorker(node, /*exportedVariableStatement*/ + true); exportedVariableStatement = savedExportedVariableStatement; return visited; } - return visitVariableDeclarationWorker( - node, - /*exportedVariableStatement*/ - false - ); + return visitVariableDeclarationWorker(node, /*exportedVariableStatement*/ + false); } function visitVariableDeclarationWorker(node, exportedVariableStatement2) { if (isBindingPattern(node.name) && node.name.transformFlags & 65536 /* ContainsObjectRestOrSpread */) { - return flattenDestructuringBinding( - node, - visitor, - context, - 1 /* ObjectRest */, - /*rval*/ - void 0, - exportedVariableStatement2 - ); + return flattenDestructuringBinding(node, visitor, context, 1 /* ObjectRest */, /*rval*/ + void 0, exportedVariableStatement2); } return visitEachChild(node, visitor, context); } function visitForStatement(node) { - return factory2.updateForStatement( - node, - visitNode(node.initializer, visitorWithUnusedExpressionResult, isForInitializer), - visitNode(node.condition, visitor, isExpression), - visitNode(node.incrementor, visitorWithUnusedExpressionResult, isExpression), - visitIterationBody(node.statement, visitor, context) - ); + return factory2.updateForStatement(node, visitNode(node.initializer, visitorWithUnusedExpressionResult, isForInitializer), visitNode(node.condition, visitor, isExpression), visitNode(node.incrementor, visitorWithUnusedExpressionResult, isExpression), visitIterationBody(node.statement, visitor, context)); } function visitVoidExpression(node) { return visitEachChild(node, visitorWithUnusedExpressionResult, context); @@ -98317,10 +89305,8 @@ ${lanes.join("\n")} if (isVariableDeclarationList(initializerWithoutParens) || isAssignmentPattern(initializerWithoutParens)) { let bodyLocation; let statementsLocation; - const temp = factory2.createTempVariable( - /*recordTempVariable*/ - void 0 - ); + const temp = factory2.createTempVariable( /*recordTempVariable*/ + void 0); const statements = [createForOfBindingStatement(factory2, initializerWithoutParens, temp)]; if (isBlock(node.statement)) { addRange(statements, node.statement.statements); @@ -98331,28 +89317,8 @@ ${lanes.join("\n")} bodyLocation = node.statement; statementsLocation = node.statement; } - return factory2.updateForOfStatement( - node, - node.awaitModifier, - setTextRange( - factory2.createVariableDeclarationList( - [ - setTextRange(factory2.createVariableDeclaration(temp), node.initializer) - ], - 1 /* Let */ - ), - node.initializer - ), - node.expression, - setTextRange( - factory2.createBlock( - setTextRange(factory2.createNodeArray(statements), statementsLocation), - /*multiLine*/ - true - ), - bodyLocation - ) - ); + return factory2.updateForOfStatement(node, node.awaitModifier, setTextRange(factory2.createVariableDeclarationList([setTextRange(factory2.createVariableDeclaration(temp), node.initializer)], 1 /* Let */), node.initializer), node.expression, setTextRange(factory2.createBlock(setTextRange(factory2.createNodeArray(statements), statementsLocation), /*multiLine*/ + true), bodyLocation)); } return node; } @@ -98377,200 +89343,70 @@ ${lanes.join("\n")} } else { statements.push(statement); } - return setTextRange( - factory2.createBlock( - setTextRange(factory2.createNodeArray(statements), statementsLocation), - /*multiLine*/ - true - ), - bodyLocation - ); + return setTextRange(factory2.createBlock(setTextRange(factory2.createNodeArray(statements), statementsLocation), /*multiLine*/ + true), bodyLocation); } function createDownlevelAwait(expression) { - return enclosingFunctionFlags & 1 /* Generator */ ? factory2.createYieldExpression( - /*asteriskToken*/ - void 0, - emitHelpers().createAwaitHelper(expression) - ) : factory2.createAwaitExpression(expression); + return enclosingFunctionFlags & 1 /* Generator */ ? factory2.createYieldExpression( /*asteriskToken*/ + void 0, emitHelpers().createAwaitHelper(expression)) : factory2.createAwaitExpression(expression); } function transformForAwaitOfStatement(node, outermostLabeledStatement, ancestorFacts) { const expression = visitNode(node.expression, visitor, isExpression); - const iterator = isIdentifier(expression) ? factory2.getGeneratedNameForNode(expression) : factory2.createTempVariable( - /*recordTempVariable*/ - void 0 - ); - const result = isIdentifier(expression) ? factory2.getGeneratedNameForNode(iterator) : factory2.createTempVariable( - /*recordTempVariable*/ - void 0 - ); - const nonUserCode = factory2.createTempVariable( - /*recordTempVariable*/ - void 0 - ); + const iterator = isIdentifier(expression) ? factory2.getGeneratedNameForNode(expression) : factory2.createTempVariable( /*recordTempVariable*/ + void 0); + const result = isIdentifier(expression) ? factory2.getGeneratedNameForNode(iterator) : factory2.createTempVariable( /*recordTempVariable*/ + void 0); + const nonUserCode = factory2.createTempVariable( /*recordTempVariable*/ + void 0); const done = factory2.createTempVariable(hoistVariableDeclaration); const errorRecord = factory2.createUniqueName("e"); const catchVariable = factory2.getGeneratedNameForNode(errorRecord); - const returnMethod = factory2.createTempVariable( - /*recordTempVariable*/ - void 0 - ); + const returnMethod = factory2.createTempVariable( /*recordTempVariable*/ + void 0); const callValues = setTextRange(emitHelpers().createAsyncValuesHelper(expression), node.expression); - const callNext = factory2.createCallExpression( - factory2.createPropertyAccessExpression(iterator, "next"), - /*typeArguments*/ - void 0, - [] - ); + const callNext = factory2.createCallExpression(factory2.createPropertyAccessExpression(iterator, "next"), /*typeArguments*/ + void 0, []); const getDone = factory2.createPropertyAccessExpression(result, "done"); const getValue = factory2.createPropertyAccessExpression(result, "value"); const callReturn = factory2.createFunctionCallCall(returnMethod, iterator, []); hoistVariableDeclaration(errorRecord); hoistVariableDeclaration(returnMethod); const initializer = ancestorFacts & 2 /* IterationContainer */ ? factory2.inlineExpressions([factory2.createAssignment(errorRecord, factory2.createVoidZero()), callValues]) : callValues; - const forStatement = setEmitFlags( - setTextRange( - factory2.createForStatement( - /*initializer*/ - setEmitFlags( - setTextRange( - factory2.createVariableDeclarationList([ - factory2.createVariableDeclaration( - nonUserCode, - /*exclamationToken*/ - void 0, - /*type*/ - void 0, - factory2.createTrue() - ), - setTextRange(factory2.createVariableDeclaration( - iterator, - /*exclamationToken*/ - void 0, - /*type*/ - void 0, - initializer - ), node.expression), - factory2.createVariableDeclaration(result) - ]), - node.expression - ), - 4194304 /* NoHoisting */ - ), - /*condition*/ - factory2.inlineExpressions([ - factory2.createAssignment(result, createDownlevelAwait(callNext)), - factory2.createAssignment(done, getDone), - factory2.createLogicalNot(done) - ]), - /*incrementor*/ - factory2.createAssignment(nonUserCode, factory2.createTrue()), - /*statement*/ - convertForOfStatementHead(node, getValue, nonUserCode) - ), - /*location*/ - node - ), - 512 /* NoTokenTrailingSourceMaps */ - ); + const forStatement = setEmitFlags(setTextRange(factory2.createForStatement( /*initializer*/ + setEmitFlags(setTextRange(factory2.createVariableDeclarationList([factory2.createVariableDeclaration(nonUserCode, /*exclamationToken*/ + void 0, /*type*/ + void 0, factory2.createTrue()), setTextRange(factory2.createVariableDeclaration(iterator, /*exclamationToken*/ + void 0, /*type*/ + void 0, initializer), node.expression), factory2.createVariableDeclaration(result)]), node.expression), 4194304 /* NoHoisting */), /*condition*/ + factory2.inlineExpressions([factory2.createAssignment(result, createDownlevelAwait(callNext)), factory2.createAssignment(done, getDone), factory2.createLogicalNot(done)]), /*incrementor*/ + factory2.createAssignment(nonUserCode, factory2.createTrue()), /*statement*/ + convertForOfStatementHead(node, getValue, nonUserCode)), /*location*/ + node), 512 /* NoTokenTrailingSourceMaps */); + setOriginalNode(forStatement, node); - return factory2.createTryStatement( - factory2.createBlock([ - factory2.restoreEnclosingLabel( - forStatement, - outermostLabeledStatement - ) - ]), - factory2.createCatchClause( - factory2.createVariableDeclaration(catchVariable), - setEmitFlags( - factory2.createBlock([ - factory2.createExpressionStatement( - factory2.createAssignment( - errorRecord, - factory2.createObjectLiteralExpression([ - factory2.createPropertyAssignment("error", catchVariable) - ]) - ) - ) - ]), - 1 /* SingleLine */ - ) - ), - factory2.createBlock([ - factory2.createTryStatement( - /*tryBlock*/ - factory2.createBlock([ - setEmitFlags( - factory2.createIfStatement( - factory2.createLogicalAnd( - factory2.createLogicalAnd( - factory2.createLogicalNot(nonUserCode), - factory2.createLogicalNot(done) - ), - factory2.createAssignment( - returnMethod, - factory2.createPropertyAccessExpression(iterator, "return") - ) - ), - factory2.createExpressionStatement(createDownlevelAwait(callReturn)) - ), - 1 /* SingleLine */ - ) - ]), - /*catchClause*/ - void 0, - /*finallyBlock*/ - setEmitFlags( - factory2.createBlock([ - setEmitFlags( - factory2.createIfStatement( - errorRecord, - factory2.createThrowStatement( - factory2.createPropertyAccessExpression(errorRecord, "error") - ) - ), - 1 /* SingleLine */ - ) - ]), - 1 /* SingleLine */ - ) - ) - ]) - ); + return factory2.createTryStatement(factory2.createBlock([factory2.restoreEnclosingLabel(forStatement, outermostLabeledStatement)]), factory2.createCatchClause(factory2.createVariableDeclaration(catchVariable), setEmitFlags(factory2.createBlock([factory2.createExpressionStatement(factory2.createAssignment(errorRecord, factory2.createObjectLiteralExpression([factory2.createPropertyAssignment("error", catchVariable)])))]), 1 /* SingleLine */)), factory2.createBlock([factory2.createTryStatement( /*tryBlock*/ + factory2.createBlock([setEmitFlags(factory2.createIfStatement(factory2.createLogicalAnd(factory2.createLogicalAnd(factory2.createLogicalNot(nonUserCode), factory2.createLogicalNot(done)), factory2.createAssignment(returnMethod, factory2.createPropertyAccessExpression(iterator, "return"))), factory2.createExpressionStatement(createDownlevelAwait(callReturn))), 1 /* SingleLine */)]), /*catchClause*/ + void 0, /*finallyBlock*/ + setEmitFlags(factory2.createBlock([setEmitFlags(factory2.createIfStatement(errorRecord, factory2.createThrowStatement(factory2.createPropertyAccessExpression(errorRecord, "error"))), 1 /* SingleLine */)]), 1 /* SingleLine */))])); } + function parameterVisitor(node) { Debug.assertNode(node, isParameter); return visitParameter(node); } function visitParameter(node) { if (parametersWithPrecedingObjectRestOrSpread == null ? void 0 : parametersWithPrecedingObjectRestOrSpread.has(node)) { - return factory2.updateParameterDeclaration( - node, - /*modifiers*/ - void 0, - node.dotDotDotToken, - isBindingPattern(node.name) ? factory2.getGeneratedNameForNode(node) : node.name, - /*questionToken*/ - void 0, - /*type*/ - void 0, - /*initializer*/ - void 0 - ); + return factory2.updateParameterDeclaration(node, /*modifiers*/ + void 0, node.dotDotDotToken, isBindingPattern(node.name) ? factory2.getGeneratedNameForNode(node) : node.name, /*questionToken*/ + void 0, /*type*/ + void 0, /*initializer*/ + void 0); } if (node.transformFlags & 65536 /* ContainsObjectRestOrSpread */) { - return factory2.updateParameterDeclaration( - node, - /*modifiers*/ - void 0, - node.dotDotDotToken, - factory2.getGeneratedNameForNode(node), - /*questionToken*/ - void 0, - /*type*/ - void 0, - visitNode(node.initializer, visitor, isExpression) - ); + return factory2.updateParameterDeclaration(node, /*modifiers*/ + void 0, node.dotDotDotToken, factory2.getGeneratedNameForNode(node), /*questionToken*/ + void 0, /*type*/ + void 0, visitNode(node.initializer, visitor, isExpression)); } return visitEachChild(node, visitor, context); } @@ -98580,7 +89416,7 @@ ${lanes.join("\n")} if (parameters) { parameters.add(parameter); } else if (parameter.transformFlags & 65536 /* ContainsObjectRestOrSpread */) { - parameters = /* @__PURE__ */ new Set(); + parameters = /* @__PURE__ */new Set(); } } return parameters; @@ -98590,12 +89426,7 @@ ${lanes.join("\n")} const savedParametersWithPrecedingObjectRestOrSpread = parametersWithPrecedingObjectRestOrSpread; enclosingFunctionFlags = getFunctionFlags(node); parametersWithPrecedingObjectRestOrSpread = collectParametersWithPrecedingObjectRestOrSpread(node); - const updated = factory2.updateConstructorDeclaration( - node, - node.modifiers, - visitParameterList(node.parameters, parameterVisitor, context), - transformFunctionBody2(node) - ); + const updated = factory2.updateConstructorDeclaration(node, node.modifiers, visitParameterList(node.parameters, parameterVisitor, context), transformFunctionBody2(node)); enclosingFunctionFlags = savedEnclosingFunctionFlags; parametersWithPrecedingObjectRestOrSpread = savedParametersWithPrecedingObjectRestOrSpread; return updated; @@ -98605,15 +89436,8 @@ ${lanes.join("\n")} const savedParametersWithPrecedingObjectRestOrSpread = parametersWithPrecedingObjectRestOrSpread; enclosingFunctionFlags = getFunctionFlags(node); parametersWithPrecedingObjectRestOrSpread = collectParametersWithPrecedingObjectRestOrSpread(node); - const updated = factory2.updateGetAccessorDeclaration( - node, - node.modifiers, - visitNode(node.name, visitor, isPropertyName), - visitParameterList(node.parameters, parameterVisitor, context), - /*type*/ - void 0, - transformFunctionBody2(node) - ); + const updated = factory2.updateGetAccessorDeclaration(node, node.modifiers, visitNode(node.name, visitor, isPropertyName), visitParameterList(node.parameters, parameterVisitor, context), /*type*/ + void 0, transformFunctionBody2(node)); enclosingFunctionFlags = savedEnclosingFunctionFlags; parametersWithPrecedingObjectRestOrSpread = savedParametersWithPrecedingObjectRestOrSpread; return updated; @@ -98623,13 +89447,7 @@ ${lanes.join("\n")} const savedParametersWithPrecedingObjectRestOrSpread = parametersWithPrecedingObjectRestOrSpread; enclosingFunctionFlags = getFunctionFlags(node); parametersWithPrecedingObjectRestOrSpread = collectParametersWithPrecedingObjectRestOrSpread(node); - const updated = factory2.updateSetAccessorDeclaration( - node, - node.modifiers, - visitNode(node.name, visitor, isPropertyName), - visitParameterList(node.parameters, parameterVisitor, context), - transformFunctionBody2(node) - ); + const updated = factory2.updateSetAccessorDeclaration(node, node.modifiers, visitNode(node.name, visitor, isPropertyName), visitParameterList(node.parameters, parameterVisitor, context), transformFunctionBody2(node)); enclosingFunctionFlags = savedEnclosingFunctionFlags; parametersWithPrecedingObjectRestOrSpread = savedParametersWithPrecedingObjectRestOrSpread; return updated; @@ -98639,24 +89457,10 @@ ${lanes.join("\n")} const savedParametersWithPrecedingObjectRestOrSpread = parametersWithPrecedingObjectRestOrSpread; enclosingFunctionFlags = getFunctionFlags(node); parametersWithPrecedingObjectRestOrSpread = collectParametersWithPrecedingObjectRestOrSpread(node); - const updated = factory2.updateMethodDeclaration( - node, - enclosingFunctionFlags & 1 /* Generator */ ? visitNodes2(node.modifiers, visitorNoAsyncModifier, isModifierLike) : node.modifiers, - enclosingFunctionFlags & 2 /* Async */ ? void 0 : node.asteriskToken, - visitNode(node.name, visitor, isPropertyName), - visitNode( - /*node*/ - void 0, - visitor, - isQuestionToken - ), - /*typeParameters*/ - void 0, - visitParameterList(node.parameters, parameterVisitor, context), - /*type*/ - void 0, - enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */ ? transformAsyncGeneratorFunctionBody(node) : transformFunctionBody2(node) - ); + const updated = factory2.updateMethodDeclaration(node, enclosingFunctionFlags & 1 /* Generator */ ? visitNodes2(node.modifiers, visitorNoAsyncModifier, isModifierLike) : node.modifiers, enclosingFunctionFlags & 2 /* Async */ ? void 0 : node.asteriskToken, visitNode(node.name, visitor, isPropertyName), visitNode( /*node*/ + void 0, visitor, isQuestionToken), /*typeParameters*/ + void 0, visitParameterList(node.parameters, parameterVisitor, context), /*type*/ + void 0, enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */ ? transformAsyncGeneratorFunctionBody(node) : transformFunctionBody2(node)); enclosingFunctionFlags = savedEnclosingFunctionFlags; parametersWithPrecedingObjectRestOrSpread = savedParametersWithPrecedingObjectRestOrSpread; return updated; @@ -98666,18 +89470,9 @@ ${lanes.join("\n")} const savedParametersWithPrecedingObjectRestOrSpread = parametersWithPrecedingObjectRestOrSpread; enclosingFunctionFlags = getFunctionFlags(node); parametersWithPrecedingObjectRestOrSpread = collectParametersWithPrecedingObjectRestOrSpread(node); - const updated = factory2.updateFunctionDeclaration( - node, - enclosingFunctionFlags & 1 /* Generator */ ? visitNodes2(node.modifiers, visitorNoAsyncModifier, isModifier) : node.modifiers, - enclosingFunctionFlags & 2 /* Async */ ? void 0 : node.asteriskToken, - node.name, - /*typeParameters*/ - void 0, - visitParameterList(node.parameters, parameterVisitor, context), - /*type*/ - void 0, - enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */ ? transformAsyncGeneratorFunctionBody(node) : transformFunctionBody2(node) - ); + const updated = factory2.updateFunctionDeclaration(node, enclosingFunctionFlags & 1 /* Generator */ ? visitNodes2(node.modifiers, visitorNoAsyncModifier, isModifier) : node.modifiers, enclosingFunctionFlags & 2 /* Async */ ? void 0 : node.asteriskToken, node.name, /*typeParameters*/ + void 0, visitParameterList(node.parameters, parameterVisitor, context), /*type*/ + void 0, enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */ ? transformAsyncGeneratorFunctionBody(node) : transformFunctionBody2(node)); enclosingFunctionFlags = savedEnclosingFunctionFlags; parametersWithPrecedingObjectRestOrSpread = savedParametersWithPrecedingObjectRestOrSpread; return updated; @@ -98687,17 +89482,9 @@ ${lanes.join("\n")} const savedParametersWithPrecedingObjectRestOrSpread = parametersWithPrecedingObjectRestOrSpread; enclosingFunctionFlags = getFunctionFlags(node); parametersWithPrecedingObjectRestOrSpread = collectParametersWithPrecedingObjectRestOrSpread(node); - const updated = factory2.updateArrowFunction( - node, - node.modifiers, - /*typeParameters*/ - void 0, - visitParameterList(node.parameters, parameterVisitor, context), - /*type*/ - void 0, - node.equalsGreaterThanToken, - transformFunctionBody2(node) - ); + const updated = factory2.updateArrowFunction(node, node.modifiers, /*typeParameters*/ + void 0, visitParameterList(node.parameters, parameterVisitor, context), /*type*/ + void 0, node.equalsGreaterThanToken, transformFunctionBody2(node)); enclosingFunctionFlags = savedEnclosingFunctionFlags; parametersWithPrecedingObjectRestOrSpread = savedParametersWithPrecedingObjectRestOrSpread; return updated; @@ -98707,18 +89494,9 @@ ${lanes.join("\n")} const savedParametersWithPrecedingObjectRestOrSpread = parametersWithPrecedingObjectRestOrSpread; enclosingFunctionFlags = getFunctionFlags(node); parametersWithPrecedingObjectRestOrSpread = collectParametersWithPrecedingObjectRestOrSpread(node); - const updated = factory2.updateFunctionExpression( - node, - enclosingFunctionFlags & 1 /* Generator */ ? visitNodes2(node.modifiers, visitorNoAsyncModifier, isModifier) : node.modifiers, - enclosingFunctionFlags & 2 /* Async */ ? void 0 : node.asteriskToken, - node.name, - /*typeParameters*/ - void 0, - visitParameterList(node.parameters, parameterVisitor, context), - /*type*/ - void 0, - enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */ ? transformAsyncGeneratorFunctionBody(node) : transformFunctionBody2(node) - ); + const updated = factory2.updateFunctionExpression(node, enclosingFunctionFlags & 1 /* Generator */ ? visitNodes2(node.modifiers, visitorNoAsyncModifier, isModifier) : node.modifiers, enclosingFunctionFlags & 2 /* Async */ ? void 0 : node.asteriskToken, node.name, /*typeParameters*/ + void 0, visitParameterList(node.parameters, parameterVisitor, context), /*type*/ + void 0, enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */ ? transformAsyncGeneratorFunctionBody(node) : transformFunctionBody2(node)); enclosingFunctionFlags = savedEnclosingFunctionFlags; parametersWithPrecedingObjectRestOrSpread = savedParametersWithPrecedingObjectRestOrSpread; return updated; @@ -98726,39 +89504,19 @@ ${lanes.join("\n")} function transformAsyncGeneratorFunctionBody(node) { resumeLexicalEnvironment(); const statements = []; - const statementOffset = factory2.copyPrologue( - node.body.statements, - statements, - /*ensureUseStrict*/ - false, - visitor - ); + const statementOffset = factory2.copyPrologue(node.body.statements, statements, /*ensureUseStrict*/ + false, visitor); appendObjectRestAssignmentsIfNeeded(statements, node); const savedCapturedSuperProperties = capturedSuperProperties; const savedHasSuperElementAccess = hasSuperElementAccess; - capturedSuperProperties = /* @__PURE__ */ new Set(); + capturedSuperProperties = /* @__PURE__ */new Set(); hasSuperElementAccess = false; - const returnStatement = factory2.createReturnStatement( - emitHelpers().createAsyncGeneratorHelper( - factory2.createFunctionExpression( - /*modifiers*/ - void 0, - factory2.createToken(42 /* AsteriskToken */), - node.name && factory2.getGeneratedNameForNode(node.name), - /*typeParameters*/ - void 0, - /*parameters*/ - [], - /*type*/ - void 0, - factory2.updateBlock( - node.body, - visitLexicalEnvironment(node.body.statements, visitor, context, statementOffset) - ) - ), - !!(hierarchyFacts & 1 /* HasLexicalThis */) - ) - ); + const returnStatement = factory2.createReturnStatement(emitHelpers().createAsyncGeneratorHelper(factory2.createFunctionExpression( /*modifiers*/ + void 0, factory2.createToken(42 /* AsteriskToken */), node.name && factory2.getGeneratedNameForNode(node.name), /*typeParameters*/ + void 0, /*parameters*/ + [], /*type*/ + void 0, factory2.updateBlock(node.body, visitLexicalEnvironment(node.body.statements, visitor, context, statementOffset))), !!(hierarchyFacts & 1 /* HasLexicalThis */))); + const emitSuperHelpers = languageVersion >= 2 /* ES2015 */ && resolver.getNodeCheckFlags(node) & (256 /* MethodWithSuperPropertyAssignmentInAsync */ | 128 /* MethodWithSuperPropertyAccessInAsync */); if (emitSuperHelpers) { enableSubstitutionForAsyncMethodsWithSuper(); @@ -98781,31 +89539,21 @@ ${lanes.join("\n")} return block; } function transformFunctionBody2(node) { + var _visitNode; resumeLexicalEnvironment(); let statementOffset = 0; const statements = []; - const body = visitNode(node.body, visitor, isConciseBody) ?? factory2.createBlock([]); + const body = (_visitNode = visitNode(node.body, visitor, isConciseBody)) !== null && _visitNode !== void 0 ? _visitNode : factory2.createBlock([]); if (isBlock(body)) { - statementOffset = factory2.copyPrologue( - body.statements, - statements, - /*ensureUseStrict*/ - false, - visitor - ); + statementOffset = factory2.copyPrologue(body.statements, statements, /*ensureUseStrict*/ + false, visitor); } - addRange(statements, appendObjectRestAssignmentsIfNeeded( - /*statements*/ - void 0, - node - )); + addRange(statements, appendObjectRestAssignmentsIfNeeded( /*statements*/ + void 0, node)); const leadingStatements = endLexicalEnvironment(); if (statementOffset > 0 || some(statements) || some(leadingStatements)) { - const block = factory2.converters.convertToFunctionBlock( - body, - /*multiLine*/ - true - ); + const block = factory2.converters.convertToFunctionBlock(body, /*multiLine*/ + true); insertStatementsAfterStandardPrologue(statements, leadingStatements); addRange(statements, block.statements.slice(statementOffset)); return factory2.updateBlock(block, setTextRange(factory2.createNodeArray(statements), block.statements)); @@ -98818,20 +89566,11 @@ ${lanes.join("\n")} if (containsPrecedingObjectRestOrSpread) { if (isBindingPattern(parameter.name)) { if (parameter.name.elements.length > 0) { - const declarations = flattenDestructuringBinding( - parameter, - visitor, - context, - 0 /* All */, - factory2.getGeneratedNameForNode(parameter) - ); + const declarations = flattenDestructuringBinding(parameter, visitor, context, 0 /* All */, factory2.getGeneratedNameForNode(parameter)); if (some(declarations)) { const declarationList = factory2.createVariableDeclarationList(declarations); - const statement = factory2.createVariableStatement( - /*modifiers*/ - void 0, - declarationList - ); + const statement = factory2.createVariableStatement( /*modifiers*/ + void 0, declarationList); setEmitFlags(statement, 2097152 /* CustomPrologue */); statements = append(statements, statement); } @@ -98864,24 +89603,13 @@ ${lanes.join("\n")} } } else if (parameter.transformFlags & 65536 /* ContainsObjectRestOrSpread */) { containsPrecedingObjectRestOrSpread = true; - const declarations = flattenDestructuringBinding( - parameter, - visitor, - context, - 1 /* ObjectRest */, - factory2.getGeneratedNameForNode(parameter), - /*hoistTempVariables*/ - false, - /*skipInitializer*/ - true - ); + const declarations = flattenDestructuringBinding(parameter, visitor, context, 1 /* ObjectRest */, factory2.getGeneratedNameForNode(parameter), /*hoistTempVariables*/ + false, /*skipInitializer*/ + true); if (some(declarations)) { const declarationList = factory2.createVariableDeclarationList(declarations); - const statement = factory2.createVariableStatement( - /*modifiers*/ - void 0, - declarationList - ); + const statement = factory2.createVariableStatement( /*modifiers*/ + void 0, declarationList); setEmitFlags(statement, 2097152 /* CustomPrologue */); statements = append(statements, statement); } @@ -98903,6 +89631,7 @@ ${lanes.join("\n")} context.enableEmitNotification(243 /* VariableStatement */); } } + function onEmitNode(hint, node, emitCallback) { if (enabledSubstitutions & 1 /* AsyncMethodsWithSuper */ && isSuperContainer(node)) { const superContainerFlags = resolver.getNodeCheckFlags(node) & (128 /* MethodWithSuperPropertyAccessInAsync */ | 256 /* MethodWithSuperPropertyAssignmentInAsync */); @@ -98942,22 +89671,13 @@ ${lanes.join("\n")} } function substitutePropertyAccessExpression(node) { if (node.expression.kind === 108 /* SuperKeyword */) { - return setTextRange( - factory2.createPropertyAccessExpression( - factory2.createUniqueName("_super", 16 /* Optimistic */ | 32 /* FileLevel */), - node.name - ), - node - ); + return setTextRange(factory2.createPropertyAccessExpression(factory2.createUniqueName("_super", 16 /* Optimistic */ | 32 /* FileLevel */), node.name), node); } return node; } function substituteElementAccessExpression(node) { if (node.expression.kind === 108 /* SuperKeyword */) { - return createSuperElementAccessInAsyncMethod( - node.argumentExpression, - node - ); + return createSuperElementAccessInAsyncMethod(node.argumentExpression, node); } return node; } @@ -98965,15 +89685,8 @@ ${lanes.join("\n")} const expression = node.expression; if (isSuperProperty(expression)) { const argumentExpression = isPropertyAccessExpression(expression) ? substitutePropertyAccessExpression(expression) : substituteElementAccessExpression(expression); - return factory2.createCallExpression( - factory2.createPropertyAccessExpression(argumentExpression, "call"), - /*typeArguments*/ - void 0, - [ - factory2.createThis(), - ...node.arguments - ] - ); + return factory2.createCallExpression(factory2.createPropertyAccessExpression(argumentExpression, "call"), /*typeArguments*/ + void 0, [factory2.createThis(), ...node.arguments]); } return node; } @@ -98981,36 +89694,21 @@ ${lanes.join("\n")} const kind = node.kind; return kind === 263 /* ClassDeclaration */ || kind === 176 /* Constructor */ || kind === 174 /* MethodDeclaration */ || kind === 177 /* GetAccessor */ || kind === 178 /* SetAccessor */; } + function createSuperElementAccessInAsyncMethod(argumentExpression, location) { if (enclosingSuperContainerFlags & 256 /* MethodWithSuperPropertyAssignmentInAsync */) { - return setTextRange( - factory2.createPropertyAccessExpression( - factory2.createCallExpression( - factory2.createIdentifier("_superIndex"), - /*typeArguments*/ - void 0, - [argumentExpression] - ), - "value" - ), - location - ); + return setTextRange(factory2.createPropertyAccessExpression(factory2.createCallExpression(factory2.createIdentifier("_superIndex"), /*typeArguments*/ + void 0, [argumentExpression]), "value"), location); } else { - return setTextRange( - factory2.createCallExpression( - factory2.createIdentifier("_superIndex"), - /*typeArguments*/ - void 0, - [argumentExpression] - ), - location - ); + return setTextRange(factory2.createCallExpression(factory2.createIdentifier("_superIndex"), /*typeArguments*/ + void 0, [argumentExpression]), location); } } } var init_es2018 = __esm({ "src/compiler/transformers/es2018.ts"() { "use strict"; + init_ts2(); } }); @@ -99038,14 +89736,8 @@ ${lanes.join("\n")} } function visitCatchClause(node) { if (!node.variableDeclaration) { - return factory2.updateCatchClause( - node, - factory2.createVariableDeclaration(factory2.createTempVariable( - /*recordTempVariable*/ - void 0 - )), - visitNode(node.block, visitor, isBlock) - ); + return factory2.updateCatchClause(node, factory2.createVariableDeclaration(factory2.createTempVariable( /*recordTempVariable*/ + void 0)), visitNode(node.block, visitor, isBlock)); } return visitEachChild(node, visitor, context); } @@ -99053,6 +89745,7 @@ ${lanes.join("\n")} var init_es2019 = __esm({ "src/compiler/transformers/es2019.ts"() { "use strict"; + init_ts2(); } }); @@ -99075,25 +89768,19 @@ ${lanes.join("\n")} return node; } switch (node.kind) { - case 213 /* CallExpression */: { - const updated = visitNonOptionalCallExpression( - node, - /*captureThisArg*/ - false - ); - Debug.assertNotNode(updated, isSyntheticReference); - return updated; - } + case 213 /* CallExpression */: + { + const updated = visitNonOptionalCallExpression(node, /*captureThisArg*/ + false); + Debug.assertNotNode(updated, isSyntheticReference); + return updated; + } case 211 /* PropertyAccessExpression */: case 212 /* ElementAccessExpression */: if (isOptionalChain(node)) { - const updated = visitOptionalExpression( - node, - /*captureThisArg*/ - false, - /*isDelete*/ - false - ); + const updated = visitOptionalExpression(node, /*captureThisArg*/ + false, /*isDelete*/ + false); Debug.assertNotNode(updated, isSyntheticReference); return updated; } @@ -99117,7 +89804,10 @@ ${lanes.join("\n")} Debug.assertNotNode(chain, isNonNullChain); links.unshift(chain); } - return { expression: chain.expression, chain: links }; + return { + expression: chain.expression, + chain: links + }; } function visitNonOptionalParenthesizedExpression(node, captureThisArg, isDelete) { const expression = visitNonOptionalExpression(node.expression, captureThisArg, isDelete); @@ -99146,32 +89836,19 @@ ${lanes.join("\n")} } function visitNonOptionalCallExpression(node, captureThisArg) { if (isOptionalChain(node)) { - return visitOptionalExpression( - node, - captureThisArg, - /*isDelete*/ - false - ); + return visitOptionalExpression(node, captureThisArg, /*isDelete*/ + false); } if (isParenthesizedExpression(node.expression) && isOptionalChain(skipParentheses(node.expression))) { - const expression = visitNonOptionalParenthesizedExpression( - node.expression, - /*captureThisArg*/ - true, - /*isDelete*/ - false - ); + const expression = visitNonOptionalParenthesizedExpression(node.expression, /*captureThisArg*/ + true, /*isDelete*/ + false); const args = visitNodes2(node.arguments, visitor, isExpression); if (isSyntheticReference(expression)) { return setTextRange(factory2.createFunctionCallCall(expression.expression, expression.thisArg, args), node); } - return factory2.updateCallExpression( - node, - expression, - /*typeArguments*/ - void 0, - args - ); + return factory2.updateCallExpression(node, expression, /*typeArguments*/ + void 0, args); } return visitEachChild(node, visitor, context); } @@ -99189,13 +89866,12 @@ ${lanes.join("\n")} } } function visitOptionalExpression(node, captureThisArg, isDelete) { - const { expression, chain } = flattenChain(node); - const left = visitNonOptionalExpression( - skipPartiallyEmittedExpressions(expression), - isCallChain(chain[0]), - /*isDelete*/ - false - ); + const { + expression, + chain + } = flattenChain(node); + const left = visitNonOptionalExpression(skipPartiallyEmittedExpressions(expression), isCallChain(chain[0]), /*isDelete*/ + false); let leftThisArg = isSyntheticReference(left) ? left.thisArg : void 0; let capturedLeft = isSyntheticReference(left) ? left.expression : left; let leftExpression = factory2.restoreOuterExpressions(expression, capturedLeft, 8 /* PartiallyEmittedExpressions */); @@ -99226,67 +89902,28 @@ ${lanes.join("\n")} leftThisArg = factory2.cloneNode(leftThisArg); addEmitFlags(leftThisArg, 3072 /* NoComments */); } - rightExpression = factory2.createFunctionCallCall( - rightExpression, - leftThisArg.kind === 108 /* SuperKeyword */ ? factory2.createThis() : leftThisArg, - visitNodes2(segment.arguments, visitor, isExpression) - ); + + rightExpression = factory2.createFunctionCallCall(rightExpression, leftThisArg.kind === 108 /* SuperKeyword */ ? factory2.createThis() : leftThisArg, visitNodes2(segment.arguments, visitor, isExpression)); } else { - rightExpression = factory2.createCallExpression( - rightExpression, - /*typeArguments*/ - void 0, - visitNodes2(segment.arguments, visitor, isExpression) - ); + rightExpression = factory2.createCallExpression(rightExpression, /*typeArguments*/ + void 0, visitNodes2(segment.arguments, visitor, isExpression)); } break; } setOriginalNode(rightExpression, segment); } - const target = isDelete ? factory2.createConditionalExpression( - createNotNullCondition( - leftExpression, - capturedLeft, - /*invert*/ - true - ), - /*questionToken*/ - void 0, - factory2.createTrue(), - /*colonToken*/ - void 0, - factory2.createDeleteExpression(rightExpression) - ) : factory2.createConditionalExpression( - createNotNullCondition( - leftExpression, - capturedLeft, - /*invert*/ - true - ), - /*questionToken*/ - void 0, - factory2.createVoidZero(), - /*colonToken*/ - void 0, - rightExpression - ); + const target = isDelete ? factory2.createConditionalExpression(createNotNullCondition(leftExpression, capturedLeft, /*invert*/ + true), /*questionToken*/ + void 0, factory2.createTrue(), /*colonToken*/ + void 0, factory2.createDeleteExpression(rightExpression)) : factory2.createConditionalExpression(createNotNullCondition(leftExpression, capturedLeft, /*invert*/ + true), /*questionToken*/ + void 0, factory2.createVoidZero(), /*colonToken*/ + void 0, rightExpression); setTextRange(target, node); return thisArg ? factory2.createSyntheticReferenceExpression(target, thisArg) : target; } function createNotNullCondition(left, right, invert) { - return factory2.createBinaryExpression( - factory2.createBinaryExpression( - left, - factory2.createToken(invert ? 37 /* EqualsEqualsEqualsToken */ : 38 /* ExclamationEqualsEqualsToken */), - factory2.createNull() - ), - factory2.createToken(invert ? 57 /* BarBarToken */ : 56 /* AmpersandAmpersandToken */), - factory2.createBinaryExpression( - right, - factory2.createToken(invert ? 37 /* EqualsEqualsEqualsToken */ : 38 /* ExclamationEqualsEqualsToken */), - factory2.createVoidZero() - ) - ); + return factory2.createBinaryExpression(factory2.createBinaryExpression(left, factory2.createToken(invert ? 37 /* EqualsEqualsEqualsToken */ : 38 /* ExclamationEqualsEqualsToken */), factory2.createNull()), factory2.createToken(invert ? 57 /* BarBarToken */ : 56 /* AmpersandAmpersandToken */), factory2.createBinaryExpression(right, factory2.createToken(invert ? 37 /* EqualsEqualsEqualsToken */ : 38 /* ExclamationEqualsEqualsToken */), factory2.createVoidZero())); } function transformNullishCoalescingExpression(node) { let left = visitNode(node.left, visitor, isExpression); @@ -99295,32 +89932,20 @@ ${lanes.join("\n")} right = factory2.createTempVariable(hoistVariableDeclaration); left = factory2.createAssignment(right, left); } - return setTextRange( - factory2.createConditionalExpression( - createNotNullCondition(left, right), - /*questionToken*/ - void 0, - right, - /*colonToken*/ - void 0, - visitNode(node.right, visitor, isExpression) - ), - node - ); + return setTextRange(factory2.createConditionalExpression(createNotNullCondition(left, right), /*questionToken*/ + void 0, right, /*colonToken*/ + void 0, visitNode(node.right, visitor, isExpression)), node); } function visitDeleteExpression(node) { - return isOptionalChain(skipParentheses(node.expression)) ? setOriginalNode(visitNonOptionalExpression( - node.expression, - /*captureThisArg*/ - false, - /*isDelete*/ - true - ), node) : factory2.updateDeleteExpression(node, visitNode(node.expression, visitor, isExpression)); + return isOptionalChain(skipParentheses(node.expression)) ? setOriginalNode(visitNonOptionalExpression(node.expression, /*captureThisArg*/ + false, /*isDelete*/ + true), node) : factory2.updateDeleteExpression(node, visitNode(node.expression, visitor, isExpression)); } } var init_es2020 = __esm({ "src/compiler/transformers/es2020.ts"() { "use strict"; + init_ts2(); } }); @@ -99356,50 +89981,24 @@ ${lanes.join("\n")} if (isAccessExpression(left)) { const propertyAccessTargetSimpleCopiable = isSimpleCopiableExpression(left.expression); const propertyAccessTarget = propertyAccessTargetSimpleCopiable ? left.expression : factory2.createTempVariable(hoistVariableDeclaration); - const propertyAccessTargetAssignment = propertyAccessTargetSimpleCopiable ? left.expression : factory2.createAssignment( - propertyAccessTarget, - left.expression - ); + const propertyAccessTargetAssignment = propertyAccessTargetSimpleCopiable ? left.expression : factory2.createAssignment(propertyAccessTarget, left.expression); if (isPropertyAccessExpression(left)) { - assignmentTarget = factory2.createPropertyAccessExpression( - propertyAccessTarget, - left.name - ); - left = factory2.createPropertyAccessExpression( - propertyAccessTargetAssignment, - left.name - ); + assignmentTarget = factory2.createPropertyAccessExpression(propertyAccessTarget, left.name); + left = factory2.createPropertyAccessExpression(propertyAccessTargetAssignment, left.name); } else { const elementAccessArgumentSimpleCopiable = isSimpleCopiableExpression(left.argumentExpression); const elementAccessArgument = elementAccessArgumentSimpleCopiable ? left.argumentExpression : factory2.createTempVariable(hoistVariableDeclaration); - assignmentTarget = factory2.createElementAccessExpression( - propertyAccessTarget, - elementAccessArgument - ); - left = factory2.createElementAccessExpression( - propertyAccessTargetAssignment, - elementAccessArgumentSimpleCopiable ? left.argumentExpression : factory2.createAssignment( - elementAccessArgument, - left.argumentExpression - ) - ); + assignmentTarget = factory2.createElementAccessExpression(propertyAccessTarget, elementAccessArgument); + left = factory2.createElementAccessExpression(propertyAccessTargetAssignment, elementAccessArgumentSimpleCopiable ? left.argumentExpression : factory2.createAssignment(elementAccessArgument, left.argumentExpression)); } } - return factory2.createBinaryExpression( - left, - nonAssignmentOperator, - factory2.createParenthesizedExpression( - factory2.createAssignment( - assignmentTarget, - right - ) - ) - ); + return factory2.createBinaryExpression(left, nonAssignmentOperator, factory2.createParenthesizedExpression(factory2.createAssignment(assignmentTarget, right))); } } var init_es2021 = __esm({ "src/compiler/transformers/es2021.ts"() { "use strict"; + init_ts2(); } }); @@ -99472,36 +90071,20 @@ ${lanes.join("\n")} const envBinding = createEnvBinding(); const bodyStatements = transformUsingDeclarations(node.statements, pos, node.statements.length, envBinding, topLevelStatements); if (exportBindings.size) { - append( - topLevelStatements, - factory2.createExportDeclaration( - /*modifiers*/ - void 0, - /*isTypeOnly*/ - false, - factory2.createNamedExports(arrayFrom(exportBindings.values())) - ) - ); + append(topLevelStatements, factory2.createExportDeclaration( /*modifiers*/ + void 0, /*isTypeOnly*/ + false, factory2.createNamedExports(arrayFrom(exportBindings.values())))); } addRange(topLevelStatements, endLexicalEnvironment()); if (exportVars.length) { - topLevelStatements.push(factory2.createVariableStatement( - factory2.createModifiersFromModifierFlags(32 /* Export */), - factory2.createVariableDeclarationList( - exportVars, - 1 /* Let */ - ) - )); + topLevelStatements.push(factory2.createVariableStatement(factory2.createModifiersFromModifierFlags(32 /* Export */), factory2.createVariableDeclarationList(exportVars, 1 /* Let */))); } + addRange(topLevelStatements, createDownlevelUsingStatements(bodyStatements, envBinding, usingKind === 2 /* Async */)); if (exportEqualsBinding) { - topLevelStatements.push(factory2.createExportAssignment( - /*modifiers*/ - void 0, - /*isExportEquals*/ - true, - exportEqualsBinding - )); + topLevelStatements.push(factory2.createExportAssignment( /*modifiers*/ + void 0, /*isExportEquals*/ + true, exportEqualsBinding)); } return factory2.updateSourceFile(node, topLevelStatements); } @@ -99512,48 +90095,17 @@ ${lanes.join("\n")} if (usingKind) { const prologueCount = countPrologueStatements(node.statements); const envBinding = createEnvBinding(); - return factory2.updateBlock( - node, - [ - ...visitArray(node.statements, visitor, isStatement, 0, prologueCount), - ...createDownlevelUsingStatements( - transformUsingDeclarations( - node.statements, - prologueCount, - node.statements.length, - envBinding, - /*topLevelStatements*/ - void 0 - ), - envBinding, - usingKind === 2 /* Async */ - ) - ] - ); + return factory2.updateBlock(node, [...visitArray(node.statements, visitor, isStatement, 0, prologueCount), ...createDownlevelUsingStatements(transformUsingDeclarations(node.statements, prologueCount, node.statements.length, envBinding, /*topLevelStatements*/ + void 0), envBinding, usingKind === 2 /* Async */)]); } + return visitEachChild(node, visitor, context); } function visitForStatement(node) { if (node.initializer && isUsingVariableDeclarationList(node.initializer)) { - return visitNode( - factory2.createBlock([ - factory2.createVariableStatement( - /*modifiers*/ - void 0, - node.initializer - ), - factory2.updateForStatement( - node, - /*initializer*/ - void 0, - node.condition, - node.incrementor, - node.statement - ) - ]), - visitor, - isStatement - ); + return visitNode(factory2.createBlock([factory2.createVariableStatement( /*modifiers*/ + void 0, node.initializer), factory2.updateForStatement(node, /*initializer*/ + void 0, node.condition, node.incrementor, node.statement)]), visitor, isStatement); } return visitEachChild(node, visitor, context); } @@ -99566,76 +90118,27 @@ ${lanes.join("\n")} Debug.assert(!forDecl.initializer, "ForInitializer may not have an initializer"); const isAwaitUsing = getUsingKindOfVariableDeclarationList(forInitializer) === 2 /* Async */; const temp = factory2.getGeneratedNameForNode(forDecl.name); - const usingVar = factory2.updateVariableDeclaration( - forDecl, - forDecl.name, - /*exclamationToken*/ - void 0, - /*type*/ - void 0, - temp - ); + const usingVar = factory2.updateVariableDeclaration(forDecl, forDecl.name, /*exclamationToken*/ + void 0, /*type*/ + void 0, temp); const usingVarList = factory2.createVariableDeclarationList([usingVar], isAwaitUsing ? 6 /* AwaitUsing */ : 4 /* Using */); - const usingVarStatement = factory2.createVariableStatement( - /*modifiers*/ - void 0, - usingVarList - ); - return visitNode( - factory2.updateForOfStatement( - node, - node.awaitModifier, - factory2.createVariableDeclarationList([ - factory2.createVariableDeclaration(temp) - ], 2 /* Const */), - node.expression, - isBlock(node.statement) ? factory2.updateBlock(node.statement, [ - usingVarStatement, - ...node.statement.statements - ]) : factory2.createBlock( - [ - usingVarStatement, - node.statement - ], - /*multiLine*/ - true - ) - ), - visitor, - isStatement - ); + const usingVarStatement = factory2.createVariableStatement( /*modifiers*/ + void 0, usingVarList); + return visitNode(factory2.updateForOfStatement(node, node.awaitModifier, factory2.createVariableDeclarationList([factory2.createVariableDeclaration(temp)], 2 /* Const */), node.expression, isBlock(node.statement) ? factory2.updateBlock(node.statement, [usingVarStatement, ...node.statement.statements]) : factory2.createBlock([usingVarStatement, node.statement], /*multiLine*/ + true)), visitor, isStatement); } return visitEachChild(node, visitor, context); } function visitCaseOrDefaultClause(node, envBinding) { if (getUsingKindOfStatements(node.statements) !== 0 /* None */) { if (isCaseClause(node)) { - return factory2.updateCaseClause( - node, - visitNode(node.expression, visitor, isExpression), - transformUsingDeclarations( - node.statements, - /*start*/ - 0, - node.statements.length, - envBinding, - /*topLevelStatements*/ - void 0 - ) - ); + return factory2.updateCaseClause(node, visitNode(node.expression, visitor, isExpression), transformUsingDeclarations(node.statements, /*start*/ + 0, node.statements.length, envBinding, /*topLevelStatements*/ + void 0)); } else { - return factory2.updateDefaultClause( - node, - transformUsingDeclarations( - node.statements, - /*start*/ - 0, - node.statements.length, - envBinding, - /*topLevelStatements*/ - void 0 - ) - ); + return factory2.updateDefaultClause(node, transformUsingDeclarations(node.statements, /*start*/ + 0, node.statements.length, envBinding, /*topLevelStatements*/ + void 0)); } } return visitEachChild(node, visitor, context); @@ -99644,21 +90147,9 @@ ${lanes.join("\n")} const usingKind = getUsingKindOfCaseOrDefaultClauses(node.caseBlock.clauses); if (usingKind) { const envBinding = createEnvBinding(); - return createDownlevelUsingStatements( - [ - factory2.updateSwitchStatement( - node, - visitNode(node.expression, visitor, isExpression), - factory2.updateCaseBlock( - node.caseBlock, - node.caseBlock.clauses.map((clause) => visitCaseOrDefaultClause(clause, envBinding)) - ) - ) - ], - envBinding, - usingKind === 2 /* Async */ - ); + return createDownlevelUsingStatements([factory2.updateSwitchStatement(node, visitNode(node.expression, visitor, isExpression), factory2.updateCaseBlock(node.caseBlock, node.caseBlock.clauses.map(clause => visitCaseOrDefaultClause(clause, envBinding))))], envBinding, usingKind === 2 /* Async */); } + return visitEachChild(node, visitor, context); } function transformUsingDeclarations(statementsIn, start, end, envBinding, topLevelStatements) { @@ -99670,6 +90161,7 @@ ${lanes.join("\n")} Debug.assertNode(statement, isVariableStatement); const declarations = []; for (let declaration of statement.declarationList.declarations) { + var _visitNode2; if (!isIdentifier(declaration.name)) { declarations.length = 0; break; @@ -99677,31 +90169,18 @@ ${lanes.join("\n")} if (isNamedEvaluation(declaration)) { declaration = transformNamedEvaluation(context, declaration); } - const initializer = visitNode(declaration.initializer, visitor, isExpression) ?? factory2.createVoidZero(); - declarations.push(factory2.updateVariableDeclaration( - declaration, - declaration.name, - /*exclamationToken*/ - void 0, - /*type*/ - void 0, - emitHelpers().createAddDisposableResourceHelper( - envBinding, - initializer, - usingKind === 2 /* Async */ - ) - )); + const initializer = (_visitNode2 = visitNode(declaration.initializer, visitor, isExpression)) !== null && _visitNode2 !== void 0 ? _visitNode2 : factory2.createVoidZero(); + declarations.push(factory2.updateVariableDeclaration(declaration, declaration.name, /*exclamationToken*/ + void 0, /*type*/ + void 0, emitHelpers().createAddDisposableResourceHelper(envBinding, initializer, usingKind === 2 /* Async */))); } + if (declarations.length) { const varList = factory2.createVariableDeclarationList(declarations, 2 /* Const */); setOriginalNode(varList, statement.declarationList); setTextRange(varList, statement.declarationList); - hoistOrAppendNode(factory2.updateVariableStatement( - statement, - /*modifiers*/ - void 0, - varList - )); + hoistOrAppendNode(factory2.updateVariableStatement(statement, /*modifiers*/ + void 0, varList)); continue; } } @@ -99718,8 +90197,7 @@ ${lanes.join("\n")} append(statements, hoist(node)); } function hoist(node) { - if (!topLevelStatements) - return node; + if (!topLevelStatements) return node; switch (node.kind) { case 272 /* ImportDeclaration */: case 271 /* ImportEqualsDeclaration */: @@ -99748,23 +90226,13 @@ ${lanes.join("\n")} return node; } defaultExportBinding = factory2.createUniqueName("_default", 8 /* ReservedInNestedScopes */ | 32 /* FileLevel */ | 16 /* Optimistic */); - hoistBindingIdentifier( - defaultExportBinding, - /*isExport*/ - true, - "default", - node - ); + hoistBindingIdentifier(defaultExportBinding, /*isExport*/ + true, "default", node); let expression = node.expression; let innerExpression = skipOuterExpressions(expression); if (isNamedEvaluation(innerExpression)) { - innerExpression = transformNamedEvaluation( - context, - innerExpression, - /*ignoreEmptyStringLiteral*/ - false, - "default" - ); + innerExpression = transformNamedEvaluation(context, innerExpression, /*ignoreEmptyStringLiteral*/ + false, "default"); expression = factory2.restoreOuterExpressions(expression, innerExpression); } const assignment = factory2.createAssignment(defaultExportBinding, expression); @@ -99787,21 +90255,12 @@ ${lanes.join("\n")} const isDefault = hasSyntacticModifier(node, 2048 /* Default */); let expression = factory2.converters.convertToClassExpression(node); if (node.name) { - hoistBindingIdentifier( - factory2.getLocalName(node), - isExported2 && !isDefault, - /*exportAlias*/ - void 0, - node - ); + hoistBindingIdentifier(factory2.getLocalName(node), isExported2 && !isDefault, /*exportAlias*/ + void 0, node); expression = factory2.createAssignment(factory2.getDeclarationName(node), expression); if (isNamedEvaluation(expression)) { - expression = transformNamedEvaluation( - context, - expression, - /*ignoreEmptyStringLiteral*/ - false - ); + expression = transformNamedEvaluation(context, expression, /*ignoreEmptyStringLiteral*/ + false); } setOriginalNode(expression, node); setSourceMapRange(expression, node); @@ -99809,22 +90268,12 @@ ${lanes.join("\n")} } if (isDefault && !defaultExportBinding) { defaultExportBinding = factory2.createUniqueName("_default", 8 /* ReservedInNestedScopes */ | 32 /* FileLevel */ | 16 /* Optimistic */); - hoistBindingIdentifier( - defaultExportBinding, - /*isExport*/ - true, - "default", - node - ); + hoistBindingIdentifier(defaultExportBinding, /*isExport*/ + true, "default", node); expression = factory2.createAssignment(defaultExportBinding, expression); if (isNamedEvaluation(expression)) { - expression = transformNamedEvaluation( - context, - expression, - /*ignoreEmptyStringLiteral*/ - false, - "default" - ); + expression = transformNamedEvaluation(context, expression, /*ignoreEmptyStringLiteral*/ + false, "default"); } setOriginalNode(expression, node); } @@ -99871,13 +90320,8 @@ ${lanes.join("\n")} } } } else { - hoistBindingIdentifier( - node.name, - isExportedDeclaration, - /*exportAlias*/ - void 0, - original - ); + hoistBindingIdentifier(node.name, isExportedDeclaration, /*exportAlias*/ + void 0, original); } } function hoistBindingIdentifier(node, isExport, exportAlias, original) { @@ -99893,12 +90337,8 @@ ${lanes.join("\n")} } const localName = exportAlias !== void 0 ? name : void 0; const exportName = exportAlias !== void 0 ? exportAlias : name; - const specifier = factory2.createExportSpecifier( - /*isTypeOnly*/ - false, - localName, - exportName - ); + const specifier = factory2.createExportSpecifier( /*isTypeOnly*/ + false, localName, exportName); if (original) { setOriginalNode(specifier, original); } @@ -99911,87 +90351,30 @@ ${lanes.join("\n")} } function createDownlevelUsingStatements(bodyStatements, envBinding, async) { const statements = []; - const envObject = factory2.createObjectLiteralExpression([ - factory2.createPropertyAssignment("stack", factory2.createArrayLiteralExpression()), - factory2.createPropertyAssignment("error", factory2.createVoidZero()), - factory2.createPropertyAssignment("hasError", factory2.createFalse()) - ]); - const envVar = factory2.createVariableDeclaration( - envBinding, - /*exclamationToken*/ - void 0, - /*type*/ - void 0, - envObject - ); + const envObject = factory2.createObjectLiteralExpression([factory2.createPropertyAssignment("stack", factory2.createArrayLiteralExpression()), factory2.createPropertyAssignment("error", factory2.createVoidZero()), factory2.createPropertyAssignment("hasError", factory2.createFalse())]); + const envVar = factory2.createVariableDeclaration(envBinding, /*exclamationToken*/ + void 0, /*type*/ + void 0, envObject); const envVarList = factory2.createVariableDeclarationList([envVar], 2 /* Const */); - const envVarStatement = factory2.createVariableStatement( - /*modifiers*/ - void 0, - envVarList - ); + const envVarStatement = factory2.createVariableStatement( /*modifiers*/ + void 0, envVarList); statements.push(envVarStatement); - const tryBlock = factory2.createBlock( - bodyStatements, - /*multiLine*/ - true - ); + const tryBlock = factory2.createBlock(bodyStatements, /*multiLine*/ + true); const bodyCatchBinding = factory2.createUniqueName("e"); - const catchClause = factory2.createCatchClause( - bodyCatchBinding, - factory2.createBlock( - [ - factory2.createExpressionStatement( - factory2.createAssignment( - factory2.createPropertyAccessExpression(envBinding, "error"), - bodyCatchBinding - ) - ), - factory2.createExpressionStatement( - factory2.createAssignment( - factory2.createPropertyAccessExpression(envBinding, "hasError"), - factory2.createTrue() - ) - ) - ], - /*multiLine*/ - true - ) - ); + const catchClause = factory2.createCatchClause(bodyCatchBinding, factory2.createBlock([factory2.createExpressionStatement(factory2.createAssignment(factory2.createPropertyAccessExpression(envBinding, "error"), bodyCatchBinding)), factory2.createExpressionStatement(factory2.createAssignment(factory2.createPropertyAccessExpression(envBinding, "hasError"), factory2.createTrue()))], /*multiLine*/ + true)); let finallyBlock; if (async) { const result = factory2.createUniqueName("result"); - finallyBlock = factory2.createBlock( - [ - factory2.createVariableStatement( - /*modifiers*/ - void 0, - factory2.createVariableDeclarationList([ - factory2.createVariableDeclaration( - result, - /*exclamationToken*/ - void 0, - /*type*/ - void 0, - emitHelpers().createDisposeResourcesHelper(envBinding) - ) - ], 2 /* Const */) - ), - factory2.createIfStatement(result, factory2.createExpressionStatement(factory2.createAwaitExpression(result))) - ], - /*multiLine*/ - true - ); + finallyBlock = factory2.createBlock([factory2.createVariableStatement( /*modifiers*/ + void 0, factory2.createVariableDeclarationList([factory2.createVariableDeclaration(result, /*exclamationToken*/ + void 0, /*type*/ + void 0, emitHelpers().createDisposeResourcesHelper(envBinding))], 2 /* Const */)), factory2.createIfStatement(result, factory2.createExpressionStatement(factory2.createAwaitExpression(result)))], /*multiLine*/ + true); } else { - finallyBlock = factory2.createBlock( - [ - factory2.createExpressionStatement( - emitHelpers().createDisposeResourcesHelper(envBinding) - ) - ], - /*multiLine*/ - true - ); + finallyBlock = factory2.createBlock([factory2.createExpressionStatement(emitHelpers().createDisposeResourcesHelper(envBinding))], /*multiLine*/ + true); } const tryStatement = factory2.createTryStatement(tryBlock, catchClause, finallyBlock); statements.push(tryStatement); @@ -100009,23 +90392,24 @@ ${lanes.join("\n")} function isUsingVariableDeclarationList(node) { return isVariableDeclarationList(node) && getUsingKindOfVariableDeclarationList(node) !== 0 /* None */; } + function getUsingKindOfVariableDeclarationList(node) { return (node.flags & 7 /* BlockScoped */) === 6 /* AwaitUsing */ ? 2 /* Async */ : (node.flags & 7 /* BlockScoped */) === 4 /* Using */ ? 1 /* Sync */ : 0 /* None */; } + function getUsingKindOfVariableStatement(node) { return getUsingKindOfVariableDeclarationList(node.declarationList); } function getUsingKind(statement) { return isVariableStatement(statement) ? getUsingKindOfVariableStatement(statement) : 0 /* None */; } + function getUsingKindOfStatements(statements) { let result = 0 /* None */; for (const statement of statements) { const usingKind = getUsingKind(statement); - if (usingKind === 2 /* Async */) - return 2 /* Async */; - if (usingKind > result) - result = usingKind; + if (usingKind === 2 /* Async */) return 2 /* Async */; + if (usingKind > result) result = usingKind; } return result; } @@ -100033,16 +90417,15 @@ ${lanes.join("\n")} 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; } var init_esnext = __esm({ "src/compiler/transformers/esnext.ts"() { "use strict"; + init_ts2(); } }); @@ -100061,14 +90444,9 @@ ${lanes.join("\n")} if (currentFileState.filenameDeclaration) { return currentFileState.filenameDeclaration.name; } - const declaration = factory2.createVariableDeclaration( - factory2.createUniqueName("_jsxFileName", 16 /* Optimistic */ | 32 /* FileLevel */), - /*exclamationToken*/ - void 0, - /*type*/ - void 0, - factory2.createStringLiteral(currentSourceFile.fileName) - ); + const declaration = factory2.createVariableDeclaration(factory2.createUniqueName("_jsxFileName", 16 /* Optimistic */ | 32 /* FileLevel */), /*exclamationToken*/ + void 0, /*type*/ + void 0, factory2.createStringLiteral(currentSourceFile.fileName)); currentFileState.filenameDeclaration = declaration; return currentFileState.filenameDeclaration.name; } @@ -100090,20 +90468,16 @@ ${lanes.join("\n")} return existing.name; } if (!currentFileState.utilizedImplicitRuntimeImports) { - currentFileState.utilizedImplicitRuntimeImports = /* @__PURE__ */ new Map(); + currentFileState.utilizedImplicitRuntimeImports = /* @__PURE__ */new Map(); } let specifierSourceImports = currentFileState.utilizedImplicitRuntimeImports.get(importSource); if (!specifierSourceImports) { - specifierSourceImports = /* @__PURE__ */ new Map(); + specifierSourceImports = /* @__PURE__ */new Map(); currentFileState.utilizedImplicitRuntimeImports.set(importSource, specifierSourceImports); } const generatedName = factory2.createUniqueName(`_${name}`, 16 /* Optimistic */ | 32 /* FileLevel */ | 64 /* AllowNameSubstitution */); - const specifier = factory2.createImportSpecifier( - /*isTypeOnly*/ - false, - factory2.createIdentifier(name), - generatedName - ); + const specifier = factory2.createImportSpecifier( /*isTypeOnly*/ + false, factory2.createIdentifier(name), generatedName); setIdentifierGeneratedImportReference(generatedName, specifier); specifierSourceImports.set(name, specifier); return generatedName; @@ -100119,68 +90493,33 @@ ${lanes.join("\n")} addEmitHelpers(visited, context.readEmitHelpers()); let statements = visited.statements; if (currentFileState.filenameDeclaration) { - statements = insertStatementAfterCustomPrologue(statements.slice(), factory2.createVariableStatement( - /*modifiers*/ - void 0, - factory2.createVariableDeclarationList([currentFileState.filenameDeclaration], 2 /* Const */) - )); + statements = insertStatementAfterCustomPrologue(statements.slice(), factory2.createVariableStatement( /*modifiers*/ + void 0, factory2.createVariableDeclarationList([currentFileState.filenameDeclaration], 2 /* Const */))); } + if (currentFileState.utilizedImplicitRuntimeImports) { for (const [importSource, importSpecifiersMap] of arrayFrom(currentFileState.utilizedImplicitRuntimeImports.entries())) { if (isExternalModule(node)) { - const importStatement = factory2.createImportDeclaration( - /*modifiers*/ - void 0, - factory2.createImportClause( - /*isTypeOnly*/ - false, - /*name*/ - void 0, - factory2.createNamedImports(arrayFrom(importSpecifiersMap.values())) - ), - factory2.createStringLiteral(importSource), - /*attributes*/ - void 0 - ); - setParentRecursive( - importStatement, - /*incremental*/ - false - ); + const importStatement = factory2.createImportDeclaration( /*modifiers*/ + void 0, factory2.createImportClause( /*isTypeOnly*/ + false, /*name*/ + void 0, factory2.createNamedImports(arrayFrom(importSpecifiersMap.values()))), factory2.createStringLiteral(importSource), /*attributes*/ + void 0); + setParentRecursive(importStatement, /*incremental*/ + false); statements = insertStatementAfterCustomPrologue(statements.slice(), importStatement); } else if (isExternalOrCommonJsModule(node)) { - const requireStatement = factory2.createVariableStatement( - /*modifiers*/ - void 0, - factory2.createVariableDeclarationList([ - factory2.createVariableDeclaration( - factory2.createObjectBindingPattern(arrayFrom(importSpecifiersMap.values(), (s) => factory2.createBindingElement( - /*dotDotDotToken*/ - void 0, - s.propertyName, - s.name - ))), - /*exclamationToken*/ - void 0, - /*type*/ - void 0, - factory2.createCallExpression( - factory2.createIdentifier("require"), - /*typeArguments*/ - void 0, - [factory2.createStringLiteral(importSource)] - ) - ) - ], 2 /* Const */) - ); - setParentRecursive( - requireStatement, - /*incremental*/ - false - ); + const requireStatement = factory2.createVariableStatement( /*modifiers*/ + void 0, factory2.createVariableDeclarationList([factory2.createVariableDeclaration(factory2.createObjectBindingPattern(arrayFrom(importSpecifiersMap.values(), s => factory2.createBindingElement( /*dotDotDotToken*/ + void 0, s.propertyName, s.name))), /*exclamationToken*/ + void 0, /*type*/ + void 0, factory2.createCallExpression(factory2.createIdentifier("require"), /*typeArguments*/ + void 0, [factory2.createStringLiteral(importSource)]))], 2 /* Const */)); + + setParentRecursive(requireStatement, /*incremental*/ + false); statements = insertStatementAfterCustomPrologue(statements.slice(), requireStatement); - } else { - } + } else {} } } if (statements !== visited.statements) { @@ -100199,23 +90538,14 @@ ${lanes.join("\n")} function visitorWorker(node) { switch (node.kind) { case 284 /* JsxElement */: - return visitJsxElement( - node, - /*isChild*/ - false - ); + return visitJsxElement(node, /*isChild*/ + false); case 285 /* JsxSelfClosingElement */: - return visitJsxSelfClosingElement( - node, - /*isChild*/ - false - ); + return visitJsxSelfClosingElement(node, /*isChild*/ + false); case 288 /* JsxFragment */: - return visitJsxFragment( - node, - /*isChild*/ - false - ); + return visitJsxFragment(node, /*isChild*/ + false); case 294 /* JsxExpression */: return visitJsxExpression(node); default: @@ -100229,31 +90559,20 @@ ${lanes.join("\n")} case 294 /* JsxExpression */: return visitJsxExpression(node); case 284 /* JsxElement */: - return visitJsxElement( - node, - /*isChild*/ - true - ); + return visitJsxElement(node, /*isChild*/ + true); case 285 /* JsxSelfClosingElement */: - return visitJsxSelfClosingElement( - node, - /*isChild*/ - true - ); + return visitJsxSelfClosingElement(node, /*isChild*/ + true); case 288 /* JsxFragment */: - return visitJsxFragment( - node, - /*isChild*/ - true - ); + return visitJsxFragment(node, /*isChild*/ + true); default: return Debug.failBadSyntaxKind(node); } } function hasProto(obj) { - return obj.properties.some( - (p) => isPropertyAssignment(p) && (isIdentifier(p.name) && idText(p.name) === "__proto__" || isStringLiteral(p.name) && p.name.text === "__proto__") - ); + return obj.properties.some(p => isPropertyAssignment(p) && (isIdentifier(p.name) && idText(p.name) === "__proto__" || isStringLiteral(p.name) && p.name.text === "__proto__")); } function hasKeyAfterPropsSpread(node) { let spread = false; @@ -100271,34 +90590,19 @@ ${lanes.join("\n")} } function visitJsxElement(node, isChild) { const tagTransform = shouldUseCreateElement(node.openingElement) ? visitJsxOpeningLikeElementCreateElement : visitJsxOpeningLikeElementJSX; - return tagTransform( - node.openingElement, - node.children, - isChild, - /*location*/ - node - ); + return tagTransform(node.openingElement, node.children, isChild, /*location*/ + node); } function visitJsxSelfClosingElement(node, isChild) { const tagTransform = shouldUseCreateElement(node) ? visitJsxOpeningLikeElementCreateElement : visitJsxOpeningLikeElementJSX; - return tagTransform( - node, - /*children*/ - void 0, - isChild, - /*location*/ - node - ); + return tagTransform(node, /*children*/ + void 0, isChild, /*location*/ + node); } function visitJsxFragment(node, isChild) { const tagTransform = currentFileState.importSpecifier === void 0 ? visitJsxOpeningFragmentCreateElement : visitJsxOpeningFragmentJSX; - return tagTransform( - node.openingFragment, - node.children, - isChild, - /*location*/ - node - ); + return tagTransform(node.openingFragment, node.children, isChild, /*location*/ + node); } function convertJsxChildrenToChildrenPropObject(children) { const prop = convertJsxChildrenToChildrenPropAssignment(children); @@ -100316,17 +90620,10 @@ ${lanes.join("\n")} function visitJsxOpeningLikeElementJSX(node, children, isChild, location) { const tagName = getTagName(node); const childrenProp = children && children.length ? convertJsxChildrenToChildrenPropAssignment(children) : void 0; - const keyAttr = find(node.attributes.properties, (p) => !!p.name && isIdentifier(p.name) && p.name.escapedText === "key"); - const attrs = keyAttr ? filter(node.attributes.properties, (p) => p !== keyAttr) : node.attributes.properties; + const keyAttr = find(node.attributes.properties, p => !!p.name && isIdentifier(p.name) && p.name.escapedText === "key"); + const attrs = keyAttr ? filter(node.attributes.properties, p => p !== keyAttr) : node.attributes.properties; const objectProperties = length(attrs) ? transformJsxAttributesToObjectProps(attrs, childrenProp) : factory2.createObjectLiteralExpression(childrenProp ? [childrenProp] : emptyArray); - return visitJsxOpeningLikeElementOrFragmentJSX( - tagName, - objectProperties, - keyAttr, - children || emptyArray, - isChild, - location - ); + return visitJsxOpeningLikeElementOrFragmentJSX(tagName, objectProperties, keyAttr, children || emptyArray, isChild, location); } function visitJsxOpeningLikeElementOrFragmentJSX(tagName, objectProperties, keyAttr, children, isChild, location) { var _a; @@ -100344,23 +90641,12 @@ ${lanes.join("\n")} } args.push(isStaticChildren ? factory2.createTrue() : factory2.createFalse()); const lineCol = getLineAndCharacterOfPosition(originalFile, location.pos); - args.push(factory2.createObjectLiteralExpression([ - factory2.createPropertyAssignment("fileName", getCurrentFileNameExpression()), - factory2.createPropertyAssignment("lineNumber", factory2.createNumericLiteral(lineCol.line + 1)), - factory2.createPropertyAssignment("columnNumber", factory2.createNumericLiteral(lineCol.character + 1)) - ])); + args.push(factory2.createObjectLiteralExpression([factory2.createPropertyAssignment("fileName", getCurrentFileNameExpression()), factory2.createPropertyAssignment("lineNumber", factory2.createNumericLiteral(lineCol.line + 1)), factory2.createPropertyAssignment("columnNumber", factory2.createNumericLiteral(lineCol.character + 1))])); args.push(factory2.createThis()); } } - const element = setTextRange( - factory2.createCallExpression( - getJsxFactoryCallee(isStaticChildren), - /*typeArguments*/ - void 0, - args - ), - location - ); + const element = setTextRange(factory2.createCallExpression(getJsxFactoryCallee(isStaticChildren), /*typeArguments*/ + void 0, args), location); if (isChild) { startOnNewLine(element); } @@ -100370,21 +90656,10 @@ ${lanes.join("\n")} const tagName = getTagName(node); const attrs = node.attributes.properties; const objectProperties = length(attrs) ? transformJsxAttributesToObjectProps(attrs) : factory2.createNull(); - const callee = currentFileState.importSpecifier === void 0 ? createJsxFactoryExpression( - factory2, - context.getEmitResolver().getJsxFactoryEntity(currentSourceFile), - compilerOptions.reactNamespace, - // TODO: GH#18217 - node - ) : getImplicitImportForName("createElement"); - const element = createExpressionForJsxElement( - factory2, - callee, - tagName, - objectProperties, - mapDefined(children, transformJsxChildToExpression), - location - ); + const callee = currentFileState.importSpecifier === void 0 ? createJsxFactoryExpression(factory2, context.getEmitResolver().getJsxFactoryEntity(currentSourceFile), compilerOptions.reactNamespace, + // TODO: GH#18217 + node) : getImplicitImportForName("createElement"); + const element = createExpressionForJsxElement(factory2, callee, tagName, objectProperties, mapDefined(children, transformJsxChildToExpression), location); if (isChild) { startOnNewLine(element); } @@ -100398,27 +90673,13 @@ ${lanes.join("\n")} childrenProps = result; } } - return visitJsxOpeningLikeElementOrFragmentJSX( - getImplicitJsxFragmentReference(), - childrenProps || factory2.createObjectLiteralExpression([]), - /*keyAttr*/ - void 0, - children, - isChild, - location - ); + return visitJsxOpeningLikeElementOrFragmentJSX(getImplicitJsxFragmentReference(), childrenProps || factory2.createObjectLiteralExpression([]), /*keyAttr*/ + void 0, children, isChild, location); } function visitJsxOpeningFragmentCreateElement(node, children, isChild, location) { - const element = createExpressionForJsxFragment( - factory2, - context.getEmitResolver().getJsxFactoryEntity(currentSourceFile), - context.getEmitResolver().getJsxFragmentFactoryEntity(currentSourceFile), - compilerOptions.reactNamespace, - // TODO: GH#18217 - mapDefined(children, transformJsxChildToExpression), - node, - location - ); + const element = createExpressionForJsxFragment(factory2, context.getEmitResolver().getJsxFactoryEntity(currentSourceFile), context.getEmitResolver().getJsxFragmentFactoryEntity(currentSourceFile), compilerOptions.reactNamespace, + // TODO: GH#18217 + mapDefined(children, transformJsxChildToExpression), node, location); if (isChild) { startOnNewLine(element); } @@ -100426,7 +90687,7 @@ ${lanes.join("\n")} } function transformJsxSpreadAttributeToProps(node) { if (isObjectLiteralExpression(node.expression) && !hasProto(node.expression)) { - return sameMap(node.expression.properties, (p) => Debug.checkDefined(visitNode(p, visitor, isObjectLiteralElementLike))); + return sameMap(node.expression.properties, p => Debug.checkDefined(visitNode(p, visitor, isObjectLiteralElementLike))); } return factory2.createSpreadAssignment(Debug.checkDefined(visitNode(node.expression, visitor, isExpression))); } @@ -100435,7 +90696,7 @@ ${lanes.join("\n")} return target && target >= 5 /* ES2018 */ ? factory2.createObjectLiteralExpression(transformJsxAttributesToProps(attrs, children)) : transformJsxAttributesToExpression(attrs, children); } function transformJsxAttributesToProps(attrs, children) { - const props = flatten(spanMap(attrs, isJsxSpreadAttribute, (attrs2, isSpread) => flatten(map(attrs2, (attr) => isSpread ? transformJsxSpreadAttributeToProps(attr) : transformJsxAttributeToObjectLiteralElement(attr))))); + const props = flatten(spanMap(attrs, isJsxSpreadAttribute, (attrs2, isSpread) => flatten(map(attrs2, attr => isSpread ? transformJsxSpreadAttributeToProps(attr) : transformJsxAttributeToObjectLiteralElement(attr))))); if (children) { props.push(children); } @@ -100499,25 +90760,16 @@ ${lanes.join("\n")} return Debug.checkDefined(visitNode(node.expression, visitor, isExpression)); } if (isJsxElement(node)) { - return visitJsxElement( - node, - /*isChild*/ - false - ); + return visitJsxElement(node, /*isChild*/ + false); } if (isJsxSelfClosingElement(node)) { - return visitJsxSelfClosingElement( - node, - /*isChild*/ - false - ); + return visitJsxSelfClosingElement(node, /*isChild*/ + false); } if (isJsxFragment(node)) { - return visitJsxFragment( - node, - /*isChild*/ - false - ); + return visitJsxFragment(node, /*isChild*/ + false); } return Debug.failBadSyntaxKind(node); } @@ -100596,6 +90848,7 @@ ${lanes.join("\n")} var init_jsx = __esm({ "src/compiler/transformers/jsx.ts"() { "use strict"; + init_ts2(); entities = new Map(Object.entries({ quot: 34, @@ -100897,47 +91150,17 @@ ${lanes.join("\n")} if (isElementAccessExpression(left)) { const expressionTemp = factory2.createTempVariable(hoistVariableDeclaration); const argumentExpressionTemp = factory2.createTempVariable(hoistVariableDeclaration); - target = setTextRange( - factory2.createElementAccessExpression( - setTextRange(factory2.createAssignment(expressionTemp, left.expression), left.expression), - setTextRange(factory2.createAssignment(argumentExpressionTemp, left.argumentExpression), left.argumentExpression) - ), - left - ); - value = setTextRange( - factory2.createElementAccessExpression( - expressionTemp, - argumentExpressionTemp - ), - left - ); + target = setTextRange(factory2.createElementAccessExpression(setTextRange(factory2.createAssignment(expressionTemp, left.expression), left.expression), setTextRange(factory2.createAssignment(argumentExpressionTemp, left.argumentExpression), left.argumentExpression)), left); + value = setTextRange(factory2.createElementAccessExpression(expressionTemp, argumentExpressionTemp), left); } else if (isPropertyAccessExpression(left)) { const expressionTemp = factory2.createTempVariable(hoistVariableDeclaration); - target = setTextRange( - factory2.createPropertyAccessExpression( - setTextRange(factory2.createAssignment(expressionTemp, left.expression), left.expression), - left.name - ), - left - ); - value = setTextRange( - factory2.createPropertyAccessExpression( - expressionTemp, - left.name - ), - left - ); + target = setTextRange(factory2.createPropertyAccessExpression(setTextRange(factory2.createAssignment(expressionTemp, left.expression), left.expression), left.name), left); + value = setTextRange(factory2.createPropertyAccessExpression(expressionTemp, left.name), left); } else { target = left; value = left; } - return setTextRange( - factory2.createAssignment( - target, - setTextRange(factory2.createGlobalMethodCall("Math", "pow", [value, right]), node) - ), - node - ); + return setTextRange(factory2.createAssignment(target, setTextRange(factory2.createGlobalMethodCall("Math", "pow", [value, right]), node)), node); } function visitExponentiationExpression(node) { const left = visitNode(node.left, visitor, isExpression); @@ -100948,13 +91171,17 @@ ${lanes.join("\n")} var init_es2016 = __esm({ "src/compiler/transformers/es2016.ts"() { "use strict"; + init_ts2(); } }); // src/compiler/transformers/es2015.ts function createSpreadSegment(kind, expression) { - return { kind, expression }; + return { + kind, + expression + }; } function transformES2015(context) { const { @@ -100976,10 +91203,7 @@ ${lanes.join("\n")} let hierarchyFacts; let taggedTemplateStringDeclarations; function recordTaggedTemplateString(temp) { - taggedTemplateStringDeclarations = append( - taggedTemplateStringDeclarations, - factory2.createVariableDeclaration(temp) - ); + taggedTemplateStringDeclarations = append(taggedTemplateStringDeclarations, factory2.createVariableDeclaration(temp)); } let convertedLoopState; let enabledSubstitutions; @@ -101010,64 +91234,41 @@ ${lanes.join("\n")} return (hierarchyFacts & 8192 /* ConstructorWithSuperCall */) !== 0 && node.kind === 253 /* ReturnStatement */ && !node.expression; } function isOrMayContainReturnCompletion(node) { - return node.transformFlags & 4194304 /* ContainsHoistedDeclarationOrCompletion */ && (isReturnStatement(node) || isIfStatement(node) || isWithStatement(node) || isSwitchStatement(node) || isCaseBlock(node) || isCaseClause(node) || isDefaultClause(node) || isTryStatement(node) || isCatchClause(node) || isLabeledStatement(node) || isIterationStatement( - node, - /*lookInLabeledStatements*/ - false - ) || isBlock(node)); + return node.transformFlags & 4194304 /* ContainsHoistedDeclarationOrCompletion */ && (isReturnStatement(node) || isIfStatement(node) || isWithStatement(node) || isSwitchStatement(node) || isCaseBlock(node) || isCaseClause(node) || isDefaultClause(node) || isTryStatement(node) || isCatchClause(node) || isLabeledStatement(node) || isIterationStatement(node, /*lookInLabeledStatements*/ + false) || isBlock(node)); } function shouldVisitNode(node) { - return (node.transformFlags & 1024 /* ContainsES2015 */) !== 0 || convertedLoopState !== void 0 || hierarchyFacts & 8192 /* ConstructorWithSuperCall */ && isOrMayContainReturnCompletion(node) || isIterationStatement( - node, - /*lookInLabeledStatements*/ - false - ) && shouldConvertIterationStatement(node) || (getInternalEmitFlags(node) & 1 /* TypeScriptClassWrapper */) !== 0; + return (node.transformFlags & 1024 /* ContainsES2015 */) !== 0 || convertedLoopState !== void 0 || hierarchyFacts & 8192 /* ConstructorWithSuperCall */ && isOrMayContainReturnCompletion(node) || isIterationStatement(node, /*lookInLabeledStatements*/ + false) && shouldConvertIterationStatement(node) || (getInternalEmitFlags(node) & 1 /* TypeScriptClassWrapper */) !== 0; } function visitor(node) { - return shouldVisitNode(node) ? visitorWorker( - node, - /*expressionResultIsUnused*/ - false - ) : node; + return shouldVisitNode(node) ? visitorWorker(node, /*expressionResultIsUnused*/ + false) : node; } function visitorWithUnusedExpressionResult(node) { - return shouldVisitNode(node) ? visitorWorker( - node, - /*expressionResultIsUnused*/ - true - ) : node; + return shouldVisitNode(node) ? visitorWorker(node, /*expressionResultIsUnused*/ + true) : node; } function classWrapperStatementVisitor(node) { if (shouldVisitNode(node)) { const original = getOriginalNode(node); if (isPropertyDeclaration(original) && hasStaticModifier(original)) { - const ancestorFacts = enterSubtree( - 32670 /* StaticInitializerExcludes */, - 16449 /* StaticInitializerIncludes */ - ); - const result = visitorWorker( - node, - /*expressionResultIsUnused*/ - false - ); + const ancestorFacts = enterSubtree(32670 /* StaticInitializerExcludes */, 16449 /* StaticInitializerIncludes */); + + const result = visitorWorker(node, /*expressionResultIsUnused*/ + false); exitSubtree(ancestorFacts, 229376 /* FunctionSubtreeExcludes */, 0 /* None */); return result; } - return visitorWorker( - node, - /*expressionResultIsUnused*/ - false - ); + return visitorWorker(node, /*expressionResultIsUnused*/ + false); } return node; } function callExpressionVisitor(node) { if (node.kind === 108 /* SuperKeyword */) { - return visitSuperKeyword( - node, - /*isExpressionOfCall*/ - true - ); + return visitSuperKeyword(node, /*isExpressionOfCall*/ + true); } return visitor(node); } @@ -101098,11 +91299,8 @@ ${lanes.join("\n")} case 269 /* CaseBlock */: return visitCaseBlock(node); case 241 /* Block */: - return visitBlock( - node, - /*isFunctionBody*/ - false - ); + return visitBlock(node, /*isFunctionBody*/ + false); case 252 /* BreakStatement */: case 251 /* ContinueStatement */: return visitBreakOrContinueStatement(node); @@ -101110,29 +91308,17 @@ ${lanes.join("\n")} return visitLabeledStatement(node); case 246 /* DoStatement */: case 247 /* WhileStatement */: - return visitDoOrWhileStatement( - node, - /*outermostLabeledStatement*/ - void 0 - ); + return visitDoOrWhileStatement(node, /*outermostLabeledStatement*/ + void 0); case 248 /* ForStatement */: - return visitForStatement( - node, - /*outermostLabeledStatement*/ - void 0 - ); + return visitForStatement(node, /*outermostLabeledStatement*/ + void 0); case 249 /* ForInStatement */: - return visitForInStatement( - node, - /*outermostLabeledStatement*/ - void 0 - ); + return visitForInStatement(node, /*outermostLabeledStatement*/ + void 0); case 250 /* ForOfStatement */: - return visitForOfStatement( - node, - /*outermostLabeledStatement*/ - void 0 - ); + return visitForOfStatement(node, /*outermostLabeledStatement*/ + void 0); case 244 /* ExpressionStatement */: return visitExpressionStatement(node); case 210 /* ObjectLiteralExpression */: @@ -101173,11 +91359,8 @@ ${lanes.join("\n")} case 230 /* SpreadElement */: return visitSpreadElement(node); case 108 /* SuperKeyword */: - return visitSuperKeyword( - node, - /*isExpressionOfCall*/ - false - ); + return visitSuperKeyword(node, /*isExpressionOfCall*/ + false); case 110 /* ThisKeyword */: return visitThisKeyword(node); case 236 /* MetaProperty */: @@ -101202,30 +91385,17 @@ ${lanes.join("\n")} const prologue = []; const statements = []; startLexicalEnvironment(); - const statementOffset = factory2.copyPrologue( - node.statements, - prologue, - /*ensureUseStrict*/ - false, - visitor - ); + const statementOffset = factory2.copyPrologue(node.statements, prologue, /*ensureUseStrict*/ + false, visitor); addRange(statements, visitNodes2(node.statements, visitor, isStatement, statementOffset)); if (taggedTemplateStringDeclarations) { - statements.push( - factory2.createVariableStatement( - /*modifiers*/ - void 0, - factory2.createVariableDeclarationList(taggedTemplateStringDeclarations) - ) - ); + statements.push(factory2.createVariableStatement( /*modifiers*/ + void 0, factory2.createVariableDeclarationList(taggedTemplateStringDeclarations))); } factory2.mergeLexicalEnvironment(prologue, endLexicalEnvironment()); insertCaptureThisForNodeIfNeeded(prologue, node); exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */); - return factory2.updateSourceFile( - node, - setTextRange(factory2.createNodeArray(concatenate(prologue, statements)), node.statements) - ); + return factory2.updateSourceFile(node, setTextRange(factory2.createNodeArray(concatenate(prologue, statements)), node.statements)); } function visitSwitchStatement(node) { if (convertedLoopState !== void 0) { @@ -101249,22 +91419,14 @@ ${lanes.join("\n")} function createCapturedThis() { return factory2.createUniqueName("_this", 16 /* Optimistic */ | 32 /* FileLevel */); } + function visitReturnStatement(node) { if (convertedLoopState) { convertedLoopState.nonLocalJumps |= 8 /* Return */; if (isReturnVoidStatementInConstructorWithCapturedSuper(node)) { node = returnCapturedThis(node); } - return factory2.createReturnStatement( - factory2.createObjectLiteralExpression( - [ - factory2.createPropertyAssignment( - factory2.createIdentifier("value"), - node.expression ? Debug.checkDefined(visitNode(node.expression, visitor, isExpression)) : factory2.createVoidZero() - ) - ] - ) - ); + return factory2.createReturnStatement(factory2.createObjectLiteralExpression([factory2.createPropertyAssignment(factory2.createIdentifier("value"), node.expression ? Debug.checkDefined(visitNode(node.expression, visitor, isExpression)) : factory2.createVoidZero())])); } else if (isReturnVoidStatementInConstructorWithCapturedSuper(node)) { return returnCapturedThis(node); } @@ -101275,6 +91437,7 @@ ${lanes.join("\n")} if (hierarchyFacts & 2 /* ArrowFunction */ && !(hierarchyFacts & 16384 /* StaticInitializer */)) { hierarchyFacts |= 131072 /* CapturedLexicalThis */; } + if (convertedLoopState) { if (hierarchyFacts & 2 /* ArrowFunction */) { convertedLoopState.containsLexicalThis = true; @@ -101294,13 +91457,7 @@ ${lanes.join("\n")} } } if (node.flags & 256 /* IdentifierHasExtendedUnicodeEscape */) { - return setOriginalNode( - setTextRange( - factory2.createIdentifier(unescapeLeadingUnderscores(node.escapedText)), - node - ), - node - ); + return setOriginalNode(setTextRange(factory2.createIdentifier(unescapeLeadingUnderscores(node.escapedText)), node), node); } return node; } @@ -101322,22 +91479,12 @@ ${lanes.join("\n")} } else { if (node.kind === 252 /* BreakStatement */) { labelMarker = `break-${label.escapedText}`; - setLabeledJump( - convertedLoopState, - /*isBreak*/ - true, - idText(label), - labelMarker - ); + setLabeledJump(convertedLoopState, /*isBreak*/ + true, idText(label), labelMarker); } else { labelMarker = `continue-${label.escapedText}`; - setLabeledJump( - convertedLoopState, - /*isBreak*/ - false, - idText(label), - labelMarker - ); + setLabeledJump(convertedLoopState, /*isBreak*/ + false, idText(label), labelMarker); } } let returnExpression = factory2.createStringLiteral(labelMarker); @@ -101360,25 +91507,14 @@ ${lanes.join("\n")} return visitEachChild(node, visitor, context); } function visitClassDeclaration(node) { - const variable = factory2.createVariableDeclaration( - factory2.getLocalName( - node, - /*allowComments*/ - true - ), - /*exclamationToken*/ - void 0, - /*type*/ - void 0, - transformClassLikeDeclarationToExpression(node) - ); + const variable = factory2.createVariableDeclaration(factory2.getLocalName(node, /*allowComments*/ + true), /*exclamationToken*/ + void 0, /*type*/ + void 0, transformClassLikeDeclarationToExpression(node)); setOriginalNode(variable, node); const statements = []; - const statement = factory2.createVariableStatement( - /*modifiers*/ - void 0, - factory2.createVariableDeclarationList([variable]) - ); + const statement = factory2.createVariableStatement( /*modifiers*/ + void 0, factory2.createVariableDeclarationList([variable])); setOriginalNode(statement, node); setTextRange(statement, node); startOnNewLine(statement); @@ -101398,26 +91534,14 @@ ${lanes.join("\n")} enableSubstitutionsForBlockScopedBindings(); } const extendsClauseElement = getClassExtendsHeritageElement(node); - const classFunction = factory2.createFunctionExpression( - /*modifiers*/ - void 0, - /*asteriskToken*/ - void 0, - /*name*/ - void 0, - /*typeParameters*/ - void 0, - extendsClauseElement ? [factory2.createParameterDeclaration( - /*modifiers*/ - void 0, - /*dotDotDotToken*/ - void 0, - createSyntheticSuper() - )] : [], - /*type*/ - void 0, - transformClassBody(node, extendsClauseElement) - ); + const classFunction = factory2.createFunctionExpression( /*modifiers*/ + void 0, /*asteriskToken*/ + void 0, /*name*/ + void 0, /*typeParameters*/ + void 0, extendsClauseElement ? [factory2.createParameterDeclaration( /*modifiers*/ + void 0, /*dotDotDotToken*/ + void 0, createSyntheticSuper())] : [], /*type*/ + void 0, transformClassBody(node, extendsClauseElement)); setEmitFlags(classFunction, getEmitFlags(node) & 131072 /* Indented */ | 1048576 /* ReuseTempVariableScope */); const inner = factory2.createPartiallyEmittedExpression(classFunction); setTextRangeEnd(inner, node.end); @@ -101425,14 +91549,8 @@ ${lanes.join("\n")} const outer = factory2.createPartiallyEmittedExpression(inner); setTextRangeEnd(outer, skipTrivia(currentText, node.pos)); setEmitFlags(outer, 3072 /* NoComments */); - const result = factory2.createParenthesizedExpression( - factory2.createCallExpression( - outer, - /*typeArguments*/ - void 0, - extendsClauseElement ? [Debug.checkDefined(visitNode(extendsClauseElement.expression, visitor, isExpression))] : [] - ) - ); + const result = factory2.createParenthesizedExpression(factory2.createCallExpression(outer, /*typeArguments*/ + void 0, extendsClauseElement ? [Debug.checkDefined(visitNode(extendsClauseElement.expression, visitor, isExpression))] : [])); addSyntheticLeadingComment(result, 3 /* MultiLineCommentTrivia */, "* @class "); return result; } @@ -101453,29 +91571,16 @@ ${lanes.join("\n")} setEmitFlags(statement, 3072 /* NoComments */ | 768 /* NoTokenSourceMaps */); statements.push(statement); insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment()); - const block = factory2.createBlock( - setTextRange( - factory2.createNodeArray(statements), - /*location*/ - node.members - ), - /*multiLine*/ - true - ); + const block = factory2.createBlock(setTextRange(factory2.createNodeArray(statements), /*location*/ + node.members), /*multiLine*/ + true); setEmitFlags(block, 3072 /* NoComments */); return block; } function addExtendsHelperIfNeeded(statements, node, extendsClauseElement) { if (extendsClauseElement) { - statements.push( - setTextRange( - factory2.createExpressionStatement( - emitHelpers().createExtendsHelper(factory2.getInternalName(node)) - ), - /*location*/ - extendsClauseElement - ) - ); + statements.push(setTextRange(factory2.createExpressionStatement(emitHelpers().createExtendsHelper(factory2.getInternalName(node))), /*location*/ + extendsClauseElement)); } } function addConstructor(statements, node, name, extendsClauseElement) { @@ -101484,23 +91589,16 @@ ${lanes.join("\n")} const ancestorFacts = enterSubtree(32662 /* ConstructorExcludes */, 73 /* ConstructorIncludes */); const constructor = getFirstConstructorWithBody(node); const hasSynthesizedSuper = hasSynthesizedDefaultSuperCall(constructor, extendsClauseElement !== void 0); - const constructorFunction = factory2.createFunctionDeclaration( - /*modifiers*/ - void 0, - /*asteriskToken*/ - void 0, - name, - /*typeParameters*/ - void 0, - transformConstructorParameters(constructor, hasSynthesizedSuper), - /*type*/ - void 0, - transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper) - ); + const constructorFunction = factory2.createFunctionDeclaration( /*modifiers*/ + void 0, /*asteriskToken*/ + void 0, name, /*typeParameters*/ + void 0, transformConstructorParameters(constructor, hasSynthesizedSuper), /*type*/ + void 0, transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper)); setTextRange(constructorFunction, constructor || node); if (extendsClauseElement) { setEmitFlags(constructorFunction, 16 /* CapturesThis */); } + statements.push(constructorFunction); exitSubtree(ancestorFacts, 229376 /* FunctionSubtreeExcludes */, 0 /* None */); convertedLoopState = savedConvertedLoopState; @@ -101517,17 +91615,14 @@ ${lanes.join("\n")} } const statementsArray = factory2.createNodeArray(statements); setTextRange(statementsArray, node.members); - const block = factory2.createBlock( - statementsArray, - /*multiLine*/ - true - ); + const block = factory2.createBlock(statementsArray, /*multiLine*/ + true); setTextRange(block, node); setEmitFlags(block, 3072 /* NoComments */); return block; } function isUninitializedVariableStatement(node) { - return isVariableStatement(node) && every(node.declarationList.declarations, (decl) => isIdentifier(decl.name) && !decl.initializer); + return isVariableStatement(node) && every(node.declarationList.declarations, decl => isIdentifier(decl.name) && !decl.initializer); } function containsSuperCall(node) { if (isSuperCall(node)) { @@ -101546,32 +91641,29 @@ ${lanes.join("\n")} case 177 /* GetAccessor */: case 178 /* SetAccessor */: case 174 /* MethodDeclaration */: - case 172 /* PropertyDeclaration */: { - const named = node; - if (isComputedPropertyName(named.name)) { - return !!forEachChild(named.name, containsSuperCall); + case 172 /* PropertyDeclaration */: + { + const named = node; + if (isComputedPropertyName(named.name)) { + return !!forEachChild(named.name, containsSuperCall); + } + return false; } - return false; - } } return !!forEachChild(node, containsSuperCall); } 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(); - const standardPrologueEnd = factory2.copyStandardPrologue( - constructor.body.statements, - prologue, - /*statementOffset*/ - 0 - ); + const standardPrologueEnd = factory2.copyStandardPrologue(constructor.body.statements, prologue, /*statementOffset*/ + 0); if (hasSynthesizedSuper || containsSuperCall(constructor.body)) { hierarchyFacts |= 8192 /* ConstructorWithSuperCall */; } + addRange(statements, visitNodes2(constructor.body.statements, visitor, isStatement, standardPrologueEnd)); const mayReplaceThis = isDerivedClass || hierarchyFacts & 8192 /* ConstructorWithSuperCall */; addDefaultValueAssignmentsIfNeeded2(prologue, constructor); @@ -101586,20 +91678,9 @@ ${lanes.join("\n")} if (mayReplaceThis && !isSufficientlyCoveredByReturnStatements(constructor.body)) { statements.push(factory2.createReturnStatement(createCapturedThis())); } - const body = factory2.createBlock( - setTextRange( - factory2.createNodeArray( - [ - ...prologue, - ...statements - ] - ), - /*location*/ - constructor.body.statements - ), - /*multiLine*/ - true - ); + const body = factory2.createBlock(setTextRange(factory2.createNodeArray([...prologue, ...statements]), /*location*/ + constructor.body.statements), /*multiLine*/ + true); setTextRange(body, constructor.body); return simplifyConstructor(body, constructor.body, hasSynthesizedSuper); } @@ -101616,15 +91697,13 @@ ${lanes.join("\n")} return isVariableDeclaration(node) && isCapturedThis(node.name) && !!node.initializer; } function isThisCapturingAssignment(node) { - return isAssignmentExpression( - node, - /*excludeCompoundAssignment*/ - true - ) && isCapturedThis(node.left); + return isAssignmentExpression(node, /*excludeCompoundAssignment*/ + true) && isCapturedThis(node.left); } function isTransformedSuperCall(node) { return isCallExpression(node) && isPropertyAccessExpression(node.expression) && isSyntheticSuper(node.expression.expression) && isIdentifier(node.expression.name) && (idText(node.expression.name) === "call" || idText(node.expression.name) === "apply") && node.arguments.length >= 1 && node.arguments[0].kind === 110 /* ThisKeyword */; } + function isTransformedSuperCallWithFallback(node) { return isBinaryExpression(node) && node.operatorToken.kind === 57 /* BarBarToken */ && node.right.kind === 110 /* ThisKeyword */ && isTransformedSuperCall(node.left); } @@ -101673,28 +91752,21 @@ ${lanes.join("\n")} if (isThisCapturingAssignment(expression)) { expression = expression.right; } - const newVarDecl = factory2.updateVariableDeclaration( - varDecl, - varDecl.name, - /*exclamationToken*/ - void 0, - /*type*/ - void 0, - expression - ); + const newVarDecl = factory2.updateVariableDeclaration(varDecl, varDecl.name, /*exclamationToken*/ + void 0, /*type*/ + void 0, expression); const newDeclList = factory2.updateVariableDeclarationList(statement.declarationList, [newVarDecl]); const newVarStatement = factory2.createVariableStatement(statement.modifiers, newDeclList); setOriginalNode(newVarStatement, following); setTextRange(newVarStatement, following); - const newStatements = factory2.createNodeArray([ - ...body.statements.slice(0, thisCaptureStatementIndex), - // copy statements preceding to `var _this` - ...body.statements.slice(thisCaptureStatementIndex + 1, superCallIndex), - // copy intervening temp variables - newVarStatement, - ...body.statements.slice(superCallIndex + 1) - // copy statements following `super.call(this, ...)` + const newStatements = factory2.createNodeArray([...body.statements.slice(0, thisCaptureStatementIndex), + // copy statements preceding to `var _this` + ...body.statements.slice(thisCaptureStatementIndex + 1, superCallIndex), + // copy intervening temp variables + newVarStatement, ...body.statements.slice(superCallIndex + 1) + // copy statements following `super.call(this, ...)` ]); + setTextRange(newStatements, body.statements); return factory2.updateBlock(body, newStatements); } @@ -101717,10 +91789,7 @@ ${lanes.join("\n")} } else if (canElideThisCapturingVariable && isThisCapturingVariableStatement(preceding)) { const varDecl = preceding.declarationList.declarations[0]; if (isTransformedSuperCallLike(skipOuterExpressions(varDecl.initializer))) { - expression = factory2.createAssignment( - createCapturedThis(), - varDecl.initializer - ); + expression = factory2.createAssignment(createCapturedThis(), varDecl.initializer); } } if (!expression) { @@ -101729,13 +91798,12 @@ ${lanes.join("\n")} const newReturnStatement = factory2.createReturnStatement(expression); setOriginalNode(newReturnStatement, preceding); setTextRange(newReturnStatement, preceding); - const newStatements = factory2.createNodeArray([ - ...body.statements.slice(0, i - 1), - // copy all statements preceding `_super.call(this, ...)` - newReturnStatement, - ...body.statements.slice(i + 1) - // copy all statements following `return _this;` + const newStatements = factory2.createNodeArray([...body.statements.slice(0, i - 1), + // copy all statements preceding `_super.call(this, ...)` + newReturnStatement, ...body.statements.slice(i + 1) + // copy all statements following `return _this;` ]); + setTextRange(newStatements, body.statements); return factory2.updateBlock(body, newStatements); } @@ -101761,13 +91829,14 @@ ${lanes.join("\n")} case 177 /* GetAccessor */: case 178 /* SetAccessor */: case 174 /* MethodDeclaration */: - case 172 /* PropertyDeclaration */: { - const named = node; - if (isComputedPropertyName(named.name)) { - return factory2.replacePropertyName(named, visitEachChild(named.name, elideUnusedThisCaptureWorker, nullTransformationContext)); + case 172 /* PropertyDeclaration */: + { + const named = node; + if (isComputedPropertyName(named.name)) { + return factory2.replacePropertyName(named, visitEachChild(named.name, elideUnusedThisCaptureWorker, nullTransformationContext)); + } + return node; } - return node; - } } return visitEachChild(node, elideUnusedThisCaptureWorker, nullTransformationContext); } @@ -101784,13 +91853,7 @@ ${lanes.join("\n")} } function injectSuperPresenceCheckWorker(node) { if (isTransformedSuperCall(node) && node.arguments.length === 2 && isIdentifier(node.arguments[1]) && idText(node.arguments[1]) === "arguments") { - return factory2.createLogicalAnd( - factory2.createStrictInequality( - createSyntheticSuper(), - factory2.createNull() - ), - node - ); + return factory2.createLogicalAnd(factory2.createStrictInequality(createSyntheticSuper(), factory2.createNull()), node); } switch (node.kind) { case 219 /* ArrowFunction */: @@ -101802,13 +91865,14 @@ ${lanes.join("\n")} case 177 /* GetAccessor */: case 178 /* SetAccessor */: case 174 /* MethodDeclaration */: - case 172 /* PropertyDeclaration */: { - const named = node; - if (isComputedPropertyName(named.name)) { - return factory2.replacePropertyName(named, visitEachChild(named.name, injectSuperPresenceCheckWorker, nullTransformationContext)); + case 172 /* PropertyDeclaration */: + { + const named = node; + if (isComputedPropertyName(named.name)) { + return factory2.replacePropertyName(named, visitEachChild(named.name, injectSuperPresenceCheckWorker, nullTransformationContext)); + } + return node; } - return node; - } } return visitEachChild(node, injectSuperPresenceCheckWorker, nullTransformationContext); } @@ -101846,69 +91910,31 @@ ${lanes.join("\n")} function createActualThis() { return setEmitFlags(factory2.createThis(), 8 /* NoSubstitution */); } + function createDefaultSuperCallOrThis() { - return factory2.createLogicalOr( - factory2.createLogicalAnd( - factory2.createStrictInequality( - createSyntheticSuper(), - factory2.createNull() - ), - factory2.createFunctionApplyCall( - createSyntheticSuper(), - createActualThis(), - factory2.createIdentifier("arguments") - ) - ), - createActualThis() - ); + return factory2.createLogicalOr(factory2.createLogicalAnd(factory2.createStrictInequality(createSyntheticSuper(), factory2.createNull()), factory2.createFunctionApplyCall(createSyntheticSuper(), createActualThis(), factory2.createIdentifier("arguments"))), createActualThis()); } function visitParameter(node) { if (node.dotDotDotToken) { return void 0; } else if (isBindingPattern(node.name)) { - return setOriginalNode( - setTextRange( - factory2.createParameterDeclaration( - /*modifiers*/ - void 0, - /*dotDotDotToken*/ - void 0, - factory2.getGeneratedNameForNode(node), - /*questionToken*/ - void 0, - /*type*/ - void 0, - /*initializer*/ - void 0 - ), - /*location*/ - node - ), - /*original*/ - node - ); + return setOriginalNode(setTextRange(factory2.createParameterDeclaration( /*modifiers*/ + void 0, /*dotDotDotToken*/ + void 0, factory2.getGeneratedNameForNode(node), /*questionToken*/ + void 0, /*type*/ + void 0, /*initializer*/ + void 0), /*location*/ + node), /*original*/ + node); } else if (node.initializer) { - return setOriginalNode( - setTextRange( - factory2.createParameterDeclaration( - /*modifiers*/ - void 0, - /*dotDotDotToken*/ - void 0, - node.name, - /*questionToken*/ - void 0, - /*type*/ - void 0, - /*initializer*/ - void 0 - ), - /*location*/ - node - ), - /*original*/ - node - ); + return setOriginalNode(setTextRange(factory2.createParameterDeclaration( /*modifiers*/ + void 0, /*dotDotDotToken*/ + void 0, node.name, /*questionToken*/ + void 0, /*type*/ + void 0, /*initializer*/ + void 0), /*location*/ + node), /*original*/ + node); } else { return node; } @@ -101922,7 +91948,11 @@ ${lanes.join("\n")} } let added = false; for (const parameter of node.parameters) { - const { name, initializer, dotDotDotToken } = parameter; + const { + name, + initializer, + dotDotDotToken + } = parameter; if (dotDotDotToken) { continue; } @@ -101937,69 +91967,23 @@ ${lanes.join("\n")} } function insertDefaultValueAssignmentForBindingPattern(statements, parameter, name, initializer) { if (name.elements.length > 0) { - insertStatementAfterCustomPrologue( - statements, - setEmitFlags( - factory2.createVariableStatement( - /*modifiers*/ - void 0, - factory2.createVariableDeclarationList( - flattenDestructuringBinding( - parameter, - visitor, - context, - 0 /* All */, - factory2.getGeneratedNameForNode(parameter) - ) - ) - ), - 2097152 /* CustomPrologue */ - ) - ); + insertStatementAfterCustomPrologue(statements, setEmitFlags(factory2.createVariableStatement( /*modifiers*/ + void 0, factory2.createVariableDeclarationList(flattenDestructuringBinding(parameter, visitor, context, 0 /* All */, factory2.getGeneratedNameForNode(parameter)))), 2097152 /* CustomPrologue */)); + return true; } else if (initializer) { - insertStatementAfterCustomPrologue( - statements, - setEmitFlags( - factory2.createExpressionStatement( - factory2.createAssignment( - factory2.getGeneratedNameForNode(parameter), - Debug.checkDefined(visitNode(initializer, visitor, isExpression)) - ) - ), - 2097152 /* CustomPrologue */ - ) - ); + insertStatementAfterCustomPrologue(statements, setEmitFlags(factory2.createExpressionStatement(factory2.createAssignment(factory2.getGeneratedNameForNode(parameter), Debug.checkDefined(visitNode(initializer, visitor, isExpression)))), 2097152 /* CustomPrologue */)); + return true; } return false; } function insertDefaultValueAssignmentForInitializer(statements, parameter, name, initializer) { initializer = Debug.checkDefined(visitNode(initializer, visitor, isExpression)); - const statement = factory2.createIfStatement( - factory2.createTypeCheck(factory2.cloneNode(name), "undefined"), - setEmitFlags( - setTextRange( - factory2.createBlock([ - factory2.createExpressionStatement( - setEmitFlags( - setTextRange( - factory2.createAssignment( - // TODO(rbuckton): Does this need to be parented? - setEmitFlags(setParent(setTextRange(factory2.cloneNode(name), name), name.parent), 96 /* NoSourceMap */), - setEmitFlags(initializer, 96 /* NoSourceMap */ | getEmitFlags(initializer) | 3072 /* NoComments */) - ), - parameter - ), - 3072 /* NoComments */ - ) - ) - ]), - parameter - ), - 1 /* SingleLine */ | 64 /* NoTrailingSourceMap */ | 768 /* NoTokenSourceMaps */ | 3072 /* NoComments */ - ) - ); + const statement = factory2.createIfStatement(factory2.createTypeCheck(factory2.cloneNode(name), "undefined"), setEmitFlags(setTextRange(factory2.createBlock([factory2.createExpressionStatement(setEmitFlags(setTextRange(factory2.createAssignment( + // TODO(rbuckton): Does this need to be parented? + setEmitFlags(setParent(setTextRange(factory2.cloneNode(name), name), name.parent), 96 /* NoSourceMap */), setEmitFlags(initializer, 96 /* NoSourceMap */ | getEmitFlags(initializer) | 3072 /* NoComments */)), parameter), 3072 /* NoComments */))]), parameter), 1 /* SingleLine */ | 64 /* NoTrailingSourceMap */ | 768 /* NoTokenSourceMaps */ | 3072 /* NoComments */)); + startOnNewLine(statement); setTextRange(statement, parameter); setEmitFlags(statement, 768 /* NoTokenSourceMaps */ | 64 /* NoTrailingSourceMap */ | 2097152 /* CustomPrologue */ | 3072 /* NoComments */); @@ -102014,97 +91998,30 @@ ${lanes.join("\n")} if (!shouldAddRestParameter(parameter, inConstructorWithSynthesizedSuper)) { return false; } - const declarationName = parameter.name.kind === 80 /* Identifier */ ? setParent(setTextRange(factory2.cloneNode(parameter.name), parameter.name), parameter.name.parent) : factory2.createTempVariable( - /*recordTempVariable*/ - void 0 - ); + const declarationName = parameter.name.kind === 80 /* Identifier */ ? setParent(setTextRange(factory2.cloneNode(parameter.name), parameter.name), parameter.name.parent) : factory2.createTempVariable( /*recordTempVariable*/ + void 0); setEmitFlags(declarationName, 96 /* NoSourceMap */); const expressionName = parameter.name.kind === 80 /* Identifier */ ? factory2.cloneNode(parameter.name) : declarationName; const restIndex = node.parameters.length - 1; const temp = factory2.createLoopVariable(); - prologueStatements.push( - setEmitFlags( - setTextRange( - factory2.createVariableStatement( - /*modifiers*/ - void 0, - factory2.createVariableDeclarationList([ - factory2.createVariableDeclaration( - declarationName, - /*exclamationToken*/ - void 0, - /*type*/ - void 0, - factory2.createArrayLiteralExpression([]) - ) - ]) - ), - /*location*/ - parameter - ), - 2097152 /* CustomPrologue */ - ) - ); - const forStatement = factory2.createForStatement( - setTextRange( - factory2.createVariableDeclarationList([ - factory2.createVariableDeclaration( - temp, - /*exclamationToken*/ - void 0, - /*type*/ - void 0, - factory2.createNumericLiteral(restIndex) - ) - ]), - parameter - ), - setTextRange( - factory2.createLessThan( - temp, - factory2.createPropertyAccessExpression(factory2.createIdentifier("arguments"), "length") - ), - parameter - ), - setTextRange(factory2.createPostfixIncrement(temp), parameter), - factory2.createBlock([ - startOnNewLine( - setTextRange( - factory2.createExpressionStatement( - factory2.createAssignment( - factory2.createElementAccessExpression( - expressionName, - restIndex === 0 ? temp : factory2.createSubtract(temp, factory2.createNumericLiteral(restIndex)) - ), - factory2.createElementAccessExpression(factory2.createIdentifier("arguments"), temp) - ) - ), - /*location*/ - parameter - ) - ) - ]) - ); + prologueStatements.push(setEmitFlags(setTextRange(factory2.createVariableStatement( /*modifiers*/ + void 0, factory2.createVariableDeclarationList([factory2.createVariableDeclaration(declarationName, /*exclamationToken*/ + void 0, /*type*/ + void 0, factory2.createArrayLiteralExpression([]))])), /*location*/ + parameter), 2097152 /* CustomPrologue */)); + + const forStatement = factory2.createForStatement(setTextRange(factory2.createVariableDeclarationList([factory2.createVariableDeclaration(temp, /*exclamationToken*/ + void 0, /*type*/ + void 0, factory2.createNumericLiteral(restIndex))]), parameter), setTextRange(factory2.createLessThan(temp, factory2.createPropertyAccessExpression(factory2.createIdentifier("arguments"), "length")), parameter), setTextRange(factory2.createPostfixIncrement(temp), parameter), factory2.createBlock([startOnNewLine(setTextRange(factory2.createExpressionStatement(factory2.createAssignment(factory2.createElementAccessExpression(expressionName, restIndex === 0 ? temp : factory2.createSubtract(temp, factory2.createNumericLiteral(restIndex))), factory2.createElementAccessExpression(factory2.createIdentifier("arguments"), temp))), /*location*/ + parameter))])); setEmitFlags(forStatement, 2097152 /* CustomPrologue */); startOnNewLine(forStatement); prologueStatements.push(forStatement); if (parameter.name.kind !== 80 /* Identifier */) { - prologueStatements.push( - setEmitFlags( - setTextRange( - factory2.createVariableStatement( - /*modifiers*/ - void 0, - factory2.createVariableDeclarationList( - flattenDestructuringBinding(parameter, visitor, context, 0 /* All */, expressionName) - ) - ), - parameter - ), - 2097152 /* CustomPrologue */ - ) - ); + prologueStatements.push(setEmitFlags(setTextRange(factory2.createVariableStatement( /*modifiers*/ + void 0, factory2.createVariableDeclarationList(flattenDestructuringBinding(parameter, visitor, context, 0 /* All */, expressionName))), parameter), 2097152 /* CustomPrologue */)); } + insertStatementsAfterCustomPrologue(statements, prologueStatements); return true; } @@ -102117,20 +92034,10 @@ ${lanes.join("\n")} } function insertCaptureThisForNode(statements, node, initializer) { enableSubstitutionsForCapturedThis(); - const captureThisStatement = factory2.createVariableStatement( - /*modifiers*/ - void 0, - factory2.createVariableDeclarationList([ - factory2.createVariableDeclaration( - createCapturedThis(), - /*exclamationToken*/ - void 0, - /*type*/ - void 0, - initializer - ) - ]) - ); + const captureThisStatement = factory2.createVariableStatement( /*modifiers*/ + void 0, factory2.createVariableDeclarationList([factory2.createVariableDeclaration(createCapturedThis(), /*exclamationToken*/ + void 0, /*type*/ + void 0, initializer)])); setEmitFlags(captureThisStatement, 3072 /* NoComments */ | 2097152 /* CustomPrologue */); setSourceMapRange(captureThisStatement, node); insertStatementAfterCustomPrologue(statements, captureThisStatement); @@ -102147,50 +92054,21 @@ ${lanes.join("\n")} newTarget = factory2.createVoidZero(); break; case 176 /* Constructor */: - newTarget = factory2.createPropertyAccessExpression( - setEmitFlags(factory2.createThis(), 8 /* NoSubstitution */), - "constructor" - ); + newTarget = factory2.createPropertyAccessExpression(setEmitFlags(factory2.createThis(), 8 /* NoSubstitution */), "constructor"); break; case 262 /* FunctionDeclaration */: case 218 /* FunctionExpression */: - newTarget = factory2.createConditionalExpression( - factory2.createLogicalAnd( - setEmitFlags(factory2.createThis(), 8 /* NoSubstitution */), - factory2.createBinaryExpression( - setEmitFlags(factory2.createThis(), 8 /* NoSubstitution */), - 104 /* InstanceOfKeyword */, - factory2.getLocalName(node) - ) - ), - /*questionToken*/ - void 0, - factory2.createPropertyAccessExpression( - setEmitFlags(factory2.createThis(), 8 /* NoSubstitution */), - "constructor" - ), - /*colonToken*/ - void 0, - factory2.createVoidZero() - ); + newTarget = factory2.createConditionalExpression(factory2.createLogicalAnd(setEmitFlags(factory2.createThis(), 8 /* NoSubstitution */), factory2.createBinaryExpression(setEmitFlags(factory2.createThis(), 8 /* NoSubstitution */), 104 /* InstanceOfKeyword */, factory2.getLocalName(node))), /*questionToken*/ + void 0, factory2.createPropertyAccessExpression(setEmitFlags(factory2.createThis(), 8 /* NoSubstitution */), "constructor"), /*colonToken*/ + void 0, factory2.createVoidZero()); break; default: return Debug.failBadSyntaxKind(node); } - const captureNewTargetStatement = factory2.createVariableStatement( - /*modifiers*/ - void 0, - factory2.createVariableDeclarationList([ - factory2.createVariableDeclaration( - factory2.createUniqueName("_newTarget", 16 /* Optimistic */ | 32 /* FileLevel */), - /*exclamationToken*/ - void 0, - /*type*/ - void 0, - newTarget - ) - ]) - ); + const captureNewTargetStatement = factory2.createVariableStatement( /*modifiers*/ + void 0, factory2.createVariableDeclarationList([factory2.createVariableDeclaration(factory2.createUniqueName("_newTarget", 16 /* Optimistic */ | 32 /* FileLevel */), /*exclamationToken*/ + void 0, /*type*/ + void 0, newTarget)])); setEmitFlags(captureNewTargetStatement, 3072 /* NoComments */ | 2097152 /* CustomPrologue */); insertStatementAfterCustomPrologue(statements, captureNewTargetStatement); } @@ -102227,55 +92105,46 @@ ${lanes.join("\n")} function transformClassMethodDeclarationToStatement(receiver, member, container) { const commentRange = getCommentRange(member); const sourceMapRange = getSourceMapRange(member); - const memberFunction = transformFunctionLikeToExpression( - member, - /*location*/ - member, - /*name*/ - void 0, - container - ); + const memberFunction = transformFunctionLikeToExpression(member, /*location*/ + member, /*name*/ + void 0, container); const propertyName = visitNode(member.name, visitor, isPropertyName); Debug.assert(propertyName); let e; if (!isPrivateIdentifier(propertyName) && getUseDefineForClassFields(context.getCompilerOptions())) { const name = isComputedPropertyName(propertyName) ? propertyName.expression : isIdentifier(propertyName) ? factory2.createStringLiteral(unescapeLeadingUnderscores(propertyName.escapedText)) : propertyName; - e = factory2.createObjectDefinePropertyCall(receiver, name, factory2.createPropertyDescriptor({ value: memberFunction, enumerable: false, writable: true, configurable: true })); + e = factory2.createObjectDefinePropertyCall(receiver, name, factory2.createPropertyDescriptor({ + value: memberFunction, + enumerable: false, + writable: true, + configurable: true + })); } else { - const memberName = createMemberAccessForPropertyName( - factory2, - receiver, - propertyName, - /*location*/ - member.name - ); + const memberName = createMemberAccessForPropertyName(factory2, receiver, propertyName, /*location*/ + member.name); e = factory2.createAssignment(memberName, memberFunction); } setEmitFlags(memberFunction, 3072 /* NoComments */); setSourceMapRange(memberFunction, sourceMapRange); - const statement = setTextRange( - factory2.createExpressionStatement(e), - /*location*/ - member - ); + const statement = setTextRange(factory2.createExpressionStatement(e), /*location*/ + member); setOriginalNode(statement, member); setCommentRange(statement, commentRange); setEmitFlags(statement, 96 /* NoSourceMap */); return statement; } function transformAccessorsToStatement(receiver, accessors, container) { - const statement = factory2.createExpressionStatement(transformAccessorsToExpression( - receiver, - accessors, - container, - /*startsOnNewLine*/ - false - )); + const statement = factory2.createExpressionStatement(transformAccessorsToExpression(receiver, accessors, container, /*startsOnNewLine*/ + false)); setEmitFlags(statement, 3072 /* NoComments */); setSourceMapRange(statement, getSourceMapRange(accessors.firstAccessor)); return statement; } - function transformAccessorsToExpression(receiver, { firstAccessor, getAccessor, setAccessor }, container, startsOnNewLine) { + function transformAccessorsToExpression(receiver, { + firstAccessor, + getAccessor, + setAccessor + }, container, startsOnNewLine) { const target = setParent(setTextRange(factory2.cloneNode(receiver), receiver), receiver.parent); setEmitFlags(target, 3072 /* NoComments */ | 64 /* NoTrailingSourceMap */); setSourceMapRange(target, firstAccessor.name); @@ -102289,14 +92158,9 @@ ${lanes.join("\n")} setSourceMapRange(propertyName, firstAccessor.name); const properties = []; if (getAccessor) { - const getterFunction = transformFunctionLikeToExpression( - getAccessor, - /*location*/ - void 0, - /*name*/ - void 0, - container - ); + const getterFunction = transformFunctionLikeToExpression(getAccessor, /*location*/ + void 0, /*name*/ + void 0, container); setSourceMapRange(getterFunction, getSourceMapRange(getAccessor)); setEmitFlags(getterFunction, 1024 /* NoLeadingComments */); const getter = factory2.createPropertyAssignment("get", getterFunction); @@ -102304,38 +92168,19 @@ ${lanes.join("\n")} properties.push(getter); } if (setAccessor) { - const setterFunction = transformFunctionLikeToExpression( - setAccessor, - /*location*/ - void 0, - /*name*/ - void 0, - container - ); + const setterFunction = transformFunctionLikeToExpression(setAccessor, /*location*/ + void 0, /*name*/ + void 0, container); setSourceMapRange(setterFunction, getSourceMapRange(setAccessor)); setEmitFlags(setterFunction, 1024 /* NoLeadingComments */); const setter = factory2.createPropertyAssignment("set", setterFunction); setCommentRange(setter, getCommentRange(setAccessor)); properties.push(setter); } - properties.push( - factory2.createPropertyAssignment("enumerable", getAccessor || setAccessor ? factory2.createFalse() : factory2.createTrue()), - factory2.createPropertyAssignment("configurable", factory2.createTrue()) - ); - const call = factory2.createCallExpression( - factory2.createPropertyAccessExpression(factory2.createIdentifier("Object"), "defineProperty"), - /*typeArguments*/ - void 0, - [ - target, - propertyName, - factory2.createObjectLiteralExpression( - properties, - /*multiLine*/ - true - ) - ] - ); + properties.push(factory2.createPropertyAssignment("enumerable", getAccessor || setAccessor ? factory2.createFalse() : factory2.createTrue()), factory2.createPropertyAssignment("configurable", factory2.createTrue())); + const call = factory2.createCallExpression(factory2.createPropertyAccessExpression(factory2.createIdentifier("Object"), "defineProperty"), /*typeArguments*/ + void 0, [target, propertyName, factory2.createObjectLiteralExpression(properties, /*multiLine*/ + true)]); if (startsOnNewLine) { startOnNewLine(call); } @@ -102345,23 +92190,16 @@ ${lanes.join("\n")} if (node.transformFlags & 16384 /* ContainsLexicalThis */ && !(hierarchyFacts & 16384 /* StaticInitializer */)) { hierarchyFacts |= 131072 /* CapturedLexicalThis */; } + const savedConvertedLoopState = convertedLoopState; convertedLoopState = void 0; const ancestorFacts = enterSubtree(15232 /* ArrowFunctionExcludes */, 66 /* ArrowFunctionIncludes */); - const func = factory2.createFunctionExpression( - /*modifiers*/ - void 0, - /*asteriskToken*/ - void 0, - /*name*/ - void 0, - /*typeParameters*/ - void 0, - visitParameterList(node.parameters, visitor, context), - /*type*/ - void 0, - transformFunctionBody2(node) - ); + const func = factory2.createFunctionExpression( /*modifiers*/ + void 0, /*asteriskToken*/ + void 0, /*name*/ + void 0, /*typeParameters*/ + void 0, visitParameterList(node.parameters, visitor, context), /*type*/ + void 0, transformFunctionBody2(node)); setTextRange(func, node); setOriginalNode(func, node); setEmitFlags(func, 16 /* CapturesThis */); @@ -102378,19 +92216,10 @@ ${lanes.join("\n")} const name = hierarchyFacts & 32768 /* NewTarget */ ? factory2.getLocalName(node) : node.name; exitSubtree(ancestorFacts, 229376 /* FunctionSubtreeExcludes */, 0 /* None */); convertedLoopState = savedConvertedLoopState; - return factory2.updateFunctionExpression( - node, - /*modifiers*/ - void 0, - node.asteriskToken, - name, - /*typeParameters*/ - void 0, - parameters, - /*type*/ - void 0, - body - ); + return factory2.updateFunctionExpression(node, /*modifiers*/ + void 0, node.asteriskToken, name, /*typeParameters*/ + void 0, parameters, /*type*/ + void 0, body); } function visitFunctionDeclaration(node) { const savedConvertedLoopState = convertedLoopState; @@ -102401,18 +92230,9 @@ ${lanes.join("\n")} const name = hierarchyFacts & 32768 /* NewTarget */ ? factory2.getLocalName(node) : node.name; exitSubtree(ancestorFacts, 229376 /* FunctionSubtreeExcludes */, 0 /* None */); convertedLoopState = savedConvertedLoopState; - return factory2.updateFunctionDeclaration( - node, - visitNodes2(node.modifiers, visitor, isModifier), - node.asteriskToken, - name, - /*typeParameters*/ - void 0, - parameters, - /*type*/ - void 0, - body - ); + return factory2.updateFunctionDeclaration(node, visitNodes2(node.modifiers, visitor, isModifier), node.asteriskToken, name, /*typeParameters*/ + void 0, parameters, /*type*/ + void 0, body); } function transformFunctionLikeToExpression(node, location, name, container) { const savedConvertedLoopState = convertedLoopState; @@ -102425,25 +92245,11 @@ ${lanes.join("\n")} } exitSubtree(ancestorFacts, 229376 /* FunctionSubtreeExcludes */, 0 /* None */); convertedLoopState = savedConvertedLoopState; - return setOriginalNode( - setTextRange( - factory2.createFunctionExpression( - /*modifiers*/ - void 0, - node.asteriskToken, - name, - /*typeParameters*/ - void 0, - parameters, - /*type*/ - void 0, - body - ), - location - ), - /*original*/ - node - ); + return setOriginalNode(setTextRange(factory2.createFunctionExpression( /*modifiers*/ + void 0, node.asteriskToken, name, /*typeParameters*/ + void 0, parameters, /*type*/ + void 0, body), location), /*original*/ + node); } function transformFunctionBody2(node) { let multiLine = false; @@ -102456,23 +92262,14 @@ ${lanes.join("\n")} let statementOffset; resumeLexicalEnvironment(); if (isBlock(body)) { - statementOffset = factory2.copyStandardPrologue( - body.statements, - prologue, - 0, - /*ensureUseStrict*/ - false - ); + statementOffset = factory2.copyStandardPrologue(body.statements, prologue, 0, /*ensureUseStrict*/ + false); statementOffset = factory2.copyCustomPrologue(body.statements, statements, statementOffset, visitor, isHoistedFunction); statementOffset = factory2.copyCustomPrologue(body.statements, statements, statementOffset, visitor, isHoistedVariableStatement); } multiLine = addDefaultValueAssignmentsIfNeeded2(statements, node) || multiLine; - multiLine = addRestParameterIfNeeded( - statements, - node, - /*inConstructorWithSynthesizedSuper*/ - false - ) || multiLine; + multiLine = addRestParameterIfNeeded(statements, node, /*inConstructorWithSynthesizedSuper*/ + false) || multiLine; if (isBlock(body)) { statementOffset = factory2.copyCustomPrologue(body.statements, statements, statementOffset, visitor); statementsLocation = body.statements; @@ -102514,6 +92311,7 @@ ${lanes.join("\n")} if (!multiLine && singleLine) { setEmitFlags(block, 1 /* SingleLine */); } + if (closeBraceLocation) { setTokenSourceMapRange(block, 20 /* CloseBraceToken */, closeBraceLocation); } @@ -102537,21 +92335,10 @@ ${lanes.join("\n")} } function visitBinaryExpression(node, expressionResultIsUnused2) { if (isDestructuringAssignment(node)) { - return flattenDestructuringAssignment( - node, - visitor, - context, - 0 /* All */, - !expressionResultIsUnused2 - ); + return flattenDestructuringAssignment(node, visitor, context, 0 /* All */, !expressionResultIsUnused2); } if (node.operatorToken.kind === 28 /* CommaToken */) { - return factory2.updateBinaryExpression( - node, - Debug.checkDefined(visitNode(node.left, visitorWithUnusedExpressionResult, isExpression)), - node.operatorToken, - Debug.checkDefined(visitNode(node.right, expressionResultIsUnused2 ? visitorWithUnusedExpressionResult : visitor, isExpression)) - ); + return factory2.updateBinaryExpression(node, Debug.checkDefined(visitNode(node.left, visitorWithUnusedExpressionResult, isExpression)), node.operatorToken, Debug.checkDefined(visitNode(node.right, expressionResultIsUnused2 ? visitorWithUnusedExpressionResult : visitor, isExpression))); } return visitEachChild(node, visitor, context); } @@ -102575,6 +92362,7 @@ ${lanes.join("\n")} function isVariableStatementOfTypeScriptClassWrapper(node) { return node.declarationList.declarations.length === 1 && !!node.declarationList.declarations[0].initializer && !!(getInternalEmitFlags(node.declarationList.declarations[0].initializer) & 1 /* TypeScriptClassWrapper */); } + function visitVariableStatement(node) { const ancestorFacts = enterSubtree(0 /* None */, hasSyntacticModifier(node, 32 /* Export */) ? 32 /* ExportedVariableStatement */ : 0 /* None */); let updated; @@ -102585,12 +92373,7 @@ ${lanes.join("\n")} if (decl.initializer) { let assignment; if (isBindingPattern(decl.name)) { - assignment = flattenDestructuringAssignment( - decl, - visitor, - context, - 0 /* All */ - ); + assignment = flattenDestructuringAssignment(decl, visitor, context, 0 /* All */); } else { assignment = factory2.createBinaryExpression(decl.name, 64 /* EqualsToken */, Debug.checkDefined(visitNode(decl.initializer, visitor, isExpression))); setTextRange(assignment, decl); @@ -102614,11 +92397,7 @@ ${lanes.join("\n")} if (node.flags & 7 /* BlockScoped */) { enableSubstitutionsForBlockScopedBindings(); } - const declarations = visitNodes2( - node.declarations, - node.flags & 1 /* Let */ ? visitVariableDeclarationInLetDeclarationList : visitVariableDeclaration, - isVariableDeclaration - ); + const declarations = visitNodes2(node.declarations, node.flags & 1 /* Let */ ? visitVariableDeclarationInLetDeclarationList : visitVariableDeclaration, isVariableDeclaration); const declarationList = factory2.createVariableDeclarationList(declarations); setOriginalNode(declarationList, node); setTextRange(declarationList, node); @@ -102631,7 +92410,8 @@ ${lanes.join("\n")} return visitEachChild(node, visitor, context); } function getRangeUnion(declarations) { - let pos = -1, end = -1; + let pos = -1, + end = -1; for (const node of declarations) { pos = pos === -1 ? node.pos : node.pos === -1 ? pos : Math.min(pos, node.pos); end = Math.max(end, node.end); @@ -102652,15 +92432,9 @@ ${lanes.join("\n")} return visitVariableDeclaration(node); } if (!node.initializer && shouldEmitExplicitInitializerForLetDeclaration(node)) { - return factory2.updateVariableDeclaration( - node, - node.name, - /*exclamationToken*/ - void 0, - /*type*/ - void 0, - factory2.createVoidZero() - ); + return factory2.updateVariableDeclaration(node, node.name, /*exclamationToken*/ + void 0, /*type*/ + void 0, factory2.createVoidZero()); } return visitEachChild(node, visitor, context); } @@ -102668,15 +92442,8 @@ ${lanes.join("\n")} const ancestorFacts = enterSubtree(32 /* ExportedVariableStatement */, 0 /* None */); let updated; if (isBindingPattern(node.name)) { - updated = flattenDestructuringBinding( - node, - visitor, - context, - 0 /* All */, - /*rval*/ - void 0, - (ancestorFacts & 32 /* ExportedVariableStatement */) !== 0 - ); + updated = flattenDestructuringBinding(node, visitor, context, 0 /* All */, /*rval*/ + void 0, (ancestorFacts & 32 /* ExportedVariableStatement */) !== 0); } else { updated = visitEachChild(node, visitor, context); } @@ -102691,18 +92458,12 @@ ${lanes.join("\n")} } function visitLabeledStatement(node) { if (convertedLoopState && !convertedLoopState.labels) { - convertedLoopState.labels = /* @__PURE__ */ new Map(); + convertedLoopState.labels = /* @__PURE__ */new Map(); } const statement = unwrapInnermostStatementOfLabel(node, convertedLoopState && recordLabel); - return isIterationStatement( - statement, - /*lookInLabeledStatements*/ - false - ) ? visitIterationStatement( - statement, - /*outermostLabeledStatement*/ - node - ) : factory2.restoreEnclosingLabel(Debug.checkDefined(visitNode(statement, visitor, isStatement, factory2.liftToBlock)), node, convertedLoopState && resetLabel); + return isIterationStatement(statement, /*lookInLabeledStatements*/ + false) ? visitIterationStatement(statement, /*outermostLabeledStatement*/ + node) : factory2.restoreEnclosingLabel(Debug.checkDefined(visitNode(statement, visitor, isStatement, factory2.liftToBlock)), node, convertedLoopState && resetLabel); } function visitIterationStatement(node, outermostLabeledStatement) { switch (node.kind) { @@ -102724,46 +92485,19 @@ ${lanes.join("\n")} return updated; } function visitDoOrWhileStatement(node, outermostLabeledStatement) { - return visitIterationStatementWithFacts( - 0 /* DoOrWhileStatementExcludes */, - 1280 /* DoOrWhileStatementIncludes */, - node, - outermostLabeledStatement - ); + return visitIterationStatementWithFacts(0 /* DoOrWhileStatementExcludes */, 1280 /* DoOrWhileStatementIncludes */, node, outermostLabeledStatement); } function visitForStatement(node, outermostLabeledStatement) { - return visitIterationStatementWithFacts( - 5056 /* ForStatementExcludes */, - 3328 /* ForStatementIncludes */, - node, - outermostLabeledStatement - ); + return visitIterationStatementWithFacts(5056 /* ForStatementExcludes */, 3328 /* ForStatementIncludes */, node, outermostLabeledStatement); } function visitEachChildOfForStatement2(node) { - return factory2.updateForStatement( - node, - visitNode(node.initializer, visitorWithUnusedExpressionResult, isForInitializer), - visitNode(node.condition, visitor, isExpression), - visitNode(node.incrementor, visitorWithUnusedExpressionResult, isExpression), - Debug.checkDefined(visitNode(node.statement, visitor, isStatement, factory2.liftToBlock)) - ); + return factory2.updateForStatement(node, visitNode(node.initializer, visitorWithUnusedExpressionResult, isForInitializer), visitNode(node.condition, visitor, isExpression), visitNode(node.incrementor, visitorWithUnusedExpressionResult, isExpression), Debug.checkDefined(visitNode(node.statement, visitor, isStatement, factory2.liftToBlock))); } function visitForInStatement(node, outermostLabeledStatement) { - return visitIterationStatementWithFacts( - 3008 /* ForInOrForOfStatementExcludes */, - 5376 /* ForInOrForOfStatementIncludes */, - node, - outermostLabeledStatement - ); + return visitIterationStatementWithFacts(3008 /* ForInOrForOfStatementExcludes */, 5376 /* ForInOrForOfStatementIncludes */, node, outermostLabeledStatement); } function visitForOfStatement(node, outermostLabeledStatement) { - return visitIterationStatementWithFacts( - 3008 /* ForInOrForOfStatementExcludes */, - 5376 /* ForInOrForOfStatementIncludes */, - node, - outermostLabeledStatement, - compilerOptions.downlevelIteration ? convertForOfStatementForIterable : convertForOfStatementForArray - ); + return visitIterationStatementWithFacts(3008 /* ForInOrForOfStatementExcludes */, 5376 /* ForInOrForOfStatementIncludes */, node, outermostLabeledStatement, compilerOptions.downlevelIteration ? convertForOfStatementForIterable : convertForOfStatementForArray); } function convertForOfStatementHead(node, boundValue, convertedLoopBodyStatements) { const statements = []; @@ -102774,61 +92508,24 @@ ${lanes.join("\n")} } const firstOriginalDeclaration = firstOrUndefined(initializer.declarations); if (firstOriginalDeclaration && isBindingPattern(firstOriginalDeclaration.name)) { - const declarations = flattenDestructuringBinding( - firstOriginalDeclaration, - visitor, - context, - 0 /* All */, - boundValue - ); + const declarations = flattenDestructuringBinding(firstOriginalDeclaration, visitor, context, 0 /* All */, boundValue); const declarationList = setTextRange(factory2.createVariableDeclarationList(declarations), node.initializer); setOriginalNode(declarationList, node.initializer); setSourceMapRange(declarationList, createRange(declarations[0].pos, last(declarations).end)); - statements.push( - factory2.createVariableStatement( - /*modifiers*/ - void 0, - declarationList - ) - ); + statements.push(factory2.createVariableStatement( /*modifiers*/ + void 0, declarationList)); } else { - statements.push( - setTextRange( - factory2.createVariableStatement( - /*modifiers*/ - void 0, - setOriginalNode( - setTextRange( - factory2.createVariableDeclarationList([ - factory2.createVariableDeclaration( - firstOriginalDeclaration ? firstOriginalDeclaration.name : factory2.createTempVariable( - /*recordTempVariable*/ - void 0 - ), - /*exclamationToken*/ - void 0, - /*type*/ - void 0, - boundValue - ) - ]), - moveRangePos(initializer, -1) - ), - initializer - ) - ), - moveRangeEnd(initializer, -1) - ) - ); + statements.push(setTextRange(factory2.createVariableStatement( /*modifiers*/ + void 0, setOriginalNode(setTextRange(factory2.createVariableDeclarationList([factory2.createVariableDeclaration(firstOriginalDeclaration ? firstOriginalDeclaration.name : factory2.createTempVariable( /*recordTempVariable*/ + void 0), /*exclamationToken*/ + void 0, /*type*/ + void 0, boundValue)]), moveRangePos(initializer, -1)), initializer)), moveRangeEnd(initializer, -1))); } } else { const assignment = factory2.createAssignment(initializer, boundValue); if (isDestructuringAssignment(assignment)) { - statements.push(factory2.createExpressionStatement(visitBinaryExpression( - assignment, - /*expressionResultIsUnused*/ - true - ))); + statements.push(factory2.createExpressionStatement(visitBinaryExpression(assignment, /*expressionResultIsUnused*/ + true))); } else { setTextRangeEnd(assignment, initializer.end); statements.push(setTextRange(factory2.createExpressionStatement(Debug.checkDefined(visitNode(assignment, visitor, isExpression))), moveRangeEnd(initializer, -1))); @@ -102848,71 +92545,27 @@ ${lanes.join("\n")} } } function createSyntheticBlockForConvertedStatements(statements) { - return setEmitFlags( - factory2.createBlock( - factory2.createNodeArray(statements), - /*multiLine*/ - true - ), - 96 /* NoSourceMap */ | 768 /* NoTokenSourceMaps */ - ); + return setEmitFlags(factory2.createBlock(factory2.createNodeArray(statements), /*multiLine*/ + true), 96 /* NoSourceMap */ | 768 /* NoTokenSourceMaps */); } + function convertForOfStatementForArray(node, outermostLabeledStatement, convertedLoopBodyStatements) { const expression = visitNode(node.expression, visitor, isExpression); Debug.assert(expression); const counter = factory2.createLoopVariable(); - const rhsReference = isIdentifier(expression) ? factory2.getGeneratedNameForNode(expression) : factory2.createTempVariable( - /*recordTempVariable*/ - void 0 - ); + const rhsReference = isIdentifier(expression) ? factory2.getGeneratedNameForNode(expression) : factory2.createTempVariable( /*recordTempVariable*/ + void 0); setEmitFlags(expression, 96 /* NoSourceMap */ | getEmitFlags(expression)); - const forStatement = setTextRange( - factory2.createForStatement( - /*initializer*/ - setEmitFlags( - setTextRange( - factory2.createVariableDeclarationList([ - setTextRange(factory2.createVariableDeclaration( - counter, - /*exclamationToken*/ - void 0, - /*type*/ - void 0, - factory2.createNumericLiteral(0) - ), moveRangePos(node.expression, -1)), - setTextRange(factory2.createVariableDeclaration( - rhsReference, - /*exclamationToken*/ - void 0, - /*type*/ - void 0, - expression - ), node.expression) - ]), - node.expression - ), - 4194304 /* NoHoisting */ - ), - /*condition*/ - setTextRange( - factory2.createLessThan( - counter, - factory2.createPropertyAccessExpression(rhsReference, "length") - ), - node.expression - ), - /*incrementor*/ - setTextRange(factory2.createPostfixIncrement(counter), node.expression), - /*statement*/ - convertForOfStatementHead( - node, - factory2.createElementAccessExpression(rhsReference, counter), - convertedLoopBodyStatements - ) - ), - /*location*/ - node - ); + const forStatement = setTextRange(factory2.createForStatement( /*initializer*/ + setEmitFlags(setTextRange(factory2.createVariableDeclarationList([setTextRange(factory2.createVariableDeclaration(counter, /*exclamationToken*/ + void 0, /*type*/ + void 0, factory2.createNumericLiteral(0)), moveRangePos(node.expression, -1)), setTextRange(factory2.createVariableDeclaration(rhsReference, /*exclamationToken*/ + void 0, /*type*/ + void 0, expression), node.expression)]), node.expression), 4194304 /* NoHoisting */), /*condition*/ + setTextRange(factory2.createLessThan(counter, factory2.createPropertyAccessExpression(rhsReference, "length")), node.expression), /*incrementor*/ + setTextRange(factory2.createPostfixIncrement(counter), node.expression), /*statement*/ + convertForOfStatementHead(node, factory2.createElementAccessExpression(rhsReference, counter), convertedLoopBodyStatements)), /*location*/ + node); setEmitFlags(forStatement, 512 /* NoTokenTrailingSourceMaps */); setTextRange(forStatement, node); return factory2.restoreEnclosingLabel(forStatement, outermostLabeledStatement, convertedLoopState && resetLabel); @@ -102920,147 +92573,41 @@ ${lanes.join("\n")} function convertForOfStatementForIterable(node, outermostLabeledStatement, convertedLoopBodyStatements, ancestorFacts) { const expression = visitNode(node.expression, visitor, isExpression); Debug.assert(expression); - const iterator = isIdentifier(expression) ? factory2.getGeneratedNameForNode(expression) : factory2.createTempVariable( - /*recordTempVariable*/ - void 0 - ); - const result = isIdentifier(expression) ? factory2.getGeneratedNameForNode(iterator) : factory2.createTempVariable( - /*recordTempVariable*/ - void 0 - ); + const iterator = isIdentifier(expression) ? factory2.getGeneratedNameForNode(expression) : factory2.createTempVariable( /*recordTempVariable*/ + void 0); + const result = isIdentifier(expression) ? factory2.getGeneratedNameForNode(iterator) : factory2.createTempVariable( /*recordTempVariable*/ + void 0); const errorRecord = factory2.createUniqueName("e"); const catchVariable = factory2.getGeneratedNameForNode(errorRecord); - const returnMethod = factory2.createTempVariable( - /*recordTempVariable*/ - void 0 - ); + const returnMethod = factory2.createTempVariable( /*recordTempVariable*/ + void 0); const values = setTextRange(emitHelpers().createValuesHelper(expression), node.expression); - const next = factory2.createCallExpression( - factory2.createPropertyAccessExpression(iterator, "next"), - /*typeArguments*/ - void 0, - [] - ); + const next = factory2.createCallExpression(factory2.createPropertyAccessExpression(iterator, "next"), /*typeArguments*/ + void 0, []); hoistVariableDeclaration(errorRecord); hoistVariableDeclaration(returnMethod); const initializer = ancestorFacts & 1024 /* IterationContainer */ ? factory2.inlineExpressions([factory2.createAssignment(errorRecord, factory2.createVoidZero()), values]) : values; - const forStatement = setEmitFlags( - setTextRange( - factory2.createForStatement( - /*initializer*/ - setEmitFlags( - setTextRange( - factory2.createVariableDeclarationList([ - setTextRange(factory2.createVariableDeclaration( - iterator, - /*exclamationToken*/ - void 0, - /*type*/ - void 0, - initializer - ), node.expression), - factory2.createVariableDeclaration( - result, - /*exclamationToken*/ - void 0, - /*type*/ - void 0, - next - ) - ]), - node.expression - ), - 4194304 /* NoHoisting */ - ), - /*condition*/ - factory2.createLogicalNot(factory2.createPropertyAccessExpression(result, "done")), - /*incrementor*/ - factory2.createAssignment(result, next), - /*statement*/ - convertForOfStatementHead( - node, - factory2.createPropertyAccessExpression(result, "value"), - convertedLoopBodyStatements - ) - ), - /*location*/ - node - ), - 512 /* NoTokenTrailingSourceMaps */ - ); - return factory2.createTryStatement( - factory2.createBlock([ - factory2.restoreEnclosingLabel( - forStatement, - outermostLabeledStatement, - convertedLoopState && resetLabel - ) - ]), - factory2.createCatchClause( - factory2.createVariableDeclaration(catchVariable), - setEmitFlags( - factory2.createBlock([ - factory2.createExpressionStatement( - factory2.createAssignment( - errorRecord, - factory2.createObjectLiteralExpression([ - factory2.createPropertyAssignment("error", catchVariable) - ]) - ) - ) - ]), - 1 /* SingleLine */ - ) - ), - factory2.createBlock([ - factory2.createTryStatement( - /*tryBlock*/ - factory2.createBlock([ - setEmitFlags( - factory2.createIfStatement( - factory2.createLogicalAnd( - factory2.createLogicalAnd( - result, - factory2.createLogicalNot( - factory2.createPropertyAccessExpression(result, "done") - ) - ), - factory2.createAssignment( - returnMethod, - factory2.createPropertyAccessExpression(iterator, "return") - ) - ), - factory2.createExpressionStatement( - factory2.createFunctionCallCall(returnMethod, iterator, []) - ) - ), - 1 /* SingleLine */ - ) - ]), - /*catchClause*/ - void 0, - /*finallyBlock*/ - setEmitFlags( - factory2.createBlock([ - setEmitFlags( - factory2.createIfStatement( - errorRecord, - factory2.createThrowStatement( - factory2.createPropertyAccessExpression(errorRecord, "error") - ) - ), - 1 /* SingleLine */ - ) - ]), - 1 /* SingleLine */ - ) - ) - ]) - ); + const forStatement = setEmitFlags(setTextRange(factory2.createForStatement( /*initializer*/ + setEmitFlags(setTextRange(factory2.createVariableDeclarationList([setTextRange(factory2.createVariableDeclaration(iterator, /*exclamationToken*/ + void 0, /*type*/ + void 0, initializer), node.expression), factory2.createVariableDeclaration(result, /*exclamationToken*/ + void 0, /*type*/ + void 0, next)]), node.expression), 4194304 /* NoHoisting */), /*condition*/ + factory2.createLogicalNot(factory2.createPropertyAccessExpression(result, "done")), /*incrementor*/ + factory2.createAssignment(result, next), /*statement*/ + convertForOfStatementHead(node, factory2.createPropertyAccessExpression(result, "value"), convertedLoopBodyStatements)), /*location*/ + node), 512 /* NoTokenTrailingSourceMaps */); + + return factory2.createTryStatement(factory2.createBlock([factory2.restoreEnclosingLabel(forStatement, outermostLabeledStatement, convertedLoopState && resetLabel)]), factory2.createCatchClause(factory2.createVariableDeclaration(catchVariable), setEmitFlags(factory2.createBlock([factory2.createExpressionStatement(factory2.createAssignment(errorRecord, factory2.createObjectLiteralExpression([factory2.createPropertyAssignment("error", catchVariable)])))]), 1 /* SingleLine */)), factory2.createBlock([factory2.createTryStatement( /*tryBlock*/ + factory2.createBlock([setEmitFlags(factory2.createIfStatement(factory2.createLogicalAnd(factory2.createLogicalAnd(result, factory2.createLogicalNot(factory2.createPropertyAccessExpression(result, "done"))), factory2.createAssignment(returnMethod, factory2.createPropertyAccessExpression(iterator, "return"))), factory2.createExpressionStatement(factory2.createFunctionCallCall(returnMethod, iterator, []))), 1 /* SingleLine */)]), /*catchClause*/ + void 0, /*finallyBlock*/ + setEmitFlags(factory2.createBlock([setEmitFlags(factory2.createIfStatement(errorRecord, factory2.createThrowStatement(factory2.createPropertyAccessExpression(errorRecord, "error"))), 1 /* SingleLine */)]), 1 /* SingleLine */))])); } + function visitObjectLiteralExpression(node) { const properties = node.properties; - let numInitialProperties = -1, hasComputed = false; + let numInitialProperties = -1, + hasComputed = false; for (let i = 0; i < properties.length; i++) { const property = properties[i]; if (property.transformFlags & 1048576 /* ContainsYield */ && hierarchyFacts & 4 /* AsyncFunctionBody */ || (hasComputed = Debug.checkDefined(property.name).kind === 167 /* ComputedPropertyName */)) { @@ -103073,16 +92620,7 @@ ${lanes.join("\n")} } const temp = factory2.createTempVariable(hoistVariableDeclaration); const expressions = []; - const assignment = factory2.createAssignment( - temp, - setEmitFlags( - factory2.createObjectLiteralExpression( - visitNodes2(properties, visitor, isObjectLiteralElementLike, 0, numInitialProperties), - node.multiLine - ), - hasComputed ? 131072 /* Indented */ : 0 - ) - ); + const assignment = factory2.createAssignment(temp, setEmitFlags(factory2.createObjectLiteralExpression(visitNodes2(properties, visitor, isObjectLiteralElementLike, 0, numInitialProperties), node.multiLine), hasComputed ? 131072 /* Indented */ : 0)); if (node.multiLine) { startOnNewLine(assignment); } @@ -103133,17 +92671,9 @@ ${lanes.join("\n")} saveAllowedNonLabeledJumps = convertedLoopState.allowedNonLabeledJumps; convertedLoopState.allowedNonLabeledJumps = 2 /* Break */ | 4 /* Continue */; } - const result = convert ? convert( - node, - outermostLabeledStatement, - /*convertedLoopBodyStatements*/ - void 0, - ancestorFacts - ) : factory2.restoreEnclosingLabel( - isForStatement(node) ? visitEachChildOfForStatement2(node) : visitEachChild(node, visitor, context), - outermostLabeledStatement, - convertedLoopState && resetLabel - ); + + const result = convert ? convert(node, outermostLabeledStatement, /*convertedLoopBodyStatements*/ + void 0, ancestorFacts) : factory2.restoreEnclosingLabel(isForStatement(node) ? visitEachChildOfForStatement2(node) : visitEachChild(node, visitor, context), outermostLabeledStatement, convertedLoopState && resetLabel); if (convertedLoopState) { convertedLoopState.allowedNonLabeledJumps = saveAllowedNonLabeledJumps; } @@ -103156,10 +92686,8 @@ ${lanes.join("\n")} 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)); @@ -103169,11 +92697,8 @@ ${lanes.join("\n")} if (convert) { loop = convert(node, outermostLabeledStatement, bodyFunction.part, ancestorFacts); } else { - const clone2 = convertIterationStatementCore(node, initializerFunction, factory2.createBlock( - bodyFunction.part, - /*multiLine*/ - true - )); + const clone2 = convertIterationStatementCore(node, initializerFunction, factory2.createBlock(bodyFunction.part, /*multiLine*/ + true)); loop = factory2.restoreEnclosingLabel(clone2, outermostLabeledStatement, convertedLoopState && resetLabel); } } else { @@ -103202,45 +92727,20 @@ ${lanes.join("\n")} function convertForStatement(node, initializerFunction, convertedLoopBody) { const shouldConvertCondition = node.condition && shouldConvertPartOfIterationStatement(node.condition); const shouldConvertIncrementor = shouldConvertCondition || node.incrementor && shouldConvertPartOfIterationStatement(node.incrementor); - return factory2.updateForStatement( - node, - visitNode(initializerFunction ? initializerFunction.part : node.initializer, visitorWithUnusedExpressionResult, isForInitializer), - visitNode(shouldConvertCondition ? void 0 : node.condition, visitor, isExpression), - visitNode(shouldConvertIncrementor ? void 0 : node.incrementor, visitorWithUnusedExpressionResult, isExpression), - convertedLoopBody - ); + return factory2.updateForStatement(node, visitNode(initializerFunction ? initializerFunction.part : node.initializer, visitorWithUnusedExpressionResult, isForInitializer), visitNode(shouldConvertCondition ? void 0 : node.condition, visitor, isExpression), visitNode(shouldConvertIncrementor ? void 0 : node.incrementor, visitorWithUnusedExpressionResult, isExpression), convertedLoopBody); } function convertForOfStatement(node, convertedLoopBody) { - return factory2.updateForOfStatement( - node, - /*awaitModifier*/ - void 0, - Debug.checkDefined(visitNode(node.initializer, visitor, isForInitializer)), - Debug.checkDefined(visitNode(node.expression, visitor, isExpression)), - convertedLoopBody - ); + return factory2.updateForOfStatement(node, /*awaitModifier*/ + void 0, Debug.checkDefined(visitNode(node.initializer, visitor, isForInitializer)), Debug.checkDefined(visitNode(node.expression, visitor, isExpression)), convertedLoopBody); } function convertForInStatement(node, convertedLoopBody) { - return factory2.updateForInStatement( - node, - Debug.checkDefined(visitNode(node.initializer, visitor, isForInitializer)), - Debug.checkDefined(visitNode(node.expression, visitor, isExpression)), - convertedLoopBody - ); + return factory2.updateForInStatement(node, Debug.checkDefined(visitNode(node.initializer, visitor, isForInitializer)), Debug.checkDefined(visitNode(node.expression, visitor, isExpression)), convertedLoopBody); } function convertDoStatement(node, convertedLoopBody) { - return factory2.updateDoStatement( - node, - convertedLoopBody, - Debug.checkDefined(visitNode(node.expression, visitor, isExpression)) - ); + return factory2.updateDoStatement(node, convertedLoopBody, Debug.checkDefined(visitNode(node.expression, visitor, isExpression))); } function convertWhileStatement(node, convertedLoopBody) { - return factory2.updateWhileStatement( - node, - Debug.checkDefined(visitNode(node.expression, visitor, isExpression)), - convertedLoopBody - ); + return factory2.updateWhileStatement(node, Debug.checkDefined(visitNode(node.expression, visitor, isExpression)), convertedLoopBody); } function createConvertedLoopState(node) { let loopInitializer; @@ -103262,7 +92762,10 @@ ${lanes.join("\n")} processLoopVariableDeclaration(node, decl, loopParameters, loopOutParameters, hasCapturedBindingsInForHead); } } - const currentState = { loopParameters, loopOutParameters }; + const currentState = { + loopParameters, + loopOutParameters + }; if (convertedLoopState) { if (convertedLoopState.argumentsName) { currentState.argumentsName = convertedLoopState.argumentsName; @@ -103282,32 +92785,18 @@ ${lanes.join("\n")} if (outerState) { outerState.argumentsName = state.argumentsName; } else { - (extraVariableDeclarations || (extraVariableDeclarations = [])).push( - factory2.createVariableDeclaration( - state.argumentsName, - /*exclamationToken*/ - void 0, - /*type*/ - void 0, - factory2.createIdentifier("arguments") - ) - ); + (extraVariableDeclarations || (extraVariableDeclarations = [])).push(factory2.createVariableDeclaration(state.argumentsName, /*exclamationToken*/ + void 0, /*type*/ + void 0, factory2.createIdentifier("arguments"))); } } if (state.thisName) { if (outerState) { outerState.thisName = state.thisName; } else { - (extraVariableDeclarations || (extraVariableDeclarations = [])).push( - factory2.createVariableDeclaration( - state.thisName, - /*exclamationToken*/ - void 0, - /*type*/ - void 0, - factory2.createIdentifier("this") - ) - ); + (extraVariableDeclarations || (extraVariableDeclarations = [])).push(factory2.createVariableDeclaration(state.thisName, /*exclamationToken*/ + void 0, /*type*/ + void 0, factory2.createIdentifier("this"))); } } if (state.hoistedLocalVariables) { @@ -103334,91 +92823,48 @@ ${lanes.join("\n")} if (!extraVariableDeclarations) { extraVariableDeclarations = []; } - extraVariableDeclarations.push(factory2.createVariableDeclaration( - state.conditionVariable, - /*exclamationToken*/ - void 0, - /*type*/ - void 0, - factory2.createFalse() - )); + extraVariableDeclarations.push(factory2.createVariableDeclaration(state.conditionVariable, /*exclamationToken*/ + void 0, /*type*/ + void 0, factory2.createFalse())); } if (extraVariableDeclarations) { - statements.push(factory2.createVariableStatement( - /*modifiers*/ - void 0, - factory2.createVariableDeclarationList(extraVariableDeclarations) - )); + statements.push(factory2.createVariableStatement( /*modifiers*/ + void 0, factory2.createVariableDeclarationList(extraVariableDeclarations))); } } function createOutVariable(p) { - return factory2.createVariableDeclaration( - p.originalName, - /*exclamationToken*/ - void 0, - /*type*/ - void 0, - p.outParamName - ); + return factory2.createVariableDeclaration(p.originalName, /*exclamationToken*/ + void 0, /*type*/ + void 0, p.outParamName); } function createFunctionForInitializerOfForStatement(node, currentState) { 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*/ - void 0, - node.initializer - )); + statements.push(factory2.createVariableStatement( /*modifiers*/ + void 0, node.initializer)); copyOutParameters(currentState.loopOutParameters, 2 /* Initializer */, 1 /* ToOutParameter */, statements); - const functionDeclaration = factory2.createVariableStatement( - /*modifiers*/ - void 0, - setEmitFlags( - factory2.createVariableDeclarationList([ - factory2.createVariableDeclaration( - functionName, - /*exclamationToken*/ - void 0, - /*type*/ - void 0, - setEmitFlags( - factory2.createFunctionExpression( - /*modifiers*/ - void 0, - containsYield ? factory2.createToken(42 /* AsteriskToken */) : void 0, - /*name*/ - void 0, - /*typeParameters*/ - void 0, - /*parameters*/ - void 0, - /*type*/ - void 0, - Debug.checkDefined(visitNode( - factory2.createBlock( - statements, - /*multiLine*/ - true - ), - visitor, - isBlock - )) - ), - emitFlags - ) - ) - ]), - 4194304 /* NoHoisting */ - ) - ); + const functionDeclaration = factory2.createVariableStatement( /*modifiers*/ + void 0, setEmitFlags(factory2.createVariableDeclarationList([factory2.createVariableDeclaration(functionName, /*exclamationToken*/ + void 0, /*type*/ + void 0, setEmitFlags(factory2.createFunctionExpression( /*modifiers*/ + void 0, containsYield ? factory2.createToken(42 /* AsteriskToken */) : void 0, /*name*/ + void 0, /*typeParameters*/ + void 0, /*parameters*/ + void 0, /*type*/ + void 0, Debug.checkDefined(visitNode(factory2.createBlock(statements, /*multiLine*/ + true), visitor, isBlock))), emitFlags))]), 4194304 /* NoHoisting */)); + const part = factory2.createVariableDeclarationList(map(currentState.loopOutParameters, createOutVariable)); - return { functionName, containsYield, functionDeclaration, part }; + return { + functionName, + containsYield, + functionDeclaration, + part + }; } function createFunctionForBodyOfIterationStatement(node, currentState, outerState) { const functionName = factory2.createUniqueName("_loop"); @@ -103429,22 +92875,12 @@ ${lanes.join("\n")} if (shouldConvertConditionOfForStatement(node) || shouldConvertIncrementorOfForStatement(node)) { currentState.conditionVariable = factory2.createUniqueName("inc"); if (node.incrementor) { - statements.push(factory2.createIfStatement( - currentState.conditionVariable, - factory2.createExpressionStatement(Debug.checkDefined(visitNode(node.incrementor, visitor, isExpression))), - factory2.createExpressionStatement(factory2.createAssignment(currentState.conditionVariable, factory2.createTrue())) - )); + statements.push(factory2.createIfStatement(currentState.conditionVariable, factory2.createExpressionStatement(Debug.checkDefined(visitNode(node.incrementor, visitor, isExpression))), factory2.createExpressionStatement(factory2.createAssignment(currentState.conditionVariable, factory2.createTrue())))); } else { - statements.push(factory2.createIfStatement( - factory2.createLogicalNot(currentState.conditionVariable), - factory2.createExpressionStatement(factory2.createAssignment(currentState.conditionVariable, factory2.createTrue())) - )); + statements.push(factory2.createIfStatement(factory2.createLogicalNot(currentState.conditionVariable), factory2.createExpressionStatement(factory2.createAssignment(currentState.conditionVariable, factory2.createTrue())))); } if (shouldConvertConditionOfForStatement(node)) { - statements.push(factory2.createIfStatement( - factory2.createPrefixUnaryExpression(54 /* ExclamationToken */, Debug.checkDefined(visitNode(node.condition, visitor, isExpression))), - Debug.checkDefined(visitNode(factory2.createBreakStatement(), visitor, isStatement)) - )); + statements.push(factory2.createIfStatement(factory2.createPrefixUnaryExpression(54 /* ExclamationToken */, Debug.checkDefined(visitNode(node.condition, visitor, isExpression))), Debug.checkDefined(visitNode(factory2.createBreakStatement(), visitor, isStatement)))); } } Debug.assert(statement); @@ -103455,55 +92891,29 @@ ${lanes.join("\n")} } copyOutParameters(currentState.loopOutParameters, 1 /* Body */, 1 /* ToOutParameter */, statements); insertStatementsAfterStandardPrologue(statements, lexicalEnvironment); - const loopBody = factory2.createBlock( - statements, - /*multiLine*/ - true - ); - if (isBlock(statement)) - setOriginalNode(loopBody, statement); + const loopBody = factory2.createBlock(statements, /*multiLine*/ + true); + 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 */; - const functionDeclaration = factory2.createVariableStatement( - /*modifiers*/ - void 0, - setEmitFlags( - factory2.createVariableDeclarationList( - [ - factory2.createVariableDeclaration( - functionName, - /*exclamationToken*/ - void 0, - /*type*/ - void 0, - setEmitFlags( - factory2.createFunctionExpression( - /*modifiers*/ - void 0, - containsYield ? factory2.createToken(42 /* AsteriskToken */) : void 0, - /*name*/ - void 0, - /*typeParameters*/ - void 0, - currentState.loopParameters, - /*type*/ - void 0, - loopBody - ), - emitFlags - ) - ) - ] - ), - 4194304 /* NoHoisting */ - ) - ); + if (currentState.containsLexicalThis) emitFlags |= 16 /* CapturesThis */; + if (containsYield && (hierarchyFacts & 4 /* AsyncFunctionBody */) !== 0) emitFlags |= 524288 /* AsyncFunctionBody */; + const functionDeclaration = factory2.createVariableStatement( /*modifiers*/ + void 0, setEmitFlags(factory2.createVariableDeclarationList([factory2.createVariableDeclaration(functionName, /*exclamationToken*/ + void 0, /*type*/ + void 0, setEmitFlags(factory2.createFunctionExpression( /*modifiers*/ + void 0, containsYield ? factory2.createToken(42 /* AsteriskToken */) : void 0, /*name*/ + void 0, /*typeParameters*/ + void 0, currentState.loopParameters, /*type*/ + void 0, loopBody), emitFlags))]), 4194304 /* NoHoisting */)); + const part = generateCallToConvertedLoop(functionName, currentState, outerState, containsYield); - return { functionName, containsYield, functionDeclaration, part }; + return { + functionName, + containsYield, + functionDeclaration, + part + }; } function copyOutParameter(outParam, copyDirection) { const source = copyDirection === 0 /* ToOriginal */ ? outParam.outParamName : outParam.originalName; @@ -103518,50 +92928,26 @@ ${lanes.join("\n")} } } function generateCallToConvertedLoopInitializer(initFunctionExpressionName, containsYield) { - const call = factory2.createCallExpression( - initFunctionExpressionName, - /*typeArguments*/ - void 0, - [] - ); - const callResult = containsYield ? factory2.createYieldExpression( - factory2.createToken(42 /* AsteriskToken */), - setEmitFlags(call, 8388608 /* Iterator */) - ) : call; + const call = factory2.createCallExpression(initFunctionExpressionName, /*typeArguments*/ + void 0, []); + const callResult = containsYield ? factory2.createYieldExpression(factory2.createToken(42 /* AsteriskToken */), setEmitFlags(call, 8388608 /* Iterator */)) : call; return factory2.createExpressionStatement(callResult); } function generateCallToConvertedLoop(loopFunctionExpressionName, state, outerState, containsYield) { const statements = []; const isSimpleLoop = !(state.nonLocalJumps & ~4 /* Continue */) && !state.labeledNonLocalBreaks && !state.labeledNonLocalContinues; - const call = factory2.createCallExpression( - loopFunctionExpressionName, - /*typeArguments*/ - void 0, - map(state.loopParameters, (p) => p.name) - ); - const callResult = containsYield ? factory2.createYieldExpression( - factory2.createToken(42 /* AsteriskToken */), - setEmitFlags(call, 8388608 /* Iterator */) - ) : call; + const call = factory2.createCallExpression(loopFunctionExpressionName, /*typeArguments*/ + void 0, map(state.loopParameters, p => p.name)); + const callResult = containsYield ? factory2.createYieldExpression(factory2.createToken(42 /* AsteriskToken */), setEmitFlags(call, 8388608 /* Iterator */)) : call; if (isSimpleLoop) { statements.push(factory2.createExpressionStatement(callResult)); copyOutParameters(state.loopOutParameters, 1 /* Body */, 0 /* ToOriginal */, statements); } else { const loopResultName = factory2.createUniqueName("state"); - const stateVariable = factory2.createVariableStatement( - /*modifiers*/ - void 0, - factory2.createVariableDeclarationList( - [factory2.createVariableDeclaration( - loopResultName, - /*exclamationToken*/ - void 0, - /*type*/ - void 0, - callResult - )] - ) - ); + const stateVariable = factory2.createVariableStatement( /*modifiers*/ + void 0, factory2.createVariableDeclarationList([factory2.createVariableDeclaration(loopResultName, /*exclamationToken*/ + void 0, /*type*/ + void 0, callResult)])); statements.push(stateVariable); copyOutParameters(state.loopOutParameters, 1 /* Body */, 0 /* ToOriginal */, statements); if (state.nonLocalJumps & 8 /* Return */) { @@ -103572,48 +92958,18 @@ ${lanes.join("\n")} } else { returnStatement = factory2.createReturnStatement(factory2.createPropertyAccessExpression(loopResultName, "value")); } - statements.push( - factory2.createIfStatement( - factory2.createTypeCheck(loopResultName, "object"), - returnStatement - ) - ); + statements.push(factory2.createIfStatement(factory2.createTypeCheck(loopResultName, "object"), returnStatement)); } if (state.nonLocalJumps & 2 /* Break */) { - statements.push( - factory2.createIfStatement( - factory2.createStrictEquality( - loopResultName, - factory2.createStringLiteral("break") - ), - factory2.createBreakStatement() - ) - ); + statements.push(factory2.createIfStatement(factory2.createStrictEquality(loopResultName, factory2.createStringLiteral("break")), factory2.createBreakStatement())); } if (state.labeledNonLocalBreaks || state.labeledNonLocalContinues) { const caseClauses = []; - processLabeledJumps( - state.labeledNonLocalBreaks, - /*isBreak*/ - true, - loopResultName, - outerState, - caseClauses - ); - processLabeledJumps( - state.labeledNonLocalContinues, - /*isBreak*/ - false, - loopResultName, - outerState, - caseClauses - ); - statements.push( - factory2.createSwitchStatement( - loopResultName, - factory2.createCaseBlock(caseClauses) - ) - ); + processLabeledJumps(state.labeledNonLocalBreaks, /*isBreak*/ + true, loopResultName, outerState, caseClauses); + processLabeledJumps(state.labeledNonLocalContinues, /*isBreak*/ + false, loopResultName, outerState, caseClauses); + statements.push(factory2.createSwitchStatement(loopResultName, factory2.createCaseBlock(caseClauses))); } } return statements; @@ -103621,12 +92977,12 @@ ${lanes.join("\n")} function setLabeledJump(state, isBreak, labelText, labelMarker) { if (isBreak) { if (!state.labeledNonLocalBreaks) { - state.labeledNonLocalBreaks = /* @__PURE__ */ new Map(); + state.labeledNonLocalBreaks = /* @__PURE__ */new Map(); } state.labeledNonLocalBreaks.set(labelText, labelMarker); } else { if (!state.labeledNonLocalContinues) { - state.labeledNonLocalContinues = /* @__PURE__ */ new Map(); + state.labeledNonLocalContinues = /* @__PURE__ */new Map(); } state.labeledNonLocalContinues.set(labelText, labelMarker); } @@ -103656,13 +93012,9 @@ ${lanes.join("\n")} } } } else { - loopParameters.push(factory2.createParameterDeclaration( - /*modifiers*/ - void 0, - /*dotDotDotToken*/ - void 0, - name - )); + loopParameters.push(factory2.createParameterDeclaration( /*modifiers*/ + void 0, /*dotDotDotToken*/ + void 0, name)); const checkFlags = resolver.getNodeCheckFlags(decl); if (checkFlags & 65536 /* NeedsLoopOutParameter */ || hasCapturedBindingsInForHead) { const outParamName = factory2.createUniqueName("out_" + idText(name)); @@ -103670,15 +93022,22 @@ ${lanes.join("\n")} if (checkFlags & 65536 /* NeedsLoopOutParameter */) { flags |= 1 /* Body */; } + if (isForStatement(container)) { if (container.initializer && resolver.isBindingCapturedByNode(container.initializer, decl)) { flags |= 2 /* Initializer */; } + if (container.condition && resolver.isBindingCapturedByNode(container.condition, decl) || container.incrementor && resolver.isBindingCapturedByNode(container.incrementor, decl)) { flags |= 1 /* Body */; } } - loopOutParameters.push({ flags, originalName: name, outParamName }); + + loopOutParameters.push({ + flags, + originalName: name, + outParamName + }); } } } @@ -103711,14 +93070,7 @@ ${lanes.join("\n")} } } function transformPropertyAssignmentToExpression(property, receiver, startsOnNewLine) { - const expression = factory2.createAssignment( - createMemberAccessForPropertyName( - factory2, - receiver, - Debug.checkDefined(visitNode(property.name, visitor, isPropertyName)) - ), - Debug.checkDefined(visitNode(property.initializer, visitor, isExpression)) - ); + const expression = factory2.createAssignment(createMemberAccessForPropertyName(factory2, receiver, Debug.checkDefined(visitNode(property.name, visitor, isPropertyName))), Debug.checkDefined(visitNode(property.initializer, visitor, isExpression))); setTextRange(expression, property); if (startsOnNewLine) { startOnNewLine(expression); @@ -103726,14 +93078,7 @@ ${lanes.join("\n")} return expression; } function transformShorthandPropertyAssignmentToExpression(property, receiver, startsOnNewLine) { - const expression = factory2.createAssignment( - createMemberAccessForPropertyName( - factory2, - receiver, - Debug.checkDefined(visitNode(property.name, visitor, isPropertyName)) - ), - factory2.cloneNode(property.name) - ); + const expression = factory2.createAssignment(createMemberAccessForPropertyName(factory2, receiver, Debug.checkDefined(visitNode(property.name, visitor, isPropertyName))), factory2.cloneNode(property.name)); setTextRange(expression, property); if (startsOnNewLine) { startOnNewLine(expression); @@ -103741,21 +93086,9 @@ ${lanes.join("\n")} return expression; } function transformObjectLiteralMethodDeclarationToExpression(method, receiver, container, startsOnNewLine) { - const expression = factory2.createAssignment( - createMemberAccessForPropertyName( - factory2, - receiver, - Debug.checkDefined(visitNode(method.name, visitor, isPropertyName)) - ), - transformFunctionLikeToExpression( - method, - /*location*/ - method, - /*name*/ - void 0, - container - ) - ); + const expression = factory2.createAssignment(createMemberAccessForPropertyName(factory2, receiver, Debug.checkDefined(visitNode(method.name, visitor, isPropertyName))), transformFunctionLikeToExpression(method, /*location*/ + method, /*name*/ + void 0, container)); setTextRange(expression, method); if (startsOnNewLine) { startOnNewLine(expression); @@ -103767,26 +93100,15 @@ ${lanes.join("\n")} let updated; Debug.assert(!!node.variableDeclaration, "Catch clause variable should always be present when downleveling ES2015."); if (isBindingPattern(node.variableDeclaration.name)) { - const temp = factory2.createTempVariable( - /*recordTempVariable*/ - void 0 - ); + const temp = factory2.createTempVariable( /*recordTempVariable*/ + void 0); const newVariableDeclaration = factory2.createVariableDeclaration(temp); setTextRange(newVariableDeclaration, node.variableDeclaration); - const vars = flattenDestructuringBinding( - node.variableDeclaration, - visitor, - context, - 0 /* All */, - temp - ); + const vars = flattenDestructuringBinding(node.variableDeclaration, visitor, context, 0 /* All */, temp); const list = factory2.createVariableDeclarationList(vars); setTextRange(list, node.variableDeclaration); - const destructure = factory2.createVariableStatement( - /*modifiers*/ - void 0, - list - ); + const destructure = factory2.createVariableStatement( /*modifiers*/ + void 0, list); updated = factory2.updateCatchClause(node, newVariableDeclaration, addStatementToStartOfBlock(node.block, destructure)); } else { updated = visitEachChild(node, visitor, context); @@ -103800,24 +93122,13 @@ ${lanes.join("\n")} } function visitMethodDeclaration(node) { Debug.assert(!isComputedPropertyName(node.name)); - const functionExpression = transformFunctionLikeToExpression( - node, - /*location*/ - moveRangePos(node, -1), - /*name*/ - void 0, - /*container*/ - void 0 - ); + const functionExpression = transformFunctionLikeToExpression(node, /*location*/ + moveRangePos(node, -1), /*name*/ + void 0, /*container*/ + void 0); setEmitFlags(functionExpression, 1024 /* NoLeadingComments */ | getEmitFlags(functionExpression)); - return setTextRange( - factory2.createPropertyAssignment( - node.name, - functionExpression - ), - /*location*/ - node - ); + return setTextRange(factory2.createPropertyAssignment(node.name, functionExpression), /*location*/ + node); } function visitAccessorDeclaration(node) { Debug.assert(!isComputedPropertyName(node.name)); @@ -103837,14 +93148,8 @@ ${lanes.join("\n")} return updated; } function visitShorthandPropertyAssignment(node) { - return setTextRange( - factory2.createPropertyAssignment( - node.name, - visitIdentifier(factory2.cloneNode(node.name)) - ), - /*location*/ - node - ); + return setTextRange(factory2.createPropertyAssignment(node.name, visitIdentifier(factory2.cloneNode(node.name))), /*location*/ + node); } function visitComputedPropertyName(node) { return visitEachChild(node, visitor, context); @@ -103854,14 +93159,9 @@ ${lanes.join("\n")} } function visitArrayLiteralExpression(node) { if (some(node.elements, isSpreadElement)) { - return transformAndSpreadElements( - node.elements, - /*isArgumentList*/ - false, - !!node.multiLine, - /*hasTrailingComma*/ - !!node.elements.hasTrailingComma - ); + return transformAndSpreadElements(node.elements, /*isArgumentList*/ + false, !!node.multiLine, /*hasTrailingComma*/ + !!node.elements.hasTrailingComma); } return visitEachChild(node, visitor, context); } @@ -103871,29 +93171,21 @@ ${lanes.join("\n")} } const expression = skipOuterExpressions(node.expression); if (expression.kind === 108 /* SuperKeyword */ || isSuperProperty(expression) || some(node.arguments, isSpreadElement)) { - return visitCallExpressionWithPotentialCapturedThisAssignment( - node, - /*assignToCapturedThis*/ - true - ); + return visitCallExpressionWithPotentialCapturedThisAssignment(node, /*assignToCapturedThis*/ + true); } - return factory2.updateCallExpression( - node, - Debug.checkDefined(visitNode(node.expression, callExpressionVisitor, isExpression)), - /*typeArguments*/ - void 0, - visitNodes2(node.arguments, visitor, isExpression) - ); + return factory2.updateCallExpression(node, Debug.checkDefined(visitNode(node.expression, callExpressionVisitor, isExpression)), /*typeArguments*/ + void 0, visitNodes2(node.arguments, visitor, isExpression)); } function visitTypeScriptClassWrapper(node) { const body = cast(cast(skipOuterExpressions(node.expression), isArrowFunction).body, isBlock); - const isVariableStatementWithInitializer = (stmt) => isVariableStatement(stmt) && !!first(stmt.declarationList.declarations).initializer; + const isVariableStatementWithInitializer = stmt => isVariableStatement(stmt) && !!first(stmt.declarationList.declarations).initializer; const savedConvertedLoopState = convertedLoopState; convertedLoopState = void 0; const bodyStatements = visitNodes2(body.statements, classWrapperStatementVisitor, isStatement); convertedLoopState = savedConvertedLoopState; const classStatements = filter(bodyStatements, isVariableStatementWithInitializer); - const remainingStatements = filter(bodyStatements, (stmt) => !isVariableStatementWithInitializer(stmt)); + const remainingStatements = filter(bodyStatements, stmt => !isVariableStatementWithInitializer(stmt)); const varStatement = cast(first(classStatements), isVariableStatement); const variable = varStatement.declarationList.declarations[0]; const initializer = skipOuterExpressions(variable.initializer); @@ -103915,14 +93207,7 @@ ${lanes.join("\n")} } statements.push(funcStatements[classBodyStart]); classBodyStart++; - statements.push( - factory2.createExpressionStatement( - factory2.createAssignment( - aliasAssignment.left, - cast(variable.name, isIdentifier) - ) - ) - ); + statements.push(factory2.createExpressionStatement(factory2.createAssignment(aliasAssignment.left, cast(variable.name, isIdentifier)))); } while (!isReturnStatement(elementAt(funcStatements, classBodyEnd))) { classBodyEnd--; @@ -103939,85 +93224,37 @@ ${lanes.join("\n")} statements.push(statement); } } - addRange( - statements, - classStatements, - /*start*/ - 1 - ); - return factory2.restoreOuterExpressions( - node.expression, - factory2.restoreOuterExpressions( - variable.initializer, - factory2.restoreOuterExpressions( - aliasAssignment && aliasAssignment.right, - factory2.updateCallExpression( - call, - factory2.restoreOuterExpressions( - call.expression, - factory2.updateFunctionExpression( - func, - /*modifiers*/ - void 0, - /*asteriskToken*/ - void 0, - /*name*/ - void 0, - /*typeParameters*/ - void 0, - func.parameters, - /*type*/ - void 0, - factory2.updateBlock( - func.body, - statements - ) - ) - ), - /*typeArguments*/ - void 0, - call.arguments - ) - ) - ) - ); + addRange(statements, classStatements, /*start*/ + 1); + return factory2.restoreOuterExpressions(node.expression, factory2.restoreOuterExpressions(variable.initializer, factory2.restoreOuterExpressions(aliasAssignment && aliasAssignment.right, factory2.updateCallExpression(call, factory2.restoreOuterExpressions(call.expression, factory2.updateFunctionExpression(func, /*modifiers*/ + void 0, /*asteriskToken*/ + void 0, /*name*/ + void 0, /*typeParameters*/ + void 0, func.parameters, /*type*/ + void 0, factory2.updateBlock(func.body, statements))), /*typeArguments*/ + void 0, call.arguments)))); } function visitCallExpressionWithPotentialCapturedThisAssignment(node, assignToCapturedThis) { if (node.transformFlags & 32768 /* ContainsRestOrSpread */ || node.expression.kind === 108 /* SuperKeyword */ || isSuperProperty(skipOuterExpressions(node.expression))) { - const { target, thisArg } = factory2.createCallBinding(node.expression, hoistVariableDeclaration); + const { + target, + thisArg + } = factory2.createCallBinding(node.expression, hoistVariableDeclaration); if (node.expression.kind === 108 /* SuperKeyword */) { setEmitFlags(thisArg, 8 /* NoSubstitution */); } + let resultingCall; if (node.transformFlags & 32768 /* ContainsRestOrSpread */) { - resultingCall = factory2.createFunctionApplyCall( - Debug.checkDefined(visitNode(target, callExpressionVisitor, isExpression)), - node.expression.kind === 108 /* SuperKeyword */ ? thisArg : Debug.checkDefined(visitNode(thisArg, visitor, isExpression)), - transformAndSpreadElements( - node.arguments, - /*isArgumentList*/ - true, - /*multiLine*/ - false, - /*hasTrailingComma*/ - false - ) - ); + resultingCall = factory2.createFunctionApplyCall(Debug.checkDefined(visitNode(target, callExpressionVisitor, isExpression)), node.expression.kind === 108 /* SuperKeyword */ ? thisArg : Debug.checkDefined(visitNode(thisArg, visitor, isExpression)), transformAndSpreadElements(node.arguments, /*isArgumentList*/ + true, /*multiLine*/ + false, /*hasTrailingComma*/ + false)); } else { - resultingCall = setTextRange( - factory2.createFunctionCallCall( - Debug.checkDefined(visitNode(target, callExpressionVisitor, isExpression)), - node.expression.kind === 108 /* SuperKeyword */ ? thisArg : Debug.checkDefined(visitNode(thisArg, visitor, isExpression)), - visitNodes2(node.arguments, visitor, isExpression) - ), - node - ); + resultingCall = setTextRange(factory2.createFunctionCallCall(Debug.checkDefined(visitNode(target, callExpressionVisitor, isExpression)), node.expression.kind === 108 /* SuperKeyword */ ? thisArg : Debug.checkDefined(visitNode(thisArg, visitor, isExpression)), visitNodes2(node.arguments, visitor, isExpression)), node); } if (node.expression.kind === 108 /* SuperKeyword */) { - const initializer = factory2.createLogicalOr( - resultingCall, - createActualThis() - ); + const initializer = factory2.createLogicalOr(resultingCall, createActualThis()); resultingCall = assignToCapturedThis ? factory2.createAssignment(createCapturedThis(), initializer) : initializer; } return setOriginalNode(resultingCall, node); @@ -104025,40 +93262,30 @@ ${lanes.join("\n")} if (isSuperCall(node)) { hierarchyFacts |= 131072 /* CapturedLexicalThis */; } + return visitEachChild(node, visitor, context); } function visitNewExpression(node) { if (some(node.arguments, isSpreadElement)) { - const { target, thisArg } = factory2.createCallBinding(factory2.createPropertyAccessExpression(node.expression, "bind"), hoistVariableDeclaration); - return factory2.createNewExpression( - factory2.createFunctionApplyCall( - Debug.checkDefined(visitNode(target, visitor, isExpression)), - thisArg, - transformAndSpreadElements( - factory2.createNodeArray([factory2.createVoidZero(), ...node.arguments]), - /*isArgumentList*/ - true, - /*multiLine*/ - false, - /*hasTrailingComma*/ - false - ) - ), - /*typeArguments*/ - void 0, - [] - ); + const { + target, + thisArg + } = factory2.createCallBinding(factory2.createPropertyAccessExpression(node.expression, "bind"), hoistVariableDeclaration); + return factory2.createNewExpression(factory2.createFunctionApplyCall(Debug.checkDefined(visitNode(target, visitor, isExpression)), thisArg, transformAndSpreadElements(factory2.createNodeArray([factory2.createVoidZero(), ...node.arguments]), /*isArgumentList*/ + true, /*multiLine*/ + false, /*hasTrailingComma*/ + false)), /*typeArguments*/ + void 0, []); } return visitEachChild(node, visitor, context); } function transformAndSpreadElements(elements, isArgumentList, multiLine, hasTrailingComma) { const numElements = elements.length; const segments = flatten( - // As we visit each element, we return one of two functions to use as the "key": - // - `visitSpanOfSpreads` for one or more contiguous `...` spread expressions, i.e. `...a, ...b` in `[1, 2, ...a, ...b]` - // - `visitSpanOfNonSpreads` for one or more contiguous non-spread elements, i.e. `1, 2`, in `[1, 2, ...a, ...b]` - spanMap(elements, partitionSpread, (partition, visitPartition, _start, end) => visitPartition(partition, multiLine, hasTrailingComma && end === numElements)) - ); + // As we visit each element, we return one of two functions to use as the "key": + // - `visitSpanOfSpreads` for one or more contiguous `...` spread expressions, i.e. `...a, ...b` in `[1, 2, ...a, ...b]` + // - `visitSpanOfNonSpreads` for one or more contiguous non-spread elements, i.e. `1, 2`, in `[1, 2, ...a, ...b]` + spanMap(elements, partitionSpread, (partition, visitPartition, _start, end) => visitPartition(partition, multiLine, hasTrailingComma && end === numElements))); if (segments.length === 1) { const firstSegment = segments[0]; if (isArgumentList && !compilerOptions.downlevelIteration || isPackedArrayLiteral(firstSegment.expression) || isCallToHelper(firstSegment.expression, "___spreadArray")) { @@ -104070,11 +93297,7 @@ ${lanes.join("\n")} let expression = startsWithSpread ? factory2.createArrayLiteralExpression() : segments[0].expression; for (let i = startsWithSpread ? 0 : 1; i < segments.length; i++) { const segment = segments[i]; - expression = helpers.createSpreadArrayHelper( - expression, - segment.expression, - segment.kind === 1 /* UnpackedSpread */ && !isArgumentList - ); + expression = helpers.createSpreadArrayHelper(expression, segment.expression, segment.kind === 1 /* UnpackedSpread */ && !isArgumentList); } return expression; } @@ -104091,20 +93314,15 @@ ${lanes.join("\n")} const isCallToReadHelper = isCallToHelper(expression, "___read"); let kind = isCallToReadHelper || isPackedArrayLiteral(expression) ? 2 /* PackedSpread */ : 1 /* UnpackedSpread */; if (compilerOptions.downlevelIteration && kind === 1 /* UnpackedSpread */ && !isArrayLiteralExpression(expression) && !isCallToReadHelper) { - expression = emitHelpers().createReadHelper( - expression, - /*count*/ - void 0 - ); + expression = emitHelpers().createReadHelper(expression, /*count*/ + void 0); kind = 2 /* PackedSpread */; } + return createSpreadSegment(kind, expression); } function visitSpanOfNonSpreads(chunk, multiLine, hasTrailingComma) { - const expression = factory2.createArrayLiteralExpression( - visitNodes2(factory2.createNodeArray(chunk, hasTrailingComma), visitor, isExpression), - multiLine - ); + const expression = factory2.createArrayLiteralExpression(visitNodes2(factory2.createNodeArray(chunk, hasTrailingComma), visitor, isExpression), multiLine); return createSpreadSegment(0 /* None */, expression); } function visitSpreadElement(node) { @@ -104126,15 +93344,9 @@ ${lanes.join("\n")} return node; } function visitTaggedTemplateExpression(node) { - return processTaggedTemplateExpression( - context, - node, - visitor, - currentSourceFile, - recordTaggedTemplateString, - 1 /* All */ - ); + return processTaggedTemplateExpression(context, node, visitor, currentSourceFile, recordTaggedTemplateString, 1 /* All */); } + function visitTemplateExpression(node) { let expression = factory2.createStringLiteral(node.head.text); for (const span of node.templateSpans) { @@ -104142,18 +93354,15 @@ ${lanes.join("\n")} if (span.literal.text.length > 0) { args.push(factory2.createStringLiteral(span.literal.text)); } - expression = factory2.createCallExpression( - factory2.createPropertyAccessExpression(expression, "concat"), - /*typeArguments*/ - void 0, - args - ); + expression = factory2.createCallExpression(factory2.createPropertyAccessExpression(expression, "concat"), /*typeArguments*/ + void 0, args); } return setTextRange(expression, node); } function createSyntheticSuper() { return factory2.createUniqueName("_super", 16 /* Optimistic */ | 32 /* FileLevel */); } + function visitSuperKeyword(node, isExpressionOfCall) { const expression = hierarchyFacts & 8 /* NonStaticClassElement */ && !isExpressionOfCall ? factory2.createPropertyAccessExpression(setOriginalNode(createSyntheticSuper(), node), "prototype") : createSyntheticSuper(); setOriginalNode(expression, node); @@ -104166,14 +93375,13 @@ ${lanes.join("\n")} hierarchyFacts |= 32768 /* NewTarget */; return factory2.createUniqueName("_newTarget", 16 /* Optimistic */ | 32 /* FileLevel */); } + return node; } function onEmitNode(hint, node, emitCallback) { if (enabledSubstitutions & 1 /* CapturedThis */ && isFunctionLike(node)) { - const ancestorFacts = enterSubtree( - 32670 /* FunctionExcludes */, - getEmitFlags(node) & 16 /* CapturesThis */ ? 65 /* FunctionIncludes */ | 16 /* CapturesThis */ : 65 /* FunctionIncludes */ - ); + const ancestorFacts = enterSubtree(32670 /* FunctionExcludes */, getEmitFlags(node) & 16 /* CapturesThis */ ? 65 /* FunctionIncludes */ | 16 /* CapturesThis */ : 65 /* FunctionIncludes */); + previousOnEmitNode(hint, node, emitCallback); exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */); return; @@ -104186,6 +93394,7 @@ ${lanes.join("\n")} context.enableSubstitution(80 /* Identifier */); } } + function enableSubstitutionsForCapturedThis() { if ((enabledSubstitutions & 1 /* CapturedThis */) === 0) { enabledSubstitutions |= 1 /* CapturedThis */; @@ -104199,6 +93408,7 @@ ${lanes.join("\n")} context.enableEmitNotification(262 /* FunctionDeclaration */); } } + function onSubstituteNode(hint, node) { node = previousOnSubstituteNode(hint, node); if (hint === 1 /* Expression */) { @@ -104302,13 +93512,16 @@ ${lanes.join("\n")} var init_es2015 = __esm({ "src/compiler/transformers/es2015.ts"() { "use strict"; + init_ts2(); } }); // src/compiler/transformers/es5.ts function transformES5(context) { - const { factory: factory2 } = context; + const { + factory: factory2 + } = context; const compilerOptions = context.getCompilerOptions(); let previousOnEmitNode; let noSubstitution; @@ -104379,6 +93592,7 @@ ${lanes.join("\n")} var init_es5 = __esm({ "src/compiler/transformers/es5.ts"() { "use strict"; + init_ts2(); } }); @@ -104543,25 +93757,11 @@ ${lanes.join("\n")} } function visitFunctionDeclaration(node) { if (node.asteriskToken) { - node = setOriginalNode( - setTextRange( - factory2.createFunctionDeclaration( - node.modifiers, - /*asteriskToken*/ - void 0, - node.name, - /*typeParameters*/ - void 0, - visitParameterList(node.parameters, visitor, context), - /*type*/ - void 0, - transformGeneratorFunctionBody(node.body) - ), - /*location*/ - node - ), - node - ); + node = setOriginalNode(setTextRange(factory2.createFunctionDeclaration(node.modifiers, /*asteriskToken*/ + void 0, node.name, /*typeParameters*/ + void 0, visitParameterList(node.parameters, visitor, context), /*type*/ + void 0, transformGeneratorFunctionBody(node.body)), /*location*/ + node), node); } else { const savedInGeneratorFunctionBody = inGeneratorFunctionBody; const savedInStatementContainingYield = inStatementContainingYield; @@ -104580,26 +93780,12 @@ ${lanes.join("\n")} } function visitFunctionExpression(node) { if (node.asteriskToken) { - node = setOriginalNode( - setTextRange( - factory2.createFunctionExpression( - /*modifiers*/ - void 0, - /*asteriskToken*/ - void 0, - node.name, - /*typeParameters*/ - void 0, - visitParameterList(node.parameters, visitor, context), - /*type*/ - void 0, - transformGeneratorFunctionBody(node.body) - ), - /*location*/ - node - ), - node - ); + node = setOriginalNode(setTextRange(factory2.createFunctionExpression( /*modifiers*/ + void 0, /*asteriskToken*/ + void 0, node.name, /*typeParameters*/ + void 0, visitParameterList(node.parameters, visitor, context), /*type*/ + void 0, transformGeneratorFunctionBody(node.body)), /*location*/ + node), node); } else { const savedInGeneratorFunctionBody = inGeneratorFunctionBody; const savedInStatementContainingYield = inStatementContainingYield; @@ -104648,18 +93834,11 @@ ${lanes.join("\n")} operations = void 0; operationArguments = void 0; operationLocations = void 0; - state = factory2.createTempVariable( - /*recordTempVariable*/ - void 0 - ); + state = factory2.createTempVariable( /*recordTempVariable*/ + void 0); resumeLexicalEnvironment(); - const statementOffset = factory2.copyPrologue( - body.statements, - statements2, - /*ensureUseStrict*/ - false, - visitor - ); + const statementOffset = factory2.copyPrologue(body.statements, statements2, /*ensureUseStrict*/ + false, visitor); transformAndEmitStatements(body.statements, statementOffset); const buildResult = build2(); insertStatementsAfterStandardPrologue(statements2, endLexicalEnvironment()); @@ -104694,14 +93873,7 @@ ${lanes.join("\n")} if (variables.length === 0) { return void 0; } - return setSourceMapRange( - factory2.createExpressionStatement( - factory2.inlineExpressions( - map(variables, transformInitializedVariable) - ) - ), - node - ); + return setSourceMapRange(factory2.createExpressionStatement(factory2.inlineExpressions(map(variables, transformInitializedVariable))), node); } } function visitBinaryExpression(node) { @@ -104716,16 +93888,15 @@ ${lanes.join("\n")} } } function visitRightAssociativeBinaryExpression(node) { - const { left, right } = node; + const { + left, + right + } = node; if (containsYield(right)) { let target; switch (left.kind) { case 211 /* PropertyAccessExpression */: - target = factory2.updatePropertyAccessExpression( - left, - cacheExpression(Debug.checkDefined(visitNode(left.expression, visitor, isLeftHandSideExpression))), - left.name - ); + target = factory2.updatePropertyAccessExpression(left, cacheExpression(Debug.checkDefined(visitNode(left.expression, visitor, isLeftHandSideExpression))), left.name); break; case 212 /* ElementAccessExpression */: target = factory2.updateElementAccessExpression(left, cacheExpression(Debug.checkDefined(visitNode(left.expression, visitor, isLeftHandSideExpression))), cacheExpression(Debug.checkDefined(visitNode(left.argumentExpression, visitor, isExpression)))); @@ -104736,20 +93907,7 @@ ${lanes.join("\n")} } const operator = node.operatorToken.kind; if (isCompoundAssignment(operator)) { - return setTextRange( - factory2.createAssignment( - target, - setTextRange( - factory2.createBinaryExpression( - cacheExpression(target), - getNonAssignmentOperatorForCompoundAssignment(operator), - Debug.checkDefined(visitNode(right, visitor, isExpression)) - ), - node - ) - ), - node - ); + return setTextRange(factory2.createAssignment(target, setTextRange(factory2.createBinaryExpression(cacheExpression(target), getNonAssignmentOperatorForCompoundAssignment(operator), Debug.checkDefined(visitNode(right, visitor, isExpression))), node)), node); } else { return factory2.updateBinaryExpression(node, target, node.operatorToken, Debug.checkDefined(visitNode(right, visitor, isExpression))); } @@ -104803,33 +93961,17 @@ ${lanes.join("\n")} function visitLogicalBinaryExpression(node) { const resultLabel = defineLabel(); const resultLocal = declareLocal(); - emitAssignment( - resultLocal, - Debug.checkDefined(visitNode(node.left, visitor, isExpression)), - /*location*/ - node.left - ); + emitAssignment(resultLocal, Debug.checkDefined(visitNode(node.left, visitor, isExpression)), /*location*/ + node.left); if (node.operatorToken.kind === 56 /* AmpersandAmpersandToken */) { - emitBreakWhenFalse( - resultLabel, - resultLocal, - /*location*/ - node.left - ); + emitBreakWhenFalse(resultLabel, resultLocal, /*location*/ + node.left); } else { - emitBreakWhenTrue( - resultLabel, - resultLocal, - /*location*/ - node.left - ); + emitBreakWhenTrue(resultLabel, resultLocal, /*location*/ + node.left); } - emitAssignment( - resultLocal, - Debug.checkDefined(visitNode(node.right, visitor, isExpression)), - /*location*/ - node.right - ); + emitAssignment(resultLocal, Debug.checkDefined(visitNode(node.right, visitor, isExpression)), /*location*/ + node.right); markLabel(resultLabel); return resultLocal; } @@ -104838,26 +93980,14 @@ ${lanes.join("\n")} const whenFalseLabel = defineLabel(); const resultLabel = defineLabel(); const resultLocal = declareLocal(); - emitBreakWhenFalse( - whenFalseLabel, - Debug.checkDefined(visitNode(node.condition, visitor, isExpression)), - /*location*/ - node.condition - ); - emitAssignment( - resultLocal, - Debug.checkDefined(visitNode(node.whenTrue, visitor, isExpression)), - /*location*/ - node.whenTrue - ); + emitBreakWhenFalse(whenFalseLabel, Debug.checkDefined(visitNode(node.condition, visitor, isExpression)), /*location*/ + node.condition); + emitAssignment(resultLocal, Debug.checkDefined(visitNode(node.whenTrue, visitor, isExpression)), /*location*/ + node.whenTrue); emitBreak(resultLabel); markLabel(whenFalseLabel); - emitAssignment( - resultLocal, - Debug.checkDefined(visitNode(node.whenFalse, visitor, isExpression)), - /*location*/ - node.whenFalse - ); + emitAssignment(resultLocal, Debug.checkDefined(visitNode(node.whenFalse, visitor, isExpression)), /*location*/ + node.whenFalse); markLabel(resultLabel); return resultLocal; } @@ -104868,33 +93998,20 @@ ${lanes.join("\n")} const expression = visitNode(node.expression, visitor, isExpression); if (node.asteriskToken) { const iterator = (getEmitFlags(node.expression) & 8388608 /* Iterator */) === 0 ? setTextRange(emitHelpers().createValuesHelper(expression), node) : expression; - emitYieldStar( - iterator, - /*location*/ - node - ); + emitYieldStar(iterator, /*location*/ + node); } else { - emitYield( - expression, - /*location*/ - node - ); + emitYield(expression, /*location*/ + node); } markLabel(resumeLabel); - return createGeneratorResume( - /*location*/ - node - ); + return createGeneratorResume( /*location*/ + node); } function visitArrayLiteralExpression(node) { - return visitElements( - node.elements, - /*leadingElement*/ - void 0, - /*location*/ - void 0, - node.multiLine - ); + return visitElements(node.elements, /*leadingElement*/ + void 0, /*location*/ + void 0, node.multiLine); } function visitElements(elements, leadingElement, location, multiLine) { const numInitialElements = countInitialNodesWithoutYield(elements); @@ -104902,35 +94019,18 @@ ${lanes.join("\n")} if (numInitialElements > 0) { temp = declareLocal(); const initialElements = visitNodes2(elements, visitor, isExpression, 0, numInitialElements); - emitAssignment( - temp, - factory2.createArrayLiteralExpression( - leadingElement ? [leadingElement, ...initialElements] : initialElements - ) - ); + emitAssignment(temp, factory2.createArrayLiteralExpression(leadingElement ? [leadingElement, ...initialElements] : initialElements)); leadingElement = void 0; } const expressions = reduceLeft(elements, reduceElement, [], numInitialElements); - return temp ? factory2.createArrayConcatCall(temp, [factory2.createArrayLiteralExpression(expressions, multiLine)]) : setTextRange( - factory2.createArrayLiteralExpression(leadingElement ? [leadingElement, ...expressions] : expressions, multiLine), - location - ); + return temp ? factory2.createArrayConcatCall(temp, [factory2.createArrayLiteralExpression(expressions, multiLine)]) : setTextRange(factory2.createArrayLiteralExpression(leadingElement ? [leadingElement, ...expressions] : expressions, multiLine), location); function reduceElement(expressions2, element) { if (containsYield(element) && expressions2.length > 0) { const hasAssignedTemp = temp !== void 0; if (!temp) { temp = declareLocal(); } - emitAssignment( - temp, - hasAssignedTemp ? factory2.createArrayConcatCall( - temp, - [factory2.createArrayLiteralExpression(expressions2, multiLine)] - ) : factory2.createArrayLiteralExpression( - leadingElement ? [leadingElement, ...expressions2] : expressions2, - multiLine - ) - ); + emitAssignment(temp, hasAssignedTemp ? factory2.createArrayConcatCall(temp, [factory2.createArrayLiteralExpression(expressions2, multiLine)]) : factory2.createArrayLiteralExpression(leadingElement ? [leadingElement, ...expressions2] : expressions2, multiLine)); leadingElement = void 0; expressions2 = []; } @@ -104943,13 +94043,7 @@ ${lanes.join("\n")} const multiLine = node.multiLine; const numInitialProperties = countInitialNodesWithoutYield(properties); const temp = declareLocal(); - emitAssignment( - temp, - factory2.createObjectLiteralExpression( - visitNodes2(properties, visitor, isObjectLiteralElementLike, 0, numInitialProperties), - multiLine - ) - ); + emitAssignment(temp, factory2.createObjectLiteralExpression(visitNodes2(properties, visitor, isObjectLiteralElementLike, 0, numInitialProperties), multiLine)); const expressions = reduceLeft(properties, reduceProperty, [], numInitialProperties); expressions.push(multiLine ? startOnNewLine(setParent(setTextRange(factory2.cloneNode(temp), temp), temp.parent)) : temp); return factory2.inlineExpressions(expressions); @@ -104977,50 +94071,24 @@ ${lanes.join("\n")} } function visitCallExpression(node) { if (!isImportCall(node) && forEach(node.arguments, containsYield)) { - const { target, thisArg } = factory2.createCallBinding( - node.expression, - hoistVariableDeclaration, - languageVersion, - /*cacheIdentifiers*/ - true - ); - return setOriginalNode( - setTextRange( - factory2.createFunctionApplyCall( - cacheExpression(Debug.checkDefined(visitNode(target, visitor, isLeftHandSideExpression))), - thisArg, - visitElements(node.arguments) - ), - node - ), - node - ); + const { + target, + thisArg + } = factory2.createCallBinding(node.expression, hoistVariableDeclaration, languageVersion, /*cacheIdentifiers*/ + true); + return setOriginalNode(setTextRange(factory2.createFunctionApplyCall(cacheExpression(Debug.checkDefined(visitNode(target, visitor, isLeftHandSideExpression))), thisArg, visitElements(node.arguments)), node), node); } return visitEachChild(node, visitor, context); } function visitNewExpression(node) { if (forEach(node.arguments, containsYield)) { - const { target, thisArg } = factory2.createCallBinding(factory2.createPropertyAccessExpression(node.expression, "bind"), hoistVariableDeclaration); - return setOriginalNode( - setTextRange( - factory2.createNewExpression( - factory2.createFunctionApplyCall( - cacheExpression(Debug.checkDefined(visitNode(target, visitor, isExpression))), - thisArg, - visitElements( - node.arguments, - /*leadingElement*/ - factory2.createVoidZero() - ) - ), - /*typeArguments*/ - void 0, - [] - ), - node - ), - node - ); + const { + target, + thisArg + } = factory2.createCallBinding(factory2.createPropertyAccessExpression(node.expression, "bind"), hoistVariableDeclaration); + return setOriginalNode(setTextRange(factory2.createNewExpression(factory2.createFunctionApplyCall(cacheExpression(Debug.checkDefined(visitNode(target, visitor, isExpression))), thisArg, visitElements(node.arguments, /*leadingElement*/ + factory2.createVoidZero())), /*typeArguments*/ + void 0, []), node), node); } return visitEachChild(node, visitor, context); } @@ -105118,25 +94186,15 @@ ${lanes.join("\n")} return void 0; } function transformInitializedVariable(node) { - return setSourceMapRange( - factory2.createAssignment( - setSourceMapRange(factory2.cloneNode(node.name), node.name), - Debug.checkDefined(visitNode(node.initializer, visitor, isExpression)) - ), - node - ); + return setSourceMapRange(factory2.createAssignment(setSourceMapRange(factory2.cloneNode(node.name), node.name), Debug.checkDefined(visitNode(node.initializer, visitor, isExpression))), node); } function transformAndEmitIfStatement(node) { if (containsYield(node)) { if (containsYield(node.thenStatement) || containsYield(node.elseStatement)) { const endLabel = defineLabel(); const elseLabel = node.elseStatement ? defineLabel() : void 0; - emitBreakWhenFalse( - node.elseStatement ? elseLabel : endLabel, - Debug.checkDefined(visitNode(node.expression, visitor, isExpression)), - /*location*/ - node.expression - ); + emitBreakWhenFalse(node.elseStatement ? elseLabel : endLabel, Debug.checkDefined(visitNode(node.expression, visitor, isExpression)), /*location*/ + node.expression); transformAndEmitEmbeddedStatement(node.thenStatement); if (node.elseStatement) { emitBreak(endLabel); @@ -105155,10 +94213,8 @@ ${lanes.join("\n")} if (containsYield(node)) { const conditionLabel = defineLabel(); const loopLabel = defineLabel(); - beginLoopBlock( - /*continueLabel*/ - conditionLabel - ); + beginLoopBlock( /*continueLabel*/ + conditionLabel); markLabel(loopLabel); transformAndEmitEmbeddedStatement(node.statement); markLabel(conditionLabel); @@ -105211,14 +94267,7 @@ ${lanes.join("\n")} if (isVariableDeclarationList(initializer)) { transformAndEmitVariableDeclarationList(initializer); } else { - emitStatement( - setTextRange( - factory2.createExpressionStatement( - Debug.checkDefined(visitNode(initializer, visitor, isExpression)) - ), - initializer - ) - ); + emitStatement(setTextRange(factory2.createExpressionStatement(Debug.checkDefined(visitNode(initializer, visitor, isExpression))), initializer)); } } markLabel(conditionLabel); @@ -105228,14 +94277,7 @@ ${lanes.join("\n")} transformAndEmitEmbeddedStatement(node.statement); markLabel(incrementLabel); if (node.incrementor) { - emitStatement( - setTextRange( - factory2.createExpressionStatement( - Debug.checkDefined(visitNode(node.incrementor, visitor, isExpression)) - ), - node.incrementor - ) - ); + emitStatement(setTextRange(factory2.createExpressionStatement(Debug.checkDefined(visitNode(node.incrementor, visitor, isExpression))), node.incrementor)); } emitBreak(conditionLabel); endLoopBlock(); @@ -105253,13 +94295,7 @@ ${lanes.join("\n")} hoistVariableDeclaration(variable.name); } const variables = getInitializedVariables(initializer); - node = factory2.updateForStatement( - node, - variables.length > 0 ? factory2.inlineExpressions(map(variables, transformInitializedVariable)) : void 0, - visitNode(node.condition, visitor, isExpression), - visitNode(node.incrementor, visitor, isExpression), - visitIterationBody(node.statement, visitor, context) - ); + node = factory2.updateForStatement(node, variables.length > 0 ? factory2.inlineExpressions(map(variables, transformInitializedVariable)) : void 0, visitNode(node.condition, visitor, isExpression), visitNode(node.incrementor, visitor, isExpression), visitIterationBody(node.statement, visitor, context)); } else { node = visitEachChild(node, visitor, context); } @@ -105278,20 +94314,8 @@ ${lanes.join("\n")} hoistVariableDeclaration(keysIndex); emitAssignment(obj, Debug.checkDefined(visitNode(node.expression, visitor, isExpression))); emitAssignment(keysArray, factory2.createArrayLiteralExpression()); - emitStatement( - factory2.createForInStatement( - key, - obj, - factory2.createExpressionStatement( - factory2.createCallExpression( - factory2.createPropertyAccessExpression(keysArray, "push"), - /*typeArguments*/ - void 0, - [key] - ) - ) - ) - ); + emitStatement(factory2.createForInStatement(key, obj, factory2.createExpressionStatement(factory2.createCallExpression(factory2.createPropertyAccessExpression(keysArray, "push"), /*typeArguments*/ + void 0, [key])))); emitAssignment(keysIndex, factory2.createNumericLiteral(0)); const conditionLabel = defineLabel(); const incrementLabel = defineLabel(); @@ -105341,11 +94365,8 @@ ${lanes.join("\n")} function transformAndEmitContinueStatement(node) { const label = findContinueTarget(node.label ? idText(node.label) : void 0); if (label > 0) { - emitBreak( - label, - /*location*/ - node - ); + emitBreak(label, /*location*/ + node); } else { emitStatement(node); } @@ -105354,11 +94375,8 @@ ${lanes.join("\n")} if (inStatementContainingYield) { const label = findContinueTarget(node.label && idText(node.label)); if (label > 0) { - return createInlineBreak( - label, - /*location*/ - node - ); + return createInlineBreak(label, /*location*/ + node); } } return visitEachChild(node, visitor, context); @@ -105366,11 +94384,8 @@ ${lanes.join("\n")} function transformAndEmitBreakStatement(node) { const label = findBreakTarget(node.label ? idText(node.label) : void 0); if (label > 0) { - emitBreak( - label, - /*location*/ - node - ); + emitBreak(label, /*location*/ + node); } else { emitStatement(node); } @@ -105379,28 +94394,19 @@ ${lanes.join("\n")} if (inStatementContainingYield) { const label = findBreakTarget(node.label && idText(node.label)); if (label > 0) { - return createInlineBreak( - label, - /*location*/ - node - ); + return createInlineBreak(label, /*location*/ + node); } } return visitEachChild(node, visitor, context); } function transformAndEmitReturnStatement(node) { - emitReturn( - visitNode(node.expression, visitor, isExpression), - /*location*/ - node - ); + emitReturn(visitNode(node.expression, visitor, isExpression), /*location*/ + node); } function visitReturnStatement(node) { - return createInlineReturn( - visitNode(node.expression, visitor, isExpression), - /*location*/ - node - ); + return createInlineReturn(visitNode(node.expression, visitor, isExpression), /*location*/ + node); } function transformAndEmitWithStatement(node) { if (containsYield(node)) { @@ -105436,18 +94442,8 @@ ${lanes.join("\n")} if (containsYield(clause.expression) && pendingClauses.length > 0) { break; } - pendingClauses.push( - factory2.createCaseClause( - Debug.checkDefined(visitNode(clause.expression, visitor, isExpression)), - [ - createInlineBreak( - clauseLabels[i], - /*location*/ - clause.expression - ) - ] - ) - ); + pendingClauses.push(factory2.createCaseClause(Debug.checkDefined(visitNode(clause.expression, visitor, isExpression)), [createInlineBreak(clauseLabels[i], /*location*/ + clause.expression)])); } else { defaultClausesSkipped++; } @@ -105506,11 +94502,9 @@ ${lanes.join("\n")} return node; } function transformAndEmitThrowStatement(node) { - emitThrow( - Debug.checkDefined(visitNode(node.expression ?? factory2.createVoidZero(), visitor, isExpression)), - /*location*/ - node - ); + var _node$expression; + emitThrow(Debug.checkDefined(visitNode((_node$expression = node.expression) !== null && _node$expression !== void 0 ? _node$expression : factory2.createVoidZero(), visitor, isExpression)), /*location*/ + node); } function transformAndEmitTryStatement(node) { if (containsYield(node)) { @@ -105577,19 +94571,13 @@ ${lanes.join("\n")} return node; } const temp = factory2.createTempVariable(hoistVariableDeclaration); - emitAssignment( - temp, - node, - /*location*/ - node - ); + emitAssignment(temp, node, /*location*/ + node); return temp; } function declareLocal(name) { - const temp = name ? factory2.createUniqueName(name) : factory2.createTempVariable( - /*recordTempVariable*/ - void 0 - ); + const temp = name ? factory2.createUniqueName(name) : factory2.createTempVariable( /*recordTempVariable*/ + void 0); hoistVariableDeclaration(temp); return temp; } @@ -105622,8 +94610,7 @@ ${lanes.join("\n")} } 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; @@ -105677,10 +94664,11 @@ ${lanes.join("\n")} const text = idText(variable.name); name = declareLocal(text); if (!renamedCatchVariables) { - renamedCatchVariables = /* @__PURE__ */ new Map(); + renamedCatchVariables = /* @__PURE__ */new Map(); renamedCatchVariableDeclarations = []; context.enableSubstitution(80 /* Identifier */); } + renamedCatchVariables.set(text, true); renamedCatchVariableDeclarations[getOriginalNodeId(variable)] = name; } @@ -105693,12 +94681,8 @@ ${lanes.join("\n")} exception.state = 1 /* Catch */; exception.catchVariable = name; exception.catchLabel = catchLabel; - emitAssignment(name, factory2.createCallExpression( - factory2.createPropertyAccessExpression(state, "sent"), - /*typeArguments*/ - void 0, - [] - )); + emitAssignment(name, factory2.createCallExpression(factory2.createPropertyAccessExpression(state, "sent"), /*typeArguments*/ + void 0, [])); emitNop(); } function beginFinallyBlock() { @@ -105725,6 +94709,7 @@ ${lanes.join("\n")} emitNop(); exception.state = 3 /* Done */; } + function beginScriptLoopBlock() { beginBlock({ kind: 3 /* Loop */, @@ -105802,12 +94787,15 @@ ${lanes.join("\n")} function supportsUnlabeledBreak(block) { return block.kind === 2 /* Switch */ || block.kind === 3 /* Loop */; } + function supportsLabeledBreakOrContinue(block) { return block.kind === 4 /* Labeled */; } + function supportsUnlabeledContinue(block) { return block.kind === 3 /* Loop */; } + function hasImmediateContainingLabeledBlock(labelText, start) { for (let j = start; j >= 0; j--) { const containingBlock = blockStack[j]; @@ -105885,40 +94873,19 @@ ${lanes.join("\n")} } function createInlineBreak(label, location) { Debug.assertLessThan(0, label, "Invalid label"); - return setTextRange( - factory2.createReturnStatement( - factory2.createArrayLiteralExpression([ - createInstruction(3 /* Break */), - createLabel(label) - ]) - ), - location - ); + return setTextRange(factory2.createReturnStatement(factory2.createArrayLiteralExpression([createInstruction(3 /* Break */), createLabel(label)])), location); } function createInlineReturn(expression, location) { - return setTextRange( - factory2.createReturnStatement( - factory2.createArrayLiteralExpression( - expression ? [createInstruction(2 /* Return */), expression] : [createInstruction(2 /* Return */)] - ) - ), - location - ); + return setTextRange(factory2.createReturnStatement(factory2.createArrayLiteralExpression(expression ? [createInstruction(2 /* Return */), expression] : [createInstruction(2 /* Return */)])), location); } function createGeneratorResume(location) { - return setTextRange( - factory2.createCallExpression( - factory2.createPropertyAccessExpression(state, "sent"), - /*typeArguments*/ - void 0, - [] - ), - location - ); + return setTextRange(factory2.createCallExpression(factory2.createPropertyAccessExpression(state, "sent"), /*typeArguments*/ + void 0, []), location); } function emitNop() { emitWorker(0 /* Nop */); } + function emitStatement(node) { if (node) { emitWorker(1 /* Statement */, [node]); @@ -105953,6 +94920,7 @@ ${lanes.join("\n")} function emitEndfinally() { emitWorker(10 /* Endfinally */); } + function emitWorker(code, args, location) { if (operations === void 0) { operations = []; @@ -105979,36 +94947,17 @@ ${lanes.join("\n")} currentExceptionBlock = void 0; withBlockStack = void 0; const buildResult = buildStatements(); - return emitHelpers().createGeneratorHelper( - setEmitFlags( - factory2.createFunctionExpression( - /*modifiers*/ - void 0, - /*asteriskToken*/ - void 0, - /*name*/ - void 0, - /*typeParameters*/ - void 0, - [factory2.createParameterDeclaration( - /*modifiers*/ - void 0, - /*dotDotDotToken*/ - void 0, - state - )], - /*type*/ - void 0, - factory2.createBlock( - buildResult, - /*multiLine*/ - buildResult.length > 0 - ) - ), - 1048576 /* ReuseTempVariableScope */ - ) - ); + return emitHelpers().createGeneratorHelper(setEmitFlags(factory2.createFunctionExpression( /*modifiers*/ + void 0, /*asteriskToken*/ + void 0, /*name*/ + void 0, /*typeParameters*/ + void 0, [factory2.createParameterDeclaration( /*modifiers*/ + void 0, /*dotDotDotToken*/ + void 0, state)], /*type*/ + void 0, factory2.createBlock(buildResult, /*multiLine*/ + buildResult.length > 0)), 1048576 /* ReuseTempVariableScope */)); } + function buildStatements() { if (operations) { for (let operationIndex = 0; operationIndex < operations.length; operationIndex++) { @@ -106032,10 +94981,8 @@ ${lanes.join("\n")} if (!statements) { return; } - appendLabel( - /*markLabelEnd*/ - !lastOperationWasAbrupt - ); + appendLabel( /*markLabelEnd*/ + !lastOperationWasAbrupt); lastOperationWasAbrupt = false; lastOperationWasCompletion = false; labelNumber++; @@ -106044,18 +94991,13 @@ ${lanes.join("\n")} if (isFinalLabelReachable(operationIndex)) { tryEnterLabel(operationIndex); withBlockStack = void 0; - writeReturn( - /*expression*/ - void 0, - /*operationLocation*/ - void 0 - ); + writeReturn( /*expression*/ + void 0, /*operationLocation*/ + void 0); } if (statements && clauses) { - appendLabel( - /*markLabelEnd*/ - false - ); + appendLabel( /*markLabelEnd*/ + false); } updateLabelExpressions(); } @@ -106085,43 +95027,21 @@ ${lanes.join("\n")} } } if (currentExceptionBlock) { - const { startLabel, catchLabel, finallyLabel, endLabel } = currentExceptionBlock; - statements.unshift( - factory2.createExpressionStatement( - factory2.createCallExpression( - factory2.createPropertyAccessExpression(factory2.createPropertyAccessExpression(state, "trys"), "push"), - /*typeArguments*/ - void 0, - [ - factory2.createArrayLiteralExpression([ - createLabel(startLabel), - createLabel(catchLabel), - createLabel(finallyLabel), - createLabel(endLabel) - ]) - ] - ) - ) - ); + const { + startLabel, + catchLabel, + finallyLabel, + endLabel + } = currentExceptionBlock; + statements.unshift(factory2.createExpressionStatement(factory2.createCallExpression(factory2.createPropertyAccessExpression(factory2.createPropertyAccessExpression(state, "trys"), "push"), /*typeArguments*/ + void 0, [factory2.createArrayLiteralExpression([createLabel(startLabel), createLabel(catchLabel), createLabel(finallyLabel), createLabel(endLabel)])]))); currentExceptionBlock = void 0; } if (markLabelEnd) { - statements.push( - factory2.createExpressionStatement( - factory2.createAssignment( - factory2.createPropertyAccessExpression(state, "label"), - factory2.createNumericLiteral(labelNumber + 1) - ) - ) - ); + statements.push(factory2.createExpressionStatement(factory2.createAssignment(factory2.createPropertyAccessExpression(state, "label"), factory2.createNumericLiteral(labelNumber + 1)))); } } - clauses.push( - factory2.createCaseClause( - factory2.createNumericLiteral(labelNumber), - statements || [] - ) - ); + clauses.push(factory2.createCaseClause(factory2.createNumericLiteral(labelNumber), statements || [])); statements = void 0; } function tryEnterLabel(operationIndex) { @@ -106251,128 +95171,42 @@ ${lanes.join("\n")} function writeReturn(expression, operationLocation) { lastOperationWasAbrupt = true; lastOperationWasCompletion = true; - writeStatement( - setEmitFlags( - setTextRange( - factory2.createReturnStatement( - factory2.createArrayLiteralExpression( - expression ? [createInstruction(2 /* Return */), expression] : [createInstruction(2 /* Return */)] - ) - ), - operationLocation - ), - 768 /* NoTokenSourceMaps */ - ) - ); + writeStatement(setEmitFlags(setTextRange(factory2.createReturnStatement(factory2.createArrayLiteralExpression(expression ? [createInstruction(2 /* Return */), expression] : [createInstruction(2 /* Return */)])), operationLocation), 768 /* NoTokenSourceMaps */)); } + function writeBreak(label, operationLocation) { lastOperationWasAbrupt = true; - writeStatement( - setEmitFlags( - setTextRange( - factory2.createReturnStatement( - factory2.createArrayLiteralExpression([ - createInstruction(3 /* Break */), - createLabel(label) - ]) - ), - operationLocation - ), - 768 /* NoTokenSourceMaps */ - ) - ); + writeStatement(setEmitFlags(setTextRange(factory2.createReturnStatement(factory2.createArrayLiteralExpression([createInstruction(3 /* Break */), createLabel(label)])), operationLocation), 768 /* NoTokenSourceMaps */)); } + function writeBreakWhenTrue(label, condition, operationLocation) { - writeStatement( - setEmitFlags( - factory2.createIfStatement( - condition, - setEmitFlags( - setTextRange( - factory2.createReturnStatement( - factory2.createArrayLiteralExpression([ - createInstruction(3 /* Break */), - createLabel(label) - ]) - ), - operationLocation - ), - 768 /* NoTokenSourceMaps */ - ) - ), - 1 /* SingleLine */ - ) - ); + writeStatement(setEmitFlags(factory2.createIfStatement(condition, setEmitFlags(setTextRange(factory2.createReturnStatement(factory2.createArrayLiteralExpression([createInstruction(3 /* Break */), createLabel(label)])), operationLocation), 768 /* NoTokenSourceMaps */)), 1 /* SingleLine */)); } + function writeBreakWhenFalse(label, condition, operationLocation) { - writeStatement( - setEmitFlags( - factory2.createIfStatement( - factory2.createLogicalNot(condition), - setEmitFlags( - setTextRange( - factory2.createReturnStatement( - factory2.createArrayLiteralExpression([ - createInstruction(3 /* Break */), - createLabel(label) - ]) - ), - operationLocation - ), - 768 /* NoTokenSourceMaps */ - ) - ), - 1 /* SingleLine */ - ) - ); + writeStatement(setEmitFlags(factory2.createIfStatement(factory2.createLogicalNot(condition), setEmitFlags(setTextRange(factory2.createReturnStatement(factory2.createArrayLiteralExpression([createInstruction(3 /* Break */), createLabel(label)])), operationLocation), 768 /* NoTokenSourceMaps */)), 1 /* SingleLine */)); } + function writeYield(expression, operationLocation) { lastOperationWasAbrupt = true; - writeStatement( - setEmitFlags( - setTextRange( - factory2.createReturnStatement( - factory2.createArrayLiteralExpression( - expression ? [createInstruction(4 /* Yield */), expression] : [createInstruction(4 /* Yield */)] - ) - ), - operationLocation - ), - 768 /* NoTokenSourceMaps */ - ) - ); + writeStatement(setEmitFlags(setTextRange(factory2.createReturnStatement(factory2.createArrayLiteralExpression(expression ? [createInstruction(4 /* Yield */), expression] : [createInstruction(4 /* Yield */)])), operationLocation), 768 /* NoTokenSourceMaps */)); } + function writeYieldStar(expression, operationLocation) { lastOperationWasAbrupt = true; - writeStatement( - setEmitFlags( - setTextRange( - factory2.createReturnStatement( - factory2.createArrayLiteralExpression([ - createInstruction(5 /* YieldStar */), - expression - ]) - ), - operationLocation - ), - 768 /* NoTokenSourceMaps */ - ) - ); + writeStatement(setEmitFlags(setTextRange(factory2.createReturnStatement(factory2.createArrayLiteralExpression([createInstruction(5 /* YieldStar */), expression])), operationLocation), 768 /* NoTokenSourceMaps */)); } + function writeEndfinally() { lastOperationWasAbrupt = true; - writeStatement( - factory2.createReturnStatement( - factory2.createArrayLiteralExpression([ - createInstruction(7 /* Endfinally */) - ]) - ) - ); + writeStatement(factory2.createReturnStatement(factory2.createArrayLiteralExpression([createInstruction(7 /* Endfinally */)]))); } } + var init_generators = __esm({ "src/compiler/transformers/generators.ts"() { "use strict"; + init_ts2(); } }); @@ -106448,25 +95282,13 @@ ${lanes.join("\n")} if (length(currentModuleInfo.exportedNames)) { const chunkSize = 50; for (let i = 0; i < currentModuleInfo.exportedNames.length; i += chunkSize) { - append( - statements, - factory2.createExpressionStatement( - reduceLeft( - currentModuleInfo.exportedNames.slice(i, i + chunkSize), - (prev, nextId) => factory2.createAssignment(factory2.createPropertyAccessExpression(factory2.createIdentifier("exports"), factory2.createIdentifier(idText(nextId))), prev), - factory2.createVoidZero() - ) - ) - ); + append(statements, factory2.createExpressionStatement(reduceLeft(currentModuleInfo.exportedNames.slice(i, i + chunkSize), (prev, nextId) => factory2.createAssignment(factory2.createPropertyAccessExpression(factory2.createIdentifier("exports"), factory2.createIdentifier(idText(nextId))), prev), factory2.createVoidZero()))); } } append(statements, visitNode(currentModuleInfo.externalHelpersImportDeclaration, topLevelVisitor, isStatement)); addRange(statements, visitNodes2(node.statements, topLevelVisitor, isStatement, statementOffset)); - addExportEqualsIfNeeded( - statements, - /*emitAsReturn*/ - false - ); + addExportEqualsIfNeeded(statements, /*emitAsReturn*/ + false); insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment()); const updated = factory2.updateSourceFile(node, setTextRange(factory2.createNodeArray(statements), node.statements)); addEmitHelpers(updated, context.readEmitHelpers()); @@ -106476,236 +95298,78 @@ ${lanes.join("\n")} const define = factory2.createIdentifier("define"); const moduleName = tryGetModuleNameFromFile(factory2, node, host, compilerOptions); const jsonSourceFile = isJsonSourceFile(node) && node; - const { aliasedModuleNames, unaliasedModuleNames, importAliasNames } = collectAsynchronousDependencies( - node, - /*includeNonAmdDependencies*/ - true - ); - const updated = factory2.updateSourceFile( - node, - setTextRange( - factory2.createNodeArray([ - factory2.createExpressionStatement( - factory2.createCallExpression( - define, - /*typeArguments*/ - void 0, - [ - // Add the module name (if provided). - ...moduleName ? [moduleName] : [], - // Add the dependency array argument: - // - // ["require", "exports", module1", "module2", ...] - factory2.createArrayLiteralExpression( - jsonSourceFile ? emptyArray : [ - factory2.createStringLiteral("require"), - factory2.createStringLiteral("exports"), - ...aliasedModuleNames, - ...unaliasedModuleNames - ] - ), - // Add the module body function argument: - // - // function (require, exports, module1, module2) ... - jsonSourceFile ? jsonSourceFile.statements.length ? jsonSourceFile.statements[0].expression : factory2.createObjectLiteralExpression() : factory2.createFunctionExpression( - /*modifiers*/ - void 0, - /*asteriskToken*/ - void 0, - /*name*/ - void 0, - /*typeParameters*/ - void 0, - [ - factory2.createParameterDeclaration( - /*modifiers*/ - void 0, - /*dotDotDotToken*/ - void 0, - "require" - ), - factory2.createParameterDeclaration( - /*modifiers*/ - void 0, - /*dotDotDotToken*/ - void 0, - "exports" - ), - ...importAliasNames - ], - /*type*/ - void 0, - transformAsynchronousModuleBody(node) - ) - ] - ) - ) - ]), - /*location*/ - node.statements - ) - ); + const { + aliasedModuleNames, + unaliasedModuleNames, + importAliasNames + } = collectAsynchronousDependencies(node, /*includeNonAmdDependencies*/ + true); + const updated = factory2.updateSourceFile(node, setTextRange(factory2.createNodeArray([factory2.createExpressionStatement(factory2.createCallExpression(define, /*typeArguments*/ + void 0, [ + // Add the module name (if provided). + ...(moduleName ? [moduleName] : []), + // Add the dependency array argument: + // + // ["require", "exports", module1", "module2", ...] + factory2.createArrayLiteralExpression(jsonSourceFile ? emptyArray : [factory2.createStringLiteral("require"), factory2.createStringLiteral("exports"), ...aliasedModuleNames, ...unaliasedModuleNames]), + // Add the module body function argument: + // + // function (require, exports, module1, module2) ... + jsonSourceFile ? jsonSourceFile.statements.length ? jsonSourceFile.statements[0].expression : factory2.createObjectLiteralExpression() : factory2.createFunctionExpression( /*modifiers*/ + void 0, /*asteriskToken*/ + void 0, /*name*/ + void 0, /*typeParameters*/ + void 0, [factory2.createParameterDeclaration( /*modifiers*/ + void 0, /*dotDotDotToken*/ + void 0, "require"), factory2.createParameterDeclaration( /*modifiers*/ + void 0, /*dotDotDotToken*/ + void 0, "exports"), ...importAliasNames], /*type*/ + void 0, transformAsynchronousModuleBody(node))]))]), /*location*/ + node.statements)); addEmitHelpers(updated, context.readEmitHelpers()); return updated; } function transformUMDModule(node) { - const { aliasedModuleNames, unaliasedModuleNames, importAliasNames } = collectAsynchronousDependencies( - node, - /*includeNonAmdDependencies*/ - false - ); + const { + aliasedModuleNames, + unaliasedModuleNames, + importAliasNames + } = collectAsynchronousDependencies(node, /*includeNonAmdDependencies*/ + false); const moduleName = tryGetModuleNameFromFile(factory2, node, host, compilerOptions); - const umdHeader = factory2.createFunctionExpression( - /*modifiers*/ - void 0, - /*asteriskToken*/ - void 0, - /*name*/ - void 0, - /*typeParameters*/ - void 0, - [factory2.createParameterDeclaration( - /*modifiers*/ - void 0, - /*dotDotDotToken*/ - void 0, - "factory" - )], - /*type*/ - void 0, - setTextRange( - factory2.createBlock( - [ - factory2.createIfStatement( - factory2.createLogicalAnd( - factory2.createTypeCheck(factory2.createIdentifier("module"), "object"), - factory2.createTypeCheck(factory2.createPropertyAccessExpression(factory2.createIdentifier("module"), "exports"), "object") - ), - factory2.createBlock([ - factory2.createVariableStatement( - /*modifiers*/ - void 0, - [ - factory2.createVariableDeclaration( - "v", - /*exclamationToken*/ - void 0, - /*type*/ - void 0, - factory2.createCallExpression( - factory2.createIdentifier("factory"), - /*typeArguments*/ - void 0, - [ - factory2.createIdentifier("require"), - factory2.createIdentifier("exports") - ] - ) - ) - ] - ), - setEmitFlags( - factory2.createIfStatement( - factory2.createStrictInequality( - factory2.createIdentifier("v"), - factory2.createIdentifier("undefined") - ), - factory2.createExpressionStatement( - factory2.createAssignment( - factory2.createPropertyAccessExpression(factory2.createIdentifier("module"), "exports"), - factory2.createIdentifier("v") - ) - ) - ), - 1 /* SingleLine */ - ) - ]), - factory2.createIfStatement( - factory2.createLogicalAnd( - factory2.createTypeCheck(factory2.createIdentifier("define"), "function"), - factory2.createPropertyAccessExpression(factory2.createIdentifier("define"), "amd") - ), - factory2.createBlock([ - factory2.createExpressionStatement( - factory2.createCallExpression( - factory2.createIdentifier("define"), - /*typeArguments*/ - void 0, - [ - // Add the module name (if provided). - ...moduleName ? [moduleName] : [], - factory2.createArrayLiteralExpression([ - factory2.createStringLiteral("require"), - factory2.createStringLiteral("exports"), - ...aliasedModuleNames, - ...unaliasedModuleNames - ]), - factory2.createIdentifier("factory") - ] - ) - ) - ]) - ) - ) - ], - /*multiLine*/ - true - ), - /*location*/ - void 0 - ) - ); - const updated = factory2.updateSourceFile( - node, - setTextRange( - factory2.createNodeArray([ - factory2.createExpressionStatement( - factory2.createCallExpression( - umdHeader, - /*typeArguments*/ - void 0, - [ - // Add the module body function argument: - // - // function (require, exports) ... - factory2.createFunctionExpression( - /*modifiers*/ - void 0, - /*asteriskToken*/ - void 0, - /*name*/ - void 0, - /*typeParameters*/ - void 0, - [ - factory2.createParameterDeclaration( - /*modifiers*/ - void 0, - /*dotDotDotToken*/ - void 0, - "require" - ), - factory2.createParameterDeclaration( - /*modifiers*/ - void 0, - /*dotDotDotToken*/ - void 0, - "exports" - ), - ...importAliasNames - ], - /*type*/ - void 0, - transformAsynchronousModuleBody(node) - ) - ] - ) - ) - ]), - /*location*/ - node.statements - ) - ); + const umdHeader = factory2.createFunctionExpression( /*modifiers*/ + void 0, /*asteriskToken*/ + void 0, /*name*/ + void 0, /*typeParameters*/ + void 0, [factory2.createParameterDeclaration( /*modifiers*/ + void 0, /*dotDotDotToken*/ + void 0, "factory")], /*type*/ + void 0, setTextRange(factory2.createBlock([factory2.createIfStatement(factory2.createLogicalAnd(factory2.createTypeCheck(factory2.createIdentifier("module"), "object"), factory2.createTypeCheck(factory2.createPropertyAccessExpression(factory2.createIdentifier("module"), "exports"), "object")), factory2.createBlock([factory2.createVariableStatement( /*modifiers*/ + void 0, [factory2.createVariableDeclaration("v", /*exclamationToken*/ + void 0, /*type*/ + void 0, factory2.createCallExpression(factory2.createIdentifier("factory"), /*typeArguments*/ + void 0, [factory2.createIdentifier("require"), factory2.createIdentifier("exports")]))]), setEmitFlags(factory2.createIfStatement(factory2.createStrictInequality(factory2.createIdentifier("v"), factory2.createIdentifier("undefined")), factory2.createExpressionStatement(factory2.createAssignment(factory2.createPropertyAccessExpression(factory2.createIdentifier("module"), "exports"), factory2.createIdentifier("v")))), 1 /* SingleLine */)]), factory2.createIfStatement(factory2.createLogicalAnd(factory2.createTypeCheck(factory2.createIdentifier("define"), "function"), factory2.createPropertyAccessExpression(factory2.createIdentifier("define"), "amd")), factory2.createBlock([factory2.createExpressionStatement(factory2.createCallExpression(factory2.createIdentifier("define"), /*typeArguments*/ + void 0, [ + // Add the module name (if provided). + ...(moduleName ? [moduleName] : []), factory2.createArrayLiteralExpression([factory2.createStringLiteral("require"), factory2.createStringLiteral("exports"), ...aliasedModuleNames, ...unaliasedModuleNames]), factory2.createIdentifier("factory")]))])))], /*multiLine*/ + true), /*location*/ + void 0)); + const updated = factory2.updateSourceFile(node, setTextRange(factory2.createNodeArray([factory2.createExpressionStatement(factory2.createCallExpression(umdHeader, /*typeArguments*/ + void 0, [ + // Add the module body function argument: + // + // function (require, exports) ... + factory2.createFunctionExpression( /*modifiers*/ + void 0, /*asteriskToken*/ + void 0, /*name*/ + void 0, /*typeParameters*/ + void 0, [factory2.createParameterDeclaration( /*modifiers*/ + void 0, /*dotDotDotToken*/ + void 0, "require"), factory2.createParameterDeclaration( /*modifiers*/ + void 0, /*dotDotDotToken*/ + void 0, "exports"), ...importAliasNames], /*type*/ + void 0, transformAsynchronousModuleBody(node))]))]), /*location*/ + node.statements)); addEmitHelpers(updated, context.readEmitHelpers()); return updated; } @@ -106716,13 +95380,9 @@ ${lanes.join("\n")} for (const amdDependency of node.amdDependencies) { if (amdDependency.name) { aliasedModuleNames.push(factory2.createStringLiteral(amdDependency.path)); - importAliasNames.push(factory2.createParameterDeclaration( - /*modifiers*/ - void 0, - /*dotDotDotToken*/ - void 0, - amdDependency.name - )); + importAliasNames.push(factory2.createParameterDeclaration( /*modifiers*/ + void 0, /*dotDotDotToken*/ + void 0, amdDependency.name)); } else { unaliasedModuleNames.push(factory2.createStringLiteral(amdDependency.path)); } @@ -106734,19 +95394,19 @@ ${lanes.join("\n")} if (includeNonAmdDependencies && importAliasName) { setEmitFlags(importAliasName, 8 /* NoSubstitution */); aliasedModuleNames.push(externalModuleName); - importAliasNames.push(factory2.createParameterDeclaration( - /*modifiers*/ - void 0, - /*dotDotDotToken*/ - void 0, - importAliasName - )); + importAliasNames.push(factory2.createParameterDeclaration( /*modifiers*/ + void 0, /*dotDotDotToken*/ + void 0, importAliasName)); } else { unaliasedModuleNames.push(externalModuleName); } } } - return { aliasedModuleNames, unaliasedModuleNames, importAliasNames }; + return { + aliasedModuleNames, + unaliasedModuleNames, + importAliasNames + }; } function getAMDImportExpressionForImport(node) { if (isImportEqualsDeclaration(node) || isExportDeclaration(node) || !getExternalModuleNameLiteral(factory2, node, currentSourceFile, host, resolver, compilerOptions)) { @@ -106762,13 +95422,8 @@ ${lanes.join("\n")} function transformAsynchronousModuleBody(node) { startLexicalEnvironment(); const statements = []; - const statementOffset = factory2.copyPrologue( - node.statements, - statements, - /*ensureUseStrict*/ - !compilerOptions.noImplicitUseStrict, - topLevelVisitor - ); + const statementOffset = factory2.copyPrologue(node.statements, statements, /*ensureUseStrict*/ + !compilerOptions.noImplicitUseStrict, topLevelVisitor); if (shouldEmitUnderscoreUnderscoreESModule()) { append(statements, createUnderscoreUnderscoreESModule()); } @@ -106780,17 +95435,11 @@ ${lanes.join("\n")} addRange(statements, mapDefined(currentModuleInfo.externalImports, getAMDImportExpressionForImport)); } addRange(statements, visitNodes2(node.statements, topLevelVisitor, isStatement, statementOffset)); - addExportEqualsIfNeeded( - statements, - /*emitAsReturn*/ - true - ); + addExportEqualsIfNeeded(statements, /*emitAsReturn*/ + true); insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment()); - const body = factory2.createBlock( - statements, - /*multiLine*/ - true - ); + const body = factory2.createBlock(statements, /*multiLine*/ + true); if (needUMDDynamicImportHelper) { addEmitHelper(body, dynamicImportUMDHelper); } @@ -106806,15 +95455,7 @@ ${lanes.join("\n")} setEmitFlags(statement, 768 /* NoTokenSourceMaps */ | 3072 /* NoComments */); statements.push(statement); } else { - const statement = factory2.createExpressionStatement( - factory2.createAssignment( - factory2.createPropertyAccessExpression( - factory2.createIdentifier("module"), - "exports" - ), - expressionResult - ) - ); + const statement = factory2.createExpressionStatement(factory2.createAssignment(factory2.createPropertyAccessExpression(factory2.createIdentifier("module"), "exports"), expressionResult)); setTextRange(statement, currentModuleInfo.exportEquals); setEmitFlags(statement, 3072 /* NoComments */); statements.push(statement); @@ -106845,11 +95486,8 @@ ${lanes.join("\n")} case 263 /* ClassDeclaration */: return visitClassDeclaration(node); case 248 /* ForStatement */: - return visitForStatement( - node, - /*isTopLevel*/ - true - ); + return visitForStatement(node, /*isTopLevel*/ + true); case 249 /* ForInStatement */: return visitForInStatement(node); case 250 /* ForOfStatement */: @@ -106888,11 +95526,8 @@ ${lanes.join("\n")} } switch (node.kind) { case 248 /* ForStatement */: - return visitForStatement( - node, - /*isTopLevel*/ - false - ); + return visitForStatement(node, /*isTopLevel*/ + false); case 244 /* ExpressionStatement */: return visitExpressionStatement(node); case 217 /* ParenthesizedExpression */: @@ -106916,18 +95551,12 @@ ${lanes.join("\n")} return visitEachChild(node, visitor, context); } function visitor(node) { - return visitorWorker( - node, - /*valueIsDiscarded*/ - false - ); + return visitorWorker(node, /*valueIsDiscarded*/ + false); } function discardedValueVisitor(node) { - return visitorWorker( - node, - /*valueIsDiscarded*/ - true - ); + return visitorWorker(node, /*valueIsDiscarded*/ + true); } function destructuringNeedsFlattening(node) { if (isObjectLiteralExpression(node)) { @@ -106979,157 +95608,81 @@ ${lanes.join("\n")} } function visitForStatement(node, isTopLevel) { if (isTopLevel && node.initializer && isVariableDeclarationList(node.initializer) && !(node.initializer.flags & 7 /* BlockScoped */)) { - const exportStatements = appendExportsOfVariableDeclarationList( - /*statements*/ - void 0, - node.initializer, - /*isForInOrOfInitializer*/ - false - ); + const exportStatements = appendExportsOfVariableDeclarationList( /*statements*/ + void 0, node.initializer, /*isForInOrOfInitializer*/ + false); if (exportStatements) { const statements = []; const varDeclList = visitNode(node.initializer, discardedValueVisitor, isVariableDeclarationList); - const varStatement = factory2.createVariableStatement( - /*modifiers*/ - void 0, - varDeclList - ); + const varStatement = factory2.createVariableStatement( /*modifiers*/ + void 0, varDeclList); statements.push(varStatement); addRange(statements, exportStatements); const condition = visitNode(node.condition, visitor, isExpression); const incrementor = visitNode(node.incrementor, discardedValueVisitor, isExpression); const body = visitIterationBody(node.statement, isTopLevel ? topLevelNestedVisitor : visitor, context); - statements.push(factory2.updateForStatement( - node, - /*initializer*/ - void 0, - condition, - incrementor, - body - )); + statements.push(factory2.updateForStatement(node, /*initializer*/ + void 0, condition, incrementor, body)); return statements; } } - return factory2.updateForStatement( - node, - visitNode(node.initializer, discardedValueVisitor, isForInitializer), - visitNode(node.condition, visitor, isExpression), - visitNode(node.incrementor, discardedValueVisitor, isExpression), - visitIterationBody(node.statement, isTopLevel ? topLevelNestedVisitor : visitor, context) - ); + return factory2.updateForStatement(node, visitNode(node.initializer, discardedValueVisitor, isForInitializer), visitNode(node.condition, visitor, isExpression), visitNode(node.incrementor, discardedValueVisitor, isExpression), visitIterationBody(node.statement, isTopLevel ? topLevelNestedVisitor : visitor, context)); } function visitForInStatement(node) { if (isVariableDeclarationList(node.initializer) && !(node.initializer.flags & 7 /* BlockScoped */)) { - const exportStatements = appendExportsOfVariableDeclarationList( - /*statements*/ - void 0, - node.initializer, - /*isForInOrOfInitializer*/ - true - ); + const exportStatements = appendExportsOfVariableDeclarationList( /*statements*/ + void 0, node.initializer, /*isForInOrOfInitializer*/ + true); if (some(exportStatements)) { const initializer = visitNode(node.initializer, discardedValueVisitor, isForInitializer); const expression = visitNode(node.expression, visitor, isExpression); const body = visitIterationBody(node.statement, topLevelNestedVisitor, context); - const mergedBody = isBlock(body) ? factory2.updateBlock(body, [...exportStatements, ...body.statements]) : factory2.createBlock( - [...exportStatements, body], - /*multiLine*/ - true - ); + const mergedBody = isBlock(body) ? factory2.updateBlock(body, [...exportStatements, ...body.statements]) : factory2.createBlock([...exportStatements, body], /*multiLine*/ + true); return factory2.updateForInStatement(node, initializer, expression, mergedBody); } } - return factory2.updateForInStatement( - node, - visitNode(node.initializer, discardedValueVisitor, isForInitializer), - visitNode(node.expression, visitor, isExpression), - visitIterationBody(node.statement, topLevelNestedVisitor, context) - ); + return factory2.updateForInStatement(node, visitNode(node.initializer, discardedValueVisitor, isForInitializer), visitNode(node.expression, visitor, isExpression), visitIterationBody(node.statement, topLevelNestedVisitor, context)); } function visitForOfStatement(node) { if (isVariableDeclarationList(node.initializer) && !(node.initializer.flags & 7 /* BlockScoped */)) { - const exportStatements = appendExportsOfVariableDeclarationList( - /*statements*/ - void 0, - node.initializer, - /*isForInOrOfInitializer*/ - true - ); + const exportStatements = appendExportsOfVariableDeclarationList( /*statements*/ + void 0, node.initializer, /*isForInOrOfInitializer*/ + true); const initializer = visitNode(node.initializer, discardedValueVisitor, isForInitializer); const expression = visitNode(node.expression, visitor, isExpression); let body = visitIterationBody(node.statement, topLevelNestedVisitor, context); if (some(exportStatements)) { - body = isBlock(body) ? factory2.updateBlock(body, [...exportStatements, ...body.statements]) : factory2.createBlock( - [...exportStatements, body], - /*multiLine*/ - true - ); + body = isBlock(body) ? factory2.updateBlock(body, [...exportStatements, ...body.statements]) : factory2.createBlock([...exportStatements, body], /*multiLine*/ + true); } return factory2.updateForOfStatement(node, node.awaitModifier, initializer, expression, body); } - return factory2.updateForOfStatement( - node, - node.awaitModifier, - visitNode(node.initializer, discardedValueVisitor, isForInitializer), - visitNode(node.expression, visitor, isExpression), - visitIterationBody(node.statement, topLevelNestedVisitor, context) - ); + return factory2.updateForOfStatement(node, node.awaitModifier, visitNode(node.initializer, discardedValueVisitor, isForInitializer), visitNode(node.expression, visitor, isExpression), visitIterationBody(node.statement, topLevelNestedVisitor, context)); } function visitDoStatement(node) { - return factory2.updateDoStatement( - node, - visitIterationBody(node.statement, topLevelNestedVisitor, context), - visitNode(node.expression, visitor, isExpression) - ); + return factory2.updateDoStatement(node, visitIterationBody(node.statement, topLevelNestedVisitor, context), visitNode(node.expression, visitor, isExpression)); } function visitWhileStatement(node) { - return factory2.updateWhileStatement( - node, - visitNode(node.expression, visitor, isExpression), - visitIterationBody(node.statement, topLevelNestedVisitor, context) - ); + return factory2.updateWhileStatement(node, visitNode(node.expression, visitor, isExpression), visitIterationBody(node.statement, topLevelNestedVisitor, context)); } function visitLabeledStatement(node) { - return factory2.updateLabeledStatement( - node, - node.label, - Debug.checkDefined(visitNode(node.statement, topLevelNestedVisitor, isStatement, factory2.liftToBlock)) - ); + return factory2.updateLabeledStatement(node, node.label, Debug.checkDefined(visitNode(node.statement, topLevelNestedVisitor, isStatement, factory2.liftToBlock))); } function visitWithStatement(node) { - return factory2.updateWithStatement( - node, - visitNode(node.expression, visitor, isExpression), - Debug.checkDefined(visitNode(node.statement, topLevelNestedVisitor, isStatement, factory2.liftToBlock)) - ); + return factory2.updateWithStatement(node, visitNode(node.expression, visitor, isExpression), Debug.checkDefined(visitNode(node.statement, topLevelNestedVisitor, isStatement, factory2.liftToBlock))); } function visitIfStatement(node) { - return factory2.updateIfStatement( - node, - visitNode(node.expression, visitor, isExpression), - Debug.checkDefined(visitNode(node.thenStatement, topLevelNestedVisitor, isStatement, factory2.liftToBlock)), - visitNode(node.elseStatement, topLevelNestedVisitor, isStatement, factory2.liftToBlock) - ); + return factory2.updateIfStatement(node, visitNode(node.expression, visitor, isExpression), Debug.checkDefined(visitNode(node.thenStatement, topLevelNestedVisitor, isStatement, factory2.liftToBlock)), visitNode(node.elseStatement, topLevelNestedVisitor, isStatement, factory2.liftToBlock)); } function visitSwitchStatement(node) { - return factory2.updateSwitchStatement( - node, - visitNode(node.expression, visitor, isExpression), - Debug.checkDefined(visitNode(node.caseBlock, topLevelNestedVisitor, isCaseBlock)) - ); + return factory2.updateSwitchStatement(node, visitNode(node.expression, visitor, isExpression), Debug.checkDefined(visitNode(node.caseBlock, topLevelNestedVisitor, isCaseBlock))); } function visitCaseBlock(node) { - return factory2.updateCaseBlock( - node, - visitNodes2(node.clauses, topLevelNestedVisitor, isCaseOrDefaultClause) - ); + return factory2.updateCaseBlock(node, visitNodes2(node.clauses, topLevelNestedVisitor, isCaseOrDefaultClause)); } function visitCaseClause(node) { - return factory2.updateCaseClause( - node, - visitNode(node.expression, visitor, isExpression), - visitNodes2(node.statements, topLevelNestedVisitor, isStatement) - ); + return factory2.updateCaseClause(node, visitNode(node.expression, visitor, isExpression), visitNodes2(node.statements, topLevelNestedVisitor, isStatement)); } function visitDefaultClause(node) { return visitEachChild(node, topLevelNestedVisitor, context); @@ -107138,21 +95691,14 @@ ${lanes.join("\n")} return visitEachChild(node, topLevelNestedVisitor, context); } function visitCatchClause(node) { - return factory2.updateCatchClause( - node, - node.variableDeclaration, - Debug.checkDefined(visitNode(node.block, topLevelNestedVisitor, isBlock)) - ); + return factory2.updateCatchClause(node, node.variableDeclaration, Debug.checkDefined(visitNode(node.block, topLevelNestedVisitor, isBlock))); } function visitBlock(node) { node = visitEachChild(node, topLevelNestedVisitor, context); return node; } function visitExpressionStatement(node) { - return factory2.updateExpressionStatement( - node, - visitNode(node.expression, discardedValueVisitor, isExpression) - ); + return factory2.updateExpressionStatement(node, visitNode(node.expression, discardedValueVisitor, isExpression)); } function visitParenthesizedExpression(node, valueIsDiscarded) { return factory2.updateParenthesizedExpression(node, visitNode(node.expression, valueIsDiscarded ? discardedValueVisitor : visitor, isExpression)); @@ -107205,7 +95751,7 @@ ${lanes.join("\n")} case 2 /* AMD */: return createImportCallExpressionAMD(argument, containsLexicalThis); case 3 /* UMD */: - return createImportCallExpressionUMD(argument ?? factory2.createVoidZero(), containsLexicalThis); + return createImportCallExpressionUMD(argument !== null && argument !== void 0 ? argument : factory2.createVoidZero(), containsLexicalThis); case 1 /* CommonJS */: default: return createImportCallExpressionCommonJS(argument); @@ -107215,198 +95761,96 @@ ${lanes.join("\n")} needUMDDynamicImportHelper = true; if (isSimpleCopiableExpression(arg)) { const argClone = isGeneratedIdentifier(arg) ? arg : isStringLiteral(arg) ? factory2.createStringLiteralFromNode(arg) : setEmitFlags(setTextRange(factory2.cloneNode(arg), arg), 3072 /* NoComments */); - return factory2.createConditionalExpression( - /*condition*/ - factory2.createIdentifier("__syncRequire"), - /*questionToken*/ - void 0, - /*whenTrue*/ - createImportCallExpressionCommonJS(arg), - /*colonToken*/ - void 0, - /*whenFalse*/ - createImportCallExpressionAMD(argClone, containsLexicalThis) - ); + return factory2.createConditionalExpression( /*condition*/ + factory2.createIdentifier("__syncRequire"), /*questionToken*/ + void 0, /*whenTrue*/ + createImportCallExpressionCommonJS(arg), /*colonToken*/ + void 0, /*whenFalse*/ + createImportCallExpressionAMD(argClone, containsLexicalThis)); } else { const temp = factory2.createTempVariable(hoistVariableDeclaration); - return factory2.createComma( - factory2.createAssignment(temp, arg), - factory2.createConditionalExpression( - /*condition*/ - factory2.createIdentifier("__syncRequire"), - /*questionToken*/ - void 0, - /*whenTrue*/ - createImportCallExpressionCommonJS( - temp, - /*isInlineable*/ - true - ), - /*colonToken*/ - void 0, - /*whenFalse*/ - createImportCallExpressionAMD(temp, containsLexicalThis) - ) - ); + return factory2.createComma(factory2.createAssignment(temp, arg), factory2.createConditionalExpression( /*condition*/ + factory2.createIdentifier("__syncRequire"), /*questionToken*/ + void 0, /*whenTrue*/ + createImportCallExpressionCommonJS(temp, /*isInlineable*/ + true), /*colonToken*/ + void 0, /*whenFalse*/ + createImportCallExpressionAMD(temp, containsLexicalThis))); } } function createImportCallExpressionAMD(arg, containsLexicalThis) { const resolve = factory2.createUniqueName("resolve"); const reject = factory2.createUniqueName("reject"); - const parameters = [ - factory2.createParameterDeclaration( - /*modifiers*/ - void 0, - /*dotDotDotToken*/ - void 0, - /*name*/ - resolve - ), - factory2.createParameterDeclaration( - /*modifiers*/ - void 0, - /*dotDotDotToken*/ - void 0, - /*name*/ - reject - ) - ]; - const body = factory2.createBlock([ - factory2.createExpressionStatement( - factory2.createCallExpression( - factory2.createIdentifier("require"), - /*typeArguments*/ - void 0, - [factory2.createArrayLiteralExpression([arg || factory2.createOmittedExpression()]), resolve, reject] - ) - ) - ]); + const parameters = [factory2.createParameterDeclaration( /*modifiers*/ + void 0, /*dotDotDotToken*/ + void 0, /*name*/ + resolve), factory2.createParameterDeclaration( /*modifiers*/ + void 0, /*dotDotDotToken*/ + void 0, /*name*/ + reject)]; + const body = factory2.createBlock([factory2.createExpressionStatement(factory2.createCallExpression(factory2.createIdentifier("require"), /*typeArguments*/ + void 0, [factory2.createArrayLiteralExpression([arg || factory2.createOmittedExpression()]), resolve, reject]))]); let func; if (languageVersion >= 2 /* ES2015 */) { - func = factory2.createArrowFunction( - /*modifiers*/ - void 0, - /*typeParameters*/ - void 0, - parameters, - /*type*/ - void 0, - /*equalsGreaterThanToken*/ - void 0, - body - ); + func = factory2.createArrowFunction( /*modifiers*/ + void 0, /*typeParameters*/ + void 0, parameters, /*type*/ + void 0, /*equalsGreaterThanToken*/ + void 0, body); } else { - func = factory2.createFunctionExpression( - /*modifiers*/ - void 0, - /*asteriskToken*/ - void 0, - /*name*/ - void 0, - /*typeParameters*/ - void 0, - parameters, - /*type*/ - void 0, - body - ); + func = factory2.createFunctionExpression( /*modifiers*/ + void 0, /*asteriskToken*/ + void 0, /*name*/ + void 0, /*typeParameters*/ + void 0, parameters, /*type*/ + void 0, body); if (containsLexicalThis) { setEmitFlags(func, 16 /* CapturesThis */); } } - const promise = factory2.createNewExpression( - factory2.createIdentifier("Promise"), - /*typeArguments*/ - void 0, - [func] - ); + + const promise = factory2.createNewExpression(factory2.createIdentifier("Promise"), /*typeArguments*/ + void 0, [func]); if (getESModuleInterop(compilerOptions)) { - return factory2.createCallExpression( - factory2.createPropertyAccessExpression(promise, factory2.createIdentifier("then")), - /*typeArguments*/ - void 0, - [emitHelpers().createImportStarCallbackHelper()] - ); + return factory2.createCallExpression(factory2.createPropertyAccessExpression(promise, factory2.createIdentifier("then")), /*typeArguments*/ + void 0, [emitHelpers().createImportStarCallbackHelper()]); } return promise; } function createImportCallExpressionCommonJS(arg, isInlineable) { const needSyncEval = arg && !isSimpleInlineableExpression(arg) && !isInlineable; - const promiseResolveCall = factory2.createCallExpression( - factory2.createPropertyAccessExpression(factory2.createIdentifier("Promise"), "resolve"), - /*typeArguments*/ - void 0, - /*argumentsArray*/ - needSyncEval ? languageVersion >= 2 /* ES2015 */ ? [ - factory2.createTemplateExpression(factory2.createTemplateHead(""), [ - factory2.createTemplateSpan(arg, factory2.createTemplateTail("")) - ]) - ] : [ - factory2.createCallExpression( - factory2.createPropertyAccessExpression(factory2.createStringLiteral(""), "concat"), - /*typeArguments*/ - void 0, - [arg] - ) - ] : [] - ); - let requireCall = factory2.createCallExpression( - factory2.createIdentifier("require"), - /*typeArguments*/ - void 0, - needSyncEval ? [factory2.createIdentifier("s")] : arg ? [arg] : [] - ); + const promiseResolveCall = factory2.createCallExpression(factory2.createPropertyAccessExpression(factory2.createIdentifier("Promise"), "resolve"), /*typeArguments*/ + void 0, /*argumentsArray*/ + needSyncEval ? languageVersion >= 2 /* ES2015 */ ? [factory2.createTemplateExpression(factory2.createTemplateHead(""), [factory2.createTemplateSpan(arg, factory2.createTemplateTail(""))])] : [factory2.createCallExpression(factory2.createPropertyAccessExpression(factory2.createStringLiteral(""), "concat"), /*typeArguments*/ + void 0, [arg])] : []); + let requireCall = factory2.createCallExpression(factory2.createIdentifier("require"), /*typeArguments*/ + void 0, needSyncEval ? [factory2.createIdentifier("s")] : arg ? [arg] : []); if (getESModuleInterop(compilerOptions)) { requireCall = emitHelpers().createImportStarHelper(requireCall); } - const parameters = needSyncEval ? [ - factory2.createParameterDeclaration( - /*modifiers*/ - void 0, - /*dotDotDotToken*/ - void 0, - /*name*/ - "s" - ) - ] : []; + const parameters = needSyncEval ? [factory2.createParameterDeclaration( /*modifiers*/ + void 0, /*dotDotDotToken*/ + void 0, /*name*/ + "s")] : []; let func; if (languageVersion >= 2 /* ES2015 */) { - func = factory2.createArrowFunction( - /*modifiers*/ - void 0, - /*typeParameters*/ - void 0, - /*parameters*/ - parameters, - /*type*/ - void 0, - /*equalsGreaterThanToken*/ - void 0, - requireCall - ); + func = factory2.createArrowFunction( /*modifiers*/ + void 0, /*typeParameters*/ + void 0, /*parameters*/ + parameters, /*type*/ + void 0, /*equalsGreaterThanToken*/ + void 0, requireCall); } else { - func = factory2.createFunctionExpression( - /*modifiers*/ - void 0, - /*asteriskToken*/ - void 0, - /*name*/ - void 0, - /*typeParameters*/ - void 0, - /*parameters*/ - parameters, - /*type*/ - void 0, - factory2.createBlock([factory2.createReturnStatement(requireCall)]) - ); + func = factory2.createFunctionExpression( /*modifiers*/ + void 0, /*asteriskToken*/ + void 0, /*name*/ + void 0, /*typeParameters*/ + void 0, /*parameters*/ + parameters, /*type*/ + void 0, factory2.createBlock([factory2.createReturnStatement(requireCall)])); } - const downleveledImport = factory2.createCallExpression( - factory2.createPropertyAccessExpression(promiseResolveCall, "then"), - /*typeArguments*/ - void 0, - [func] - ); + const downleveledImport = factory2.createCallExpression(factory2.createPropertyAccessExpression(promiseResolveCall, "then"), /*typeArguments*/ + void 0, [func]); return downleveledImport; } function getHelperExpressionForExport(node, innerExpr) { @@ -107439,90 +95883,33 @@ ${lanes.join("\n")} } else { const variables = []; if (namespaceDeclaration && !isDefaultImport(node)) { - variables.push( - factory2.createVariableDeclaration( - factory2.cloneNode(namespaceDeclaration.name), - /*exclamationToken*/ - void 0, - /*type*/ - void 0, - getHelperExpressionForImport(node, createRequireCall2(node)) - ) - ); + variables.push(factory2.createVariableDeclaration(factory2.cloneNode(namespaceDeclaration.name), /*exclamationToken*/ + void 0, /*type*/ + void 0, getHelperExpressionForImport(node, createRequireCall2(node)))); } else { - variables.push( - factory2.createVariableDeclaration( - factory2.getGeneratedNameForNode(node), - /*exclamationToken*/ - void 0, - /*type*/ - void 0, - getHelperExpressionForImport(node, createRequireCall2(node)) - ) - ); + variables.push(factory2.createVariableDeclaration(factory2.getGeneratedNameForNode(node), /*exclamationToken*/ + void 0, /*type*/ + void 0, getHelperExpressionForImport(node, createRequireCall2(node)))); if (namespaceDeclaration && isDefaultImport(node)) { - variables.push( - factory2.createVariableDeclaration( - factory2.cloneNode(namespaceDeclaration.name), - /*exclamationToken*/ - void 0, - /*type*/ - void 0, - factory2.getGeneratedNameForNode(node) - ) - ); + variables.push(factory2.createVariableDeclaration(factory2.cloneNode(namespaceDeclaration.name), /*exclamationToken*/ + void 0, /*type*/ + void 0, factory2.getGeneratedNameForNode(node))); } } - statements = append( - statements, - setOriginalNode( - setTextRange( - factory2.createVariableStatement( - /*modifiers*/ - void 0, - factory2.createVariableDeclarationList( - variables, - languageVersion >= 2 /* ES2015 */ ? 2 /* Const */ : 0 /* None */ - ) - ), - /*location*/ - node - ), - /*original*/ - node - ) - ); + statements = append(statements, setOriginalNode(setTextRange(factory2.createVariableStatement( /*modifiers*/ + void 0, factory2.createVariableDeclarationList(variables, languageVersion >= 2 /* ES2015 */ ? 2 /* Const */ : 0 /* None */)), /*location*/ + node), /*original*/ + node)); } } else if (namespaceDeclaration && isDefaultImport(node)) { - statements = append( - statements, - factory2.createVariableStatement( - /*modifiers*/ - void 0, - factory2.createVariableDeclarationList( - [ - setOriginalNode( - setTextRange( - factory2.createVariableDeclaration( - factory2.cloneNode(namespaceDeclaration.name), - /*exclamationToken*/ - void 0, - /*type*/ - void 0, - factory2.getGeneratedNameForNode(node) - ), - /*location*/ - node - ), - /*original*/ - node - ) - ], - languageVersion >= 2 /* ES2015 */ ? 2 /* Const */ : 0 /* None */ - ) - ) - ); + statements = append(statements, factory2.createVariableStatement( /*modifiers*/ + void 0, factory2.createVariableDeclarationList([setOriginalNode(setTextRange(factory2.createVariableDeclaration(factory2.cloneNode(namespaceDeclaration.name), /*exclamationToken*/ + void 0, /*type*/ + void 0, factory2.getGeneratedNameForNode(node)), /*location*/ + node), /*original*/ + node)], languageVersion >= 2 /* ES2015 */ ? 2 /* Const */ : 0 /* None */))); } + statements = appendExportsOfImportDeclaration(statements, node); return singleOrMany(statements); } @@ -107532,76 +95919,25 @@ ${lanes.join("\n")} if (moduleName) { args.push(moduleName); } - return factory2.createCallExpression( - factory2.createIdentifier("require"), - /*typeArguments*/ - void 0, - args - ); + return factory2.createCallExpression(factory2.createIdentifier("require"), /*typeArguments*/ + void 0, args); } function visitTopLevelImportEqualsDeclaration(node) { Debug.assert(isExternalModuleImportEqualsDeclaration(node), "import= for internal module references should be handled in an earlier transformer."); let statements; if (moduleKind !== 2 /* AMD */) { if (hasSyntacticModifier(node, 32 /* Export */)) { - statements = append( - statements, - setOriginalNode( - setTextRange( - factory2.createExpressionStatement( - createExportExpression( - node.name, - createRequireCall2(node) - ) - ), - node - ), - node - ) - ); + statements = append(statements, setOriginalNode(setTextRange(factory2.createExpressionStatement(createExportExpression(node.name, createRequireCall2(node))), node), node)); } else { - statements = append( - statements, - setOriginalNode( - setTextRange( - factory2.createVariableStatement( - /*modifiers*/ - void 0, - factory2.createVariableDeclarationList( - [ - factory2.createVariableDeclaration( - factory2.cloneNode(node.name), - /*exclamationToken*/ - void 0, - /*type*/ - void 0, - createRequireCall2(node) - ) - ], - /*flags*/ - languageVersion >= 2 /* ES2015 */ ? 2 /* Const */ : 0 /* None */ - ) - ), - node - ), - node - ) - ); + statements = append(statements, setOriginalNode(setTextRange(factory2.createVariableStatement( /*modifiers*/ + void 0, factory2.createVariableDeclarationList([factory2.createVariableDeclaration(factory2.cloneNode(node.name), /*exclamationToken*/ + void 0, /*type*/ + void 0, createRequireCall2(node))], /*flags*/ + languageVersion >= 2 /* ES2015 */ ? 2 /* Const */ : 0 /* None */)), node), node)); } } else { if (hasSyntacticModifier(node, 32 /* Export */)) { - statements = append( - statements, - setOriginalNode( - setTextRange( - factory2.createExpressionStatement( - createExportExpression(factory2.getExportName(node), factory2.getLocalName(node)) - ), - node - ), - node - ) - ); + statements = append(statements, setOriginalNode(setTextRange(factory2.createExpressionStatement(createExportExpression(factory2.getExportName(node), factory2.getLocalName(node))), node), node)); } } statements = appendExportsOfImportEqualsDeclaration(statements, node); @@ -107615,147 +95951,51 @@ ${lanes.join("\n")} if (node.exportClause && isNamedExports(node.exportClause)) { const statements = []; if (moduleKind !== 2 /* AMD */) { - statements.push( - setOriginalNode( - setTextRange( - factory2.createVariableStatement( - /*modifiers*/ - void 0, - factory2.createVariableDeclarationList([ - factory2.createVariableDeclaration( - generatedName, - /*exclamationToken*/ - void 0, - /*type*/ - void 0, - createRequireCall2(node) - ) - ]) - ), - /*location*/ - node - ), - /* original */ - node - ) - ); + statements.push(setOriginalNode(setTextRange(factory2.createVariableStatement( /*modifiers*/ + void 0, factory2.createVariableDeclarationList([factory2.createVariableDeclaration(generatedName, /*exclamationToken*/ + void 0, /*type*/ + void 0, createRequireCall2(node))])), /*location*/ + node), /* original */ + node)); } for (const specifier of node.exportClause.elements) { if (languageVersion === 0 /* ES3 */) { - statements.push( - setOriginalNode( - setTextRange( - factory2.createExpressionStatement( - emitHelpers().createCreateBindingHelper(generatedName, factory2.createStringLiteralFromNode(specifier.propertyName || specifier.name), specifier.propertyName ? factory2.createStringLiteralFromNode(specifier.name) : void 0) - ), - specifier - ), - specifier - ) - ); + statements.push(setOriginalNode(setTextRange(factory2.createExpressionStatement(emitHelpers().createCreateBindingHelper(generatedName, factory2.createStringLiteralFromNode(specifier.propertyName || specifier.name), specifier.propertyName ? factory2.createStringLiteralFromNode(specifier.name) : void 0)), specifier), specifier)); } else { const exportNeedsImportDefault = !!getESModuleInterop(compilerOptions) && !(getInternalEmitFlags(node) & 2 /* NeverApplyImportHelper */) && idText(specifier.propertyName || specifier.name) === "default"; - const exportedValue = factory2.createPropertyAccessExpression( - exportNeedsImportDefault ? emitHelpers().createImportDefaultHelper(generatedName) : generatedName, - specifier.propertyName || specifier.name - ); - statements.push( - setOriginalNode( - setTextRange( - factory2.createExpressionStatement( - createExportExpression( - factory2.getExportName(specifier), - exportedValue, - /*location*/ - void 0, - /*liveBinding*/ - true - ) - ), - specifier - ), - specifier - ) - ); + const exportedValue = factory2.createPropertyAccessExpression(exportNeedsImportDefault ? emitHelpers().createImportDefaultHelper(generatedName) : generatedName, specifier.propertyName || specifier.name); + statements.push(setOriginalNode(setTextRange(factory2.createExpressionStatement(createExportExpression(factory2.getExportName(specifier), exportedValue, /*location*/ + void 0, /*liveBinding*/ + true)), specifier), specifier)); } } return singleOrMany(statements); } else if (node.exportClause) { const statements = []; - statements.push( - setOriginalNode( - setTextRange( - factory2.createExpressionStatement( - createExportExpression( - factory2.cloneNode(node.exportClause.name), - getHelperExpressionForExport( - node, - moduleKind !== 2 /* AMD */ ? createRequireCall2(node) : isExportNamespaceAsDefaultDeclaration(node) ? generatedName : factory2.createIdentifier(idText(node.exportClause.name)) - ) - ) - ), - node - ), - node - ) - ); + statements.push(setOriginalNode(setTextRange(factory2.createExpressionStatement(createExportExpression(factory2.cloneNode(node.exportClause.name), getHelperExpressionForExport(node, moduleKind !== 2 /* AMD */ ? createRequireCall2(node) : isExportNamespaceAsDefaultDeclaration(node) ? generatedName : factory2.createIdentifier(idText(node.exportClause.name))))), node), node)); return singleOrMany(statements); } else { - return setOriginalNode( - setTextRange( - factory2.createExpressionStatement( - emitHelpers().createExportStarHelper(moduleKind !== 2 /* AMD */ ? createRequireCall2(node) : generatedName) - ), - node - ), - node - ); + return setOriginalNode(setTextRange(factory2.createExpressionStatement(emitHelpers().createExportStarHelper(moduleKind !== 2 /* AMD */ ? createRequireCall2(node) : generatedName)), node), node); } } function visitTopLevelExportAssignment(node) { if (node.isExportEquals) { return void 0; } - return createExportStatement( - factory2.createIdentifier("default"), - visitNode(node.expression, visitor, isExpression), - /*location*/ - node, - /*allowComments*/ - true - ); + return createExportStatement(factory2.createIdentifier("default"), visitNode(node.expression, visitor, isExpression), /*location*/ + node, /*allowComments*/ + true); } function visitFunctionDeclaration(node) { let statements; if (hasSyntacticModifier(node, 32 /* Export */)) { - statements = append( - statements, - setOriginalNode( - setTextRange( - factory2.createFunctionDeclaration( - visitNodes2(node.modifiers, modifierVisitor, isModifier), - node.asteriskToken, - factory2.getDeclarationName( - node, - /*allowComments*/ - true, - /*allowSourceMaps*/ - true - ), - /*typeParameters*/ - void 0, - visitNodes2(node.parameters, visitor, isParameter), - /*type*/ - void 0, - visitEachChild(node.body, visitor, context) - ), - /*location*/ - node - ), - /*original*/ - node - ) - ); + statements = append(statements, setOriginalNode(setTextRange(factory2.createFunctionDeclaration(visitNodes2(node.modifiers, modifierVisitor, isModifier), node.asteriskToken, factory2.getDeclarationName(node, /*allowComments*/ + true, /*allowSourceMaps*/ + true), /*typeParameters*/ + void 0, visitNodes2(node.parameters, visitor, isParameter), /*type*/ + void 0, visitEachChild(node.body, visitor, context)), /*location*/ + node), /*original*/ + node)); } else { statements = append(statements, visitEachChild(node, visitor, context)); } @@ -107765,29 +96005,10 @@ ${lanes.join("\n")} function visitClassDeclaration(node) { let statements; if (hasSyntacticModifier(node, 32 /* Export */)) { - statements = append( - statements, - setOriginalNode( - setTextRange( - factory2.createClassDeclaration( - visitNodes2(node.modifiers, modifierVisitor, isModifierLike), - factory2.getDeclarationName( - node, - /*allowComments*/ - true, - /*allowSourceMaps*/ - true - ), - /*typeParameters*/ - void 0, - visitNodes2(node.heritageClauses, visitor, isHeritageClause), - visitNodes2(node.members, visitor, isClassElement) - ), - node - ), - node - ) - ); + statements = append(statements, setOriginalNode(setTextRange(factory2.createClassDeclaration(visitNodes2(node.modifiers, modifierVisitor, isModifierLike), factory2.getDeclarationName(node, /*allowComments*/ + true, /*allowSourceMaps*/ + true), /*typeParameters*/ + void 0, visitNodes2(node.heritageClauses, visitor, isHeritageClause), visitNodes2(node.members, visitor, isClassElement)), node), node)); } else { statements = append(statements, visitEachChild(node, visitor, context)); } @@ -107807,41 +96028,18 @@ ${lanes.join("\n")} modifiers = visitNodes2(node.modifiers, modifierVisitor, isModifier); } if (variable.initializer) { - const updatedVariable = factory2.updateVariableDeclaration( - variable, - variable.name, - /*exclamationToken*/ - void 0, - /*type*/ - void 0, - createExportExpression( - variable.name, - visitNode(variable.initializer, visitor, isExpression) - ) - ); + const updatedVariable = factory2.updateVariableDeclaration(variable, variable.name, /*exclamationToken*/ + void 0, /*type*/ + void 0, createExportExpression(variable.name, visitNode(variable.initializer, visitor, isExpression))); variables = append(variables, updatedVariable); } else { variables = append(variables, variable); } } else if (variable.initializer) { if (!isBindingPattern(variable.name) && (isArrowFunction(variable.initializer) || isFunctionExpression(variable.initializer) || isClassExpression(variable.initializer))) { - const expression = factory2.createAssignment( - setTextRange( - factory2.createPropertyAccessExpression( - factory2.createIdentifier("exports"), - variable.name - ), - /*location*/ - variable.name - ), - factory2.createIdentifier(getTextOfIdentifierOrLiteral(variable.name)) - ); - const updatedVariable = factory2.createVariableDeclaration( - variable.name, - variable.exclamationToken, - variable.type, - visitNode(variable.initializer, visitor, isExpression) - ); + const expression = factory2.createAssignment(setTextRange(factory2.createPropertyAccessExpression(factory2.createIdentifier("exports"), variable.name), /*location*/ + variable.name), factory2.createIdentifier(getTextOfIdentifierOrLiteral(variable.name))); + const updatedVariable = factory2.createVariableDeclaration(variable.name, variable.exclamationToken, variable.type, visitNode(variable.initializer, visitor, isExpression)); variables = append(variables, updatedVariable); expressions = append(expressions, expression); removeCommentsOnExpressions = true; @@ -107872,12 +96070,8 @@ ${lanes.join("\n")} let expression = isExportName(name) ? value : factory2.createAssignment(name, value); for (const exportName of exportedNames) { setEmitFlags(expression, 8 /* NoSubstitution */); - expression = createExportExpression( - exportName, - expression, - /*location*/ - location - ); + expression = createExportExpression(exportName, expression, /*location*/ + location); } return expression; } @@ -107885,27 +96079,11 @@ ${lanes.join("\n")} } function transformInitializedVariable(node) { if (isBindingPattern(node.name)) { - return flattenDestructuringAssignment( - visitNode(node, visitor, isInitializedVariable), - visitor, - context, - 0 /* All */, - /*needsValue*/ - false, - createAllExportExpressions - ); + return flattenDestructuringAssignment(visitNode(node, visitor, isInitializedVariable), visitor, context, 0 /* All */, /*needsValue*/ + false, createAllExportExpressions); } else { - return factory2.createAssignment( - setTextRange( - factory2.createPropertyAccessExpression( - factory2.createIdentifier("exports"), - node.name - ), - /*location*/ - node.name - ), - node.initializer ? visitNode(node.initializer, visitor, isExpression) : factory2.createVoidZero() - ); + return factory2.createAssignment(setTextRange(factory2.createPropertyAccessExpression(factory2.createIdentifier("exports"), node.name), /*location*/ + node.name), node.initializer ? visitNode(node.initializer, visitor, isExpression) : factory2.createVoidZero()); } } function appendExportsOfImportDeclaration(statements, decl) { @@ -107928,13 +96106,8 @@ ${lanes.join("\n")} break; case 275 /* NamedImports */: for (const importBinding of namedBindings.elements) { - statements = appendExportsOfDeclaration( - statements, - seen, - importBinding, - /*liveBinding*/ - true - ); + statements = appendExportsOfDeclaration(statements, seen, importBinding, /*liveBinding*/ + true); } break; } @@ -107948,12 +96121,8 @@ ${lanes.join("\n")} return appendExportsOfDeclaration(statements, new IdentifierNameMap(), decl); } function appendExportsOfVariableStatement(statements, node) { - return appendExportsOfVariableDeclarationList( - statements, - node.declarationList, - /*isForInOrOfInitializer*/ - false - ); + return appendExportsOfVariableDeclarationList(statements, node.declarationList, /*isForInOrOfInitializer*/ + false); } function appendExportsOfVariableDeclarationList(statements, node, isForInOrOfInitializer) { if (currentModuleInfo.exportEquals) { @@ -107986,14 +96155,8 @@ ${lanes.join("\n")} const seen = new IdentifierNameMap(); if (hasSyntacticModifier(decl, 32 /* Export */)) { const exportName = hasSyntacticModifier(decl, 2048 /* Default */) ? factory2.createIdentifier("default") : factory2.getDeclarationName(decl); - statements = appendExportStatement( - statements, - seen, - exportName, - factory2.getLocalName(decl), - /*location*/ - decl - ); + statements = appendExportStatement(statements, seen, exportName, factory2.getLocalName(decl), /*location*/ + decl); } if (decl.name) { statements = appendExportsOfDeclaration(statements, seen, decl); @@ -108005,17 +96168,9 @@ ${lanes.join("\n")} const exportSpecifiers = currentModuleInfo.exportSpecifiers.get(name); if (exportSpecifiers) { for (const exportSpecifier of exportSpecifiers) { - statements = appendExportStatement( - statements, - seen, - exportSpecifier.name, - name, - /*location*/ - exportSpecifier.name, - /*allowComments*/ - void 0, - liveBinding - ); + statements = appendExportStatement(statements, seen, exportSpecifier.name, name, /*location*/ + exportSpecifier.name, /*allowComments*/ + void 0, liveBinding); } } return statements; @@ -108030,88 +96185,33 @@ ${lanes.join("\n")} function createUnderscoreUnderscoreESModule() { let statement; if (languageVersion === 0 /* ES3 */) { - statement = factory2.createExpressionStatement( - createExportExpression( - factory2.createIdentifier("__esModule"), - factory2.createTrue() - ) - ); + statement = factory2.createExpressionStatement(createExportExpression(factory2.createIdentifier("__esModule"), factory2.createTrue())); } else { - statement = factory2.createExpressionStatement( - factory2.createCallExpression( - factory2.createPropertyAccessExpression(factory2.createIdentifier("Object"), "defineProperty"), - /*typeArguments*/ - void 0, - [ - factory2.createIdentifier("exports"), - factory2.createStringLiteral("__esModule"), - factory2.createObjectLiteralExpression([ - factory2.createPropertyAssignment("value", factory2.createTrue()) - ]) - ] - ) - ); + statement = factory2.createExpressionStatement(factory2.createCallExpression(factory2.createPropertyAccessExpression(factory2.createIdentifier("Object"), "defineProperty"), /*typeArguments*/ + void 0, [factory2.createIdentifier("exports"), factory2.createStringLiteral("__esModule"), factory2.createObjectLiteralExpression([factory2.createPropertyAssignment("value", factory2.createTrue())])])); } setEmitFlags(statement, 2097152 /* CustomPrologue */); return statement; } function createExportStatement(name, value, location, allowComments, liveBinding) { - const statement = setTextRange(factory2.createExpressionStatement(createExportExpression( - name, - value, - /*location*/ - void 0, - liveBinding - )), location); + const statement = setTextRange(factory2.createExpressionStatement(createExportExpression(name, value, /*location*/ + void 0, liveBinding)), location); startOnNewLine(statement); if (!allowComments) { setEmitFlags(statement, 3072 /* NoComments */); } + return statement; } function createExportExpression(name, value, location, liveBinding) { - return setTextRange( - liveBinding && languageVersion !== 0 /* ES3 */ ? factory2.createCallExpression( - factory2.createPropertyAccessExpression( - factory2.createIdentifier("Object"), - "defineProperty" - ), - /*typeArguments*/ - void 0, - [ - factory2.createIdentifier("exports"), - factory2.createStringLiteralFromNode(name), - factory2.createObjectLiteralExpression([ - factory2.createPropertyAssignment("enumerable", factory2.createTrue()), - factory2.createPropertyAssignment( - "get", - factory2.createFunctionExpression( - /*modifiers*/ - void 0, - /*asteriskToken*/ - void 0, - /*name*/ - void 0, - /*typeParameters*/ - void 0, - /*parameters*/ - [], - /*type*/ - void 0, - factory2.createBlock([factory2.createReturnStatement(value)]) - ) - ) - ]) - ] - ) : factory2.createAssignment( - factory2.createPropertyAccessExpression( - factory2.createIdentifier("exports"), - factory2.cloneNode(name) - ), - value - ), - location - ); + return setTextRange(liveBinding && languageVersion !== 0 /* ES3 */ ? factory2.createCallExpression(factory2.createPropertyAccessExpression(factory2.createIdentifier("Object"), "defineProperty"), /*typeArguments*/ + void 0, [factory2.createIdentifier("exports"), factory2.createStringLiteralFromNode(name), factory2.createObjectLiteralExpression([factory2.createPropertyAssignment("enumerable", factory2.createTrue()), factory2.createPropertyAssignment("get", factory2.createFunctionExpression( /*modifiers*/ + void 0, /*asteriskToken*/ + void 0, /*name*/ + void 0, /*typeParameters*/ + void 0, /*parameters*/ + [], /*type*/ + void 0, factory2.createBlock([factory2.createReturnStatement(value)])))])]) : factory2.createAssignment(factory2.createPropertyAccessExpression(factory2.createIdentifier("exports"), factory2.cloneNode(name)), value), location); } function modifierVisitor(node) { switch (node.kind) { @@ -108174,18 +96274,11 @@ ${lanes.join("\n")} const expression = substituteExpressionIdentifier(node.expression); noSubstitution[getNodeId(expression)] = true; if (!isIdentifier(expression) && !(getEmitFlags(node.expression) & 8192 /* HelperName */)) { - return addInternalEmitFlags( - factory2.updateCallExpression( - node, - expression, - /*typeArguments*/ - void 0, - node.arguments - ), - 16 /* IndirectCall */ - ); + return addInternalEmitFlags(factory2.updateCallExpression(node, expression, /*typeArguments*/ + void 0, node.arguments), 16 /* IndirectCall */); } } + return node; } function substituteTaggedTemplateExpression(node) { @@ -108193,18 +96286,11 @@ ${lanes.join("\n")} const tag = substituteExpressionIdentifier(node.tag); noSubstitution[getNodeId(tag)] = true; if (!isIdentifier(tag) && !(getEmitFlags(node.tag) & 8192 /* HelperName */)) { - return addInternalEmitFlags( - factory2.updateTaggedTemplateExpression( - node, - tag, - /*typeArguments*/ - void 0, - node.template - ), - 16 /* IndirectCall */ - ); + return addInternalEmitFlags(factory2.updateTaggedTemplateExpression(node, tag, /*typeArguments*/ + void 0, node.template), 16 /* IndirectCall */); } } + return node; } function substituteExpressionIdentifier(node) { @@ -108218,36 +96304,18 @@ ${lanes.join("\n")} } else if (!(isGeneratedIdentifier(node) && !(node.emitNode.autoGenerate.flags & 64 /* AllowNameSubstitution */)) && !isLocalName(node)) { const exportContainer = resolver.getReferencedExportContainer(node, isExportName(node)); if (exportContainer && exportContainer.kind === 312 /* SourceFile */) { - return setTextRange( - factory2.createPropertyAccessExpression( - factory2.createIdentifier("exports"), - factory2.cloneNode(node) - ), - /*location*/ - node - ); + return setTextRange(factory2.createPropertyAccessExpression(factory2.createIdentifier("exports"), factory2.cloneNode(node)), /*location*/ + node); } const importDeclaration = resolver.getReferencedImportDeclaration(node); if (importDeclaration) { if (isImportClause(importDeclaration)) { - return setTextRange( - factory2.createPropertyAccessExpression( - factory2.getGeneratedNameForNode(importDeclaration.parent), - factory2.createIdentifier("default") - ), - /*location*/ - node - ); + return setTextRange(factory2.createPropertyAccessExpression(factory2.getGeneratedNameForNode(importDeclaration.parent), factory2.createIdentifier("default")), /*location*/ + node); } else if (isImportSpecifier(importDeclaration)) { const name = importDeclaration.propertyName || importDeclaration.name; - return setTextRange( - factory2.createPropertyAccessExpression( - factory2.getGeneratedNameForNode(((_b = (_a = importDeclaration.parent) == null ? void 0 : _a.parent) == null ? void 0 : _b.parent) || importDeclaration), - factory2.cloneNode(name) - ), - /*location*/ - node - ); + return setTextRange(factory2.createPropertyAccessExpression(factory2.getGeneratedNameForNode(((_b = (_a = importDeclaration.parent) == null ? void 0 : _a.parent) == null ? void 0 : _b.parent) || importDeclaration), factory2.cloneNode(name)), /*location*/ + node); } } } @@ -108260,12 +96328,8 @@ ${lanes.join("\n")} let expression = node; for (const exportName of exportedNames) { noSubstitution[getNodeId(expression)] = true; - expression = createExportExpression( - exportName, - expression, - /*location*/ - node - ); + expression = createExportExpression(exportName, expression, /*location*/ + node); } return expression; } @@ -108278,7 +96342,7 @@ ${lanes.join("\n")} if (importDeclaration) { return currentModuleInfo == null ? void 0 : currentModuleInfo.exportedBindings[getOriginalNodeId(importDeclaration)]; } - const bindingsSet = /* @__PURE__ */ new Set(); + const bindingsSet = /* @__PURE__ */new Set(); const declarations = resolver.getReferencedValueDeclarations(name); if (declarations) { for (const declaration of declarations) { @@ -108309,6 +96373,7 @@ ${lanes.join("\n")} var init_module = __esm({ "src/compiler/transformers/module/module.ts"() { "use strict"; + init_ts2(); dynamicImportUMDHelper = { name: "typescript:dynamicimport-sync-require", @@ -108364,58 +96429,23 @@ ${lanes.join("\n")} contextObject = contextObjectMap[id] = factory2.createUniqueName("context"); const dependencyGroups = collectDependencyGroups(moduleInfo.externalImports); const moduleBodyBlock = createSystemModuleBody(node, dependencyGroups); - const moduleBodyFunction = factory2.createFunctionExpression( - /*modifiers*/ - void 0, - /*asteriskToken*/ - void 0, - /*name*/ - void 0, - /*typeParameters*/ - void 0, - [ - factory2.createParameterDeclaration( - /*modifiers*/ - void 0, - /*dotDotDotToken*/ - void 0, - exportFunction - ), - factory2.createParameterDeclaration( - /*modifiers*/ - void 0, - /*dotDotDotToken*/ - void 0, - contextObject - ) - ], - /*type*/ - void 0, - moduleBodyBlock - ); + const moduleBodyFunction = factory2.createFunctionExpression( /*modifiers*/ + void 0, /*asteriskToken*/ + void 0, /*name*/ + void 0, /*typeParameters*/ + void 0, [factory2.createParameterDeclaration( /*modifiers*/ + void 0, /*dotDotDotToken*/ + void 0, exportFunction), factory2.createParameterDeclaration( /*modifiers*/ + void 0, /*dotDotDotToken*/ + void 0, contextObject)], /*type*/ + void 0, moduleBodyBlock); const moduleName = tryGetModuleNameFromFile(factory2, node, host, compilerOptions); - const dependencies = factory2.createArrayLiteralExpression(map(dependencyGroups, (dependencyGroup) => dependencyGroup.name)); - const updated = setEmitFlags( - factory2.updateSourceFile( - node, - setTextRange( - factory2.createNodeArray([ - factory2.createExpressionStatement( - factory2.createCallExpression( - factory2.createPropertyAccessExpression(factory2.createIdentifier("System"), "register"), - /*typeArguments*/ - void 0, - moduleName ? [moduleName, dependencies, moduleBodyFunction] : [dependencies, moduleBodyFunction] - ) - ) - ]), - node.statements - ) - ), - 2048 /* NoTrailingComments */ - ); + const dependencies = factory2.createArrayLiteralExpression(map(dependencyGroups, dependencyGroup => dependencyGroup.name)); + const updated = setEmitFlags(factory2.updateSourceFile(node, setTextRange(factory2.createNodeArray([factory2.createExpressionStatement(factory2.createCallExpression(factory2.createPropertyAccessExpression(factory2.createIdentifier("System"), "register"), /*typeArguments*/ + void 0, moduleName ? [moduleName, dependencies, moduleBodyFunction] : [dependencies, moduleBodyFunction]))]), node.statements)), 2048 /* NoTrailingComments */); + if (!outFile(compilerOptions)) { - moveEmitHelpers(updated, moduleBodyBlock, (helper) => !helper.scoped); + moveEmitHelpers(updated, moduleBodyBlock, helper => !helper.scoped); } if (noSubstitution) { noSubstitutionMap[id] = noSubstitution; @@ -108430,7 +96460,7 @@ ${lanes.join("\n")} return updated; } function collectDependencyGroups(externalImports) { - const groupIndices = /* @__PURE__ */ new Map(); + const groupIndices = /* @__PURE__ */new Map(); const dependencyGroups = []; for (const externalImport of externalImports) { const externalModuleName = getExternalModuleNameLiteral(factory2, externalImport, currentSourceFile, host, resolver, compilerOptions); @@ -108455,65 +96485,27 @@ ${lanes.join("\n")} startLexicalEnvironment(); const ensureUseStrict = getStrictOptionValue(compilerOptions, "alwaysStrict") || !compilerOptions.noImplicitUseStrict && isExternalModule(currentSourceFile); const statementOffset = factory2.copyPrologue(node.statements, statements, ensureUseStrict, topLevelVisitor); - statements.push( - factory2.createVariableStatement( - /*modifiers*/ - void 0, - factory2.createVariableDeclarationList([ - factory2.createVariableDeclaration( - "__moduleName", - /*exclamationToken*/ - void 0, - /*type*/ - void 0, - factory2.createLogicalAnd( - contextObject, - factory2.createPropertyAccessExpression(contextObject, "id") - ) - ) - ]) - ) - ); + statements.push(factory2.createVariableStatement( /*modifiers*/ + void 0, factory2.createVariableDeclarationList([factory2.createVariableDeclaration("__moduleName", /*exclamationToken*/ + void 0, /*type*/ + void 0, factory2.createLogicalAnd(contextObject, factory2.createPropertyAccessExpression(contextObject, "id")))]))); visitNode(moduleInfo.externalHelpersImportDeclaration, topLevelVisitor, isStatement); const executeStatements = visitNodes2(node.statements, topLevelVisitor, isStatement, statementOffset); addRange(statements, hoistedStatements); insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment()); const exportStarFunction = addExportStarIfNeeded(statements); const modifiers = node.transformFlags & 2097152 /* ContainsAwait */ ? factory2.createModifiersFromModifierFlags(1024 /* Async */) : void 0; - const moduleObject = factory2.createObjectLiteralExpression( - [ - factory2.createPropertyAssignment("setters", createSettersArray(exportStarFunction, dependencyGroups)), - factory2.createPropertyAssignment( - "execute", - factory2.createFunctionExpression( - modifiers, - /*asteriskToken*/ - void 0, - /*name*/ - void 0, - /*typeParameters*/ - void 0, - /*parameters*/ - [], - /*type*/ - void 0, - factory2.createBlock( - executeStatements, - /*multiLine*/ - true - ) - ) - ) - ], - /*multiLine*/ - true - ); + const moduleObject = factory2.createObjectLiteralExpression([factory2.createPropertyAssignment("setters", createSettersArray(exportStarFunction, dependencyGroups)), factory2.createPropertyAssignment("execute", factory2.createFunctionExpression(modifiers, /*asteriskToken*/ + void 0, /*name*/ + void 0, /*typeParameters*/ + void 0, /*parameters*/ + [], /*type*/ + void 0, factory2.createBlock(executeStatements, /*multiLine*/ + true)))], /*multiLine*/ + true); statements.push(factory2.createReturnStatement(moduleObject)); - return factory2.createBlock( - statements, - /*multiLine*/ - true - ); + return factory2.createBlock(statements, /*multiLine*/ + true); } function addExportStarIfNeeded(statements) { if (!moduleInfo.hasExportStarsToExportValues) { @@ -108528,10 +96520,8 @@ ${lanes.join("\n")} } } if (!hasExportDeclarationWithExportClause) { - const exportStarFunction2 = createExportStarFunction( - /*localNames*/ - void 0 - ); + const exportStarFunction2 = createExportStarFunction( /*localNames*/ + void 0); statements.push(exportStarFunction2); return exportStarFunction2.name; } @@ -108542,35 +96532,15 @@ ${lanes.join("\n")} if (exportedLocalName.escapedText === "default") { continue; } - exportedNames.push( - factory2.createPropertyAssignment( - factory2.createStringLiteralFromNode(exportedLocalName), - factory2.createTrue() - ) - ); + exportedNames.push(factory2.createPropertyAssignment(factory2.createStringLiteralFromNode(exportedLocalName), factory2.createTrue())); } } const exportedNamesStorageRef = factory2.createUniqueName("exportedNames"); - statements.push( - factory2.createVariableStatement( - /*modifiers*/ - void 0, - factory2.createVariableDeclarationList([ - factory2.createVariableDeclaration( - exportedNamesStorageRef, - /*exclamationToken*/ - void 0, - /*type*/ - void 0, - factory2.createObjectLiteralExpression( - exportedNames, - /*multiLine*/ - true - ) - ) - ]) - ) - ); + statements.push(factory2.createVariableStatement( /*modifiers*/ + void 0, factory2.createVariableDeclarationList([factory2.createVariableDeclaration(exportedNamesStorageRef, /*exclamationToken*/ + void 0, /*type*/ + void 0, factory2.createObjectLiteralExpression(exportedNames, /*multiLine*/ + true))]))); const exportStarFunction = createExportStarFunction(exportedNamesStorageRef); statements.push(exportStarFunction); return exportStarFunction.name; @@ -108582,89 +96552,26 @@ ${lanes.join("\n")} const exports = factory2.createIdentifier("exports"); let condition = factory2.createStrictInequality(n, factory2.createStringLiteral("default")); if (localNames) { - condition = factory2.createLogicalAnd( - condition, - factory2.createLogicalNot( - factory2.createCallExpression( - factory2.createPropertyAccessExpression(localNames, "hasOwnProperty"), - /*typeArguments*/ - void 0, - [n] - ) - ) - ); + condition = factory2.createLogicalAnd(condition, factory2.createLogicalNot(factory2.createCallExpression(factory2.createPropertyAccessExpression(localNames, "hasOwnProperty"), /*typeArguments*/ + void 0, [n]))); } - return factory2.createFunctionDeclaration( - /*modifiers*/ - void 0, - /*asteriskToken*/ - void 0, - exportStarFunction, - /*typeParameters*/ - void 0, - [factory2.createParameterDeclaration( - /*modifiers*/ - void 0, - /*dotDotDotToken*/ - void 0, - m - )], - /*type*/ - void 0, - factory2.createBlock( - [ - factory2.createVariableStatement( - /*modifiers*/ - void 0, - factory2.createVariableDeclarationList([ - factory2.createVariableDeclaration( - exports, - /*exclamationToken*/ - void 0, - /*type*/ - void 0, - factory2.createObjectLiteralExpression([]) - ) - ]) - ), - factory2.createForInStatement( - factory2.createVariableDeclarationList([ - factory2.createVariableDeclaration(n) - ]), - m, - factory2.createBlock([ - setEmitFlags( - factory2.createIfStatement( - condition, - factory2.createExpressionStatement( - factory2.createAssignment( - factory2.createElementAccessExpression(exports, n), - factory2.createElementAccessExpression(m, n) - ) - ) - ), - 1 /* SingleLine */ - ) - ]) - ), - factory2.createExpressionStatement( - factory2.createCallExpression( - exportFunction, - /*typeArguments*/ - void 0, - [exports] - ) - ) - ], - /*multiLine*/ - true - ) - ); + return factory2.createFunctionDeclaration( /*modifiers*/ + void 0, /*asteriskToken*/ + void 0, exportStarFunction, /*typeParameters*/ + void 0, [factory2.createParameterDeclaration( /*modifiers*/ + void 0, /*dotDotDotToken*/ + void 0, m)], /*type*/ + void 0, factory2.createBlock([factory2.createVariableStatement( /*modifiers*/ + void 0, factory2.createVariableDeclarationList([factory2.createVariableDeclaration(exports, /*exclamationToken*/ + void 0, /*type*/ + void 0, factory2.createObjectLiteralExpression([]))])), factory2.createForInStatement(factory2.createVariableDeclarationList([factory2.createVariableDeclaration(n)]), m, factory2.createBlock([setEmitFlags(factory2.createIfStatement(condition, factory2.createExpressionStatement(factory2.createAssignment(factory2.createElementAccessExpression(exports, n), factory2.createElementAccessExpression(m, n)))), 1 /* SingleLine */)])), factory2.createExpressionStatement(factory2.createCallExpression(exportFunction, /*typeArguments*/ + void 0, [exports]))], /*multiLine*/ + true)); } function createSettersArray(exportStarFunction, dependencyGroups) { const setters = []; for (const group2 of dependencyGroups) { - const localName = forEach(group2.externalImports, (i) => getLocalNameForExternalImport(factory2, i, currentSourceFile)); + const localName = forEach(group2.externalImports, i => getLocalNameForExternalImport(factory2, i, currentSourceFile)); const parameterName = localName ? factory2.getGeneratedNameForNode(localName) : factory2.createUniqueName(""); const statements = []; for (const entry of group2.externalImports) { @@ -108676,25 +96583,10 @@ ${lanes.join("\n")} } case 271 /* ImportEqualsDeclaration */: Debug.assert(importVariableName !== void 0); - statements.push( - factory2.createExpressionStatement( - factory2.createAssignment(importVariableName, parameterName) - ) - ); + statements.push(factory2.createExpressionStatement(factory2.createAssignment(importVariableName, parameterName))); if (hasSyntacticModifier(entry, 32 /* Export */)) { - statements.push( - factory2.createExpressionStatement( - factory2.createCallExpression( - exportFunction, - /*typeArguments*/ - void 0, - [ - factory2.createStringLiteral(idText(importVariableName)), - parameterName - ] - ) - ) - ); + statements.push(factory2.createExpressionStatement(factory2.createCallExpression(exportFunction, /*typeArguments*/ + void 0, [factory2.createStringLiteral(idText(importVariableName)), parameterName]))); } break; case 278 /* ExportDeclaration */: @@ -108703,92 +96595,34 @@ ${lanes.join("\n")} if (isNamedExports(entry.exportClause)) { const properties = []; for (const e of entry.exportClause.elements) { - properties.push( - factory2.createPropertyAssignment( - factory2.createStringLiteral(idText(e.name)), - factory2.createElementAccessExpression( - parameterName, - factory2.createStringLiteral(idText(e.propertyName || e.name)) - ) - ) - ); + properties.push(factory2.createPropertyAssignment(factory2.createStringLiteral(idText(e.name)), factory2.createElementAccessExpression(parameterName, factory2.createStringLiteral(idText(e.propertyName || e.name))))); } - statements.push( - factory2.createExpressionStatement( - factory2.createCallExpression( - exportFunction, - /*typeArguments*/ - void 0, - [factory2.createObjectLiteralExpression( - properties, - /*multiLine*/ - true - )] - ) - ) - ); + statements.push(factory2.createExpressionStatement(factory2.createCallExpression(exportFunction, /*typeArguments*/ + void 0, [factory2.createObjectLiteralExpression(properties, /*multiLine*/ + true)]))); } else { - statements.push( - factory2.createExpressionStatement( - factory2.createCallExpression( - exportFunction, - /*typeArguments*/ - void 0, - [ - factory2.createStringLiteral(idText(entry.exportClause.name)), - parameterName - ] - ) - ) - ); + statements.push(factory2.createExpressionStatement(factory2.createCallExpression(exportFunction, /*typeArguments*/ + void 0, [factory2.createStringLiteral(idText(entry.exportClause.name)), parameterName]))); } } else { - statements.push( - factory2.createExpressionStatement( - factory2.createCallExpression( - exportStarFunction, - /*typeArguments*/ - void 0, - [parameterName] - ) - ) - ); + statements.push(factory2.createExpressionStatement(factory2.createCallExpression(exportStarFunction, /*typeArguments*/ + void 0, [parameterName]))); } break; } } - setters.push( - factory2.createFunctionExpression( - /*modifiers*/ - void 0, - /*asteriskToken*/ - void 0, - /*name*/ - void 0, - /*typeParameters*/ - void 0, - [factory2.createParameterDeclaration( - /*modifiers*/ - void 0, - /*dotDotDotToken*/ - void 0, - parameterName - )], - /*type*/ - void 0, - factory2.createBlock( - statements, - /*multiLine*/ - true - ) - ) - ); + setters.push(factory2.createFunctionExpression( /*modifiers*/ + void 0, /*asteriskToken*/ + void 0, /*name*/ + void 0, /*typeParameters*/ + void 0, [factory2.createParameterDeclaration( /*modifiers*/ + void 0, /*dotDotDotToken*/ + void 0, parameterName)], /*type*/ + void 0, factory2.createBlock(statements, /*multiLine*/ + true))); } - return factory2.createArrayLiteralExpression( - setters, - /*multiLine*/ - true - ); + return factory2.createArrayLiteralExpression(setters, /*multiLine*/ + true); } function topLevelVisitor(node) { switch (node.kind) { @@ -108826,36 +96660,16 @@ ${lanes.join("\n")} return void 0; } const expression = visitNode(node.expression, visitor, isExpression); - return createExportStatement( - factory2.createIdentifier("default"), - expression, - /*allowComments*/ - true - ); + return createExportStatement(factory2.createIdentifier("default"), expression, /*allowComments*/ + true); } function visitFunctionDeclaration(node) { if (hasSyntacticModifier(node, 32 /* Export */)) { - hoistedStatements = append( - hoistedStatements, - factory2.updateFunctionDeclaration( - node, - visitNodes2(node.modifiers, modifierVisitor, isModifierLike), - node.asteriskToken, - factory2.getDeclarationName( - node, - /*allowComments*/ - true, - /*allowSourceMaps*/ - true - ), - /*typeParameters*/ - void 0, - visitNodes2(node.parameters, visitor, isParameter), - /*type*/ - void 0, - visitNode(node.body, visitor, isBlock) - ) - ); + hoistedStatements = append(hoistedStatements, factory2.updateFunctionDeclaration(node, visitNodes2(node.modifiers, modifierVisitor, isModifierLike), node.asteriskToken, factory2.getDeclarationName(node, /*allowComments*/ + true, /*allowSourceMaps*/ + true), /*typeParameters*/ + void 0, visitNodes2(node.parameters, visitor, isParameter), /*type*/ + void 0, visitNode(node.body, visitor, isBlock))); } else { hoistedStatements = append(hoistedStatements, visitEachChild(node, visitor, context)); } @@ -108866,28 +96680,8 @@ ${lanes.join("\n")} let statements; const name = factory2.getLocalName(node); hoistVariableDeclaration(name); - statements = append( - statements, - setTextRange( - factory2.createExpressionStatement( - factory2.createAssignment( - name, - setTextRange( - factory2.createClassExpression( - visitNodes2(node.modifiers, modifierVisitor, isModifierLike), - node.name, - /*typeParameters*/ - void 0, - visitNodes2(node.heritageClauses, visitor, isHeritageClause), - visitNodes2(node.members, visitor, isClassElement) - ), - node - ) - ) - ), - node - ) - ); + statements = append(statements, setTextRange(factory2.createExpressionStatement(factory2.createAssignment(name, setTextRange(factory2.createClassExpression(visitNodes2(node.modifiers, modifierVisitor, isModifierLike), node.name, /*typeParameters*/ + void 0, visitNodes2(node.heritageClauses, visitor, isHeritageClause), visitNodes2(node.members, visitor, isClassElement)), node))), node)); statements = appendExportsOfHoistedDeclaration(statements, node); return singleOrMany(statements); } @@ -108900,24 +96694,12 @@ ${lanes.join("\n")} const modifiers = visitNodes2(node.modifiers, modifierVisitor, isModifierLike); const declarations = []; for (const variable of node.declarationList.declarations) { - declarations.push(factory2.updateVariableDeclaration( - variable, - factory2.getGeneratedNameForNode(variable.name), - /*exclamationToken*/ - void 0, - /*type*/ - void 0, - transformInitializedVariable( - variable, - /*isExportedDeclaration*/ - false - ) - )); + declarations.push(factory2.updateVariableDeclaration(variable, factory2.getGeneratedNameForNode(variable.name), /*exclamationToken*/ + void 0, /*type*/ + void 0, transformInitializedVariable(variable, /*isExportedDeclaration*/ + false))); } - const declarationList = factory2.updateVariableDeclarationList( - node.declarationList, - declarations - ); + const declarationList = factory2.updateVariableDeclarationList(node.declarationList, declarations); statements = append(statements, factory2.updateVariableStatement(node, modifiers, declarationList)); } else { let expressions; @@ -108933,12 +96715,8 @@ ${lanes.join("\n")} statements = append(statements, setTextRange(factory2.createExpressionStatement(factory2.inlineExpressions(expressions)), node)); } } - statements = appendExportsOfVariableStatement( - statements, - node, - /*exportSelf*/ - false - ); + statements = appendExportsOfVariableStatement(statements, node, /*exportSelf*/ + false); return singleOrMany(statements); } function hoistBindingElement(node) { @@ -108957,33 +96735,16 @@ ${lanes.join("\n")} } function transformInitializedVariable(node, isExportedDeclaration) { const createAssignment = isExportedDeclaration ? createExportedVariableAssignment : createNonExportedVariableAssignment; - return isBindingPattern(node.name) ? flattenDestructuringAssignment( - node, - visitor, - context, - 0 /* All */, - /*needsValue*/ - false, - createAssignment - ) : node.initializer ? createAssignment(node.name, visitNode(node.initializer, visitor, isExpression)) : node.name; + return isBindingPattern(node.name) ? flattenDestructuringAssignment(node, visitor, context, 0 /* All */, /*needsValue*/ + false, createAssignment) : node.initializer ? createAssignment(node.name, visitNode(node.initializer, visitor, isExpression)) : node.name; } function createExportedVariableAssignment(name, value, location) { - return createVariableAssignment( - name, - value, - location, - /*isExportedDeclaration*/ - true - ); + return createVariableAssignment(name, value, location, /*isExportedDeclaration*/ + true); } function createNonExportedVariableAssignment(name, value, location) { - return createVariableAssignment( - name, - value, - location, - /*isExportedDeclaration*/ - false - ); + return createVariableAssignment(name, value, location, /*isExportedDeclaration*/ + false); } function createVariableAssignment(name, value, location, isExportedDeclaration) { hoistVariableDeclaration(factory2.cloneNode(name)); @@ -109092,17 +96853,14 @@ ${lanes.join("\n")} if (!allowComments) { setEmitFlags(statement, 3072 /* NoComments */); } + return statement; } function createExportExpression(name, value) { const exportName = isIdentifier(name) ? factory2.createStringLiteralFromNode(name) : name; setEmitFlags(value, getEmitFlags(value) | 3072 /* NoComments */); - return setCommentRange(factory2.createCallExpression( - exportFunction, - /*typeArguments*/ - void 0, - [exportName, value] - ), value); + return setCommentRange(factory2.createCallExpression(exportFunction, /*typeArguments*/ + void 0, [exportName, value]), value); } function topLevelNestedVisitor(node) { switch (node.kind) { @@ -109113,11 +96871,8 @@ ${lanes.join("\n")} case 263 /* ClassDeclaration */: return visitClassDeclaration(node); case 248 /* ForStatement */: - return visitForStatement( - node, - /*isTopLevel*/ - true - ); + return visitForStatement(node, /*isTopLevel*/ + true); case 249 /* ForInStatement */: return visitForInStatement(node); case 250 /* ForOfStatement */: @@ -109153,38 +96908,21 @@ ${lanes.join("\n")} function visitForStatement(node, isTopLevel) { const savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; enclosingBlockScopedContainer = node; - node = factory2.updateForStatement( - node, - visitNode(node.initializer, isTopLevel ? visitForInitializer : discardedValueVisitor, isForInitializer), - visitNode(node.condition, visitor, isExpression), - visitNode(node.incrementor, discardedValueVisitor, isExpression), - visitIterationBody(node.statement, isTopLevel ? topLevelNestedVisitor : visitor, context) - ); + node = factory2.updateForStatement(node, visitNode(node.initializer, isTopLevel ? visitForInitializer : discardedValueVisitor, isForInitializer), visitNode(node.condition, visitor, isExpression), visitNode(node.incrementor, discardedValueVisitor, isExpression), visitIterationBody(node.statement, isTopLevel ? topLevelNestedVisitor : visitor, context)); enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; return node; } function visitForInStatement(node) { const savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; enclosingBlockScopedContainer = node; - node = factory2.updateForInStatement( - node, - visitForInitializer(node.initializer), - visitNode(node.expression, visitor, isExpression), - visitIterationBody(node.statement, topLevelNestedVisitor, context) - ); + node = factory2.updateForInStatement(node, visitForInitializer(node.initializer), visitNode(node.expression, visitor, isExpression), visitIterationBody(node.statement, topLevelNestedVisitor, context)); enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; return node; } function visitForOfStatement(node) { const savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; enclosingBlockScopedContainer = node; - node = factory2.updateForOfStatement( - node, - node.awaitModifier, - visitForInitializer(node.initializer), - visitNode(node.expression, visitor, isExpression), - visitIterationBody(node.statement, topLevelNestedVisitor, context) - ); + node = factory2.updateForOfStatement(node, node.awaitModifier, visitForInitializer(node.initializer), visitNode(node.expression, visitor, isExpression), visitIterationBody(node.statement, topLevelNestedVisitor, context)); enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; return node; } @@ -109195,11 +96933,8 @@ ${lanes.join("\n")} if (shouldHoistForInitializer(node)) { let expressions; for (const variable of node.declarations) { - expressions = append(expressions, transformInitializedVariable( - variable, - /*isExportedDeclaration*/ - false - )); + expressions = append(expressions, transformInitializedVariable(variable, /*isExportedDeclaration*/ + false)); if (!variable.initializer) { hoistBindingElement(variable); } @@ -109210,64 +96945,32 @@ ${lanes.join("\n")} } } function visitDoStatement(node) { - return factory2.updateDoStatement( - node, - visitIterationBody(node.statement, topLevelNestedVisitor, context), - visitNode(node.expression, visitor, isExpression) - ); + return factory2.updateDoStatement(node, visitIterationBody(node.statement, topLevelNestedVisitor, context), visitNode(node.expression, visitor, isExpression)); } function visitWhileStatement(node) { - return factory2.updateWhileStatement( - node, - visitNode(node.expression, visitor, isExpression), - visitIterationBody(node.statement, topLevelNestedVisitor, context) - ); + return factory2.updateWhileStatement(node, visitNode(node.expression, visitor, isExpression), visitIterationBody(node.statement, topLevelNestedVisitor, context)); } function visitLabeledStatement(node) { - return factory2.updateLabeledStatement( - node, - node.label, - Debug.checkDefined(visitNode(node.statement, topLevelNestedVisitor, isStatement, factory2.liftToBlock)) - ); + return factory2.updateLabeledStatement(node, node.label, Debug.checkDefined(visitNode(node.statement, topLevelNestedVisitor, isStatement, factory2.liftToBlock))); } function visitWithStatement(node) { - return factory2.updateWithStatement( - node, - visitNode(node.expression, visitor, isExpression), - Debug.checkDefined(visitNode(node.statement, topLevelNestedVisitor, isStatement, factory2.liftToBlock)) - ); + return factory2.updateWithStatement(node, visitNode(node.expression, visitor, isExpression), Debug.checkDefined(visitNode(node.statement, topLevelNestedVisitor, isStatement, factory2.liftToBlock))); } function visitIfStatement(node) { - return factory2.updateIfStatement( - node, - visitNode(node.expression, visitor, isExpression), - Debug.checkDefined(visitNode(node.thenStatement, topLevelNestedVisitor, isStatement, factory2.liftToBlock)), - visitNode(node.elseStatement, topLevelNestedVisitor, isStatement, factory2.liftToBlock) - ); + return factory2.updateIfStatement(node, visitNode(node.expression, visitor, isExpression), Debug.checkDefined(visitNode(node.thenStatement, topLevelNestedVisitor, isStatement, factory2.liftToBlock)), visitNode(node.elseStatement, topLevelNestedVisitor, isStatement, factory2.liftToBlock)); } function visitSwitchStatement(node) { - return factory2.updateSwitchStatement( - node, - visitNode(node.expression, visitor, isExpression), - Debug.checkDefined(visitNode(node.caseBlock, topLevelNestedVisitor, isCaseBlock)) - ); + return factory2.updateSwitchStatement(node, visitNode(node.expression, visitor, isExpression), Debug.checkDefined(visitNode(node.caseBlock, topLevelNestedVisitor, isCaseBlock))); } function visitCaseBlock(node) { const savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; enclosingBlockScopedContainer = node; - node = factory2.updateCaseBlock( - node, - visitNodes2(node.clauses, topLevelNestedVisitor, isCaseOrDefaultClause) - ); + node = factory2.updateCaseBlock(node, visitNodes2(node.clauses, topLevelNestedVisitor, isCaseOrDefaultClause)); enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; return node; } function visitCaseClause(node) { - return factory2.updateCaseClause( - node, - visitNode(node.expression, visitor, isExpression), - visitNodes2(node.statements, topLevelNestedVisitor, isStatement) - ); + return factory2.updateCaseClause(node, visitNode(node.expression, visitor, isExpression), visitNodes2(node.statements, topLevelNestedVisitor, isStatement)); } function visitDefaultClause(node) { return visitEachChild(node, topLevelNestedVisitor, context); @@ -109278,11 +96981,7 @@ ${lanes.join("\n")} function visitCatchClause(node) { const savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; enclosingBlockScopedContainer = node; - node = factory2.updateCatchClause( - node, - node.variableDeclaration, - Debug.checkDefined(visitNode(node.block, topLevelNestedVisitor, isBlock)) - ); + node = factory2.updateCatchClause(node, node.variableDeclaration, Debug.checkDefined(visitNode(node.block, topLevelNestedVisitor, isBlock))); enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; return node; } @@ -109299,11 +96998,8 @@ ${lanes.join("\n")} } switch (node.kind) { case 248 /* ForStatement */: - return visitForStatement( - node, - /*isTopLevel*/ - false - ); + return visitForStatement(node, /*isTopLevel*/ + false); case 244 /* ExpressionStatement */: return visitExpressionStatement(node); case 217 /* ParenthesizedExpression */: @@ -109327,18 +97023,12 @@ ${lanes.join("\n")} return visitEachChild(node, visitor, context); } function visitor(node) { - return visitorWorker( - node, - /*valueIsDiscarded*/ - false - ); + return visitorWorker(node, /*valueIsDiscarded*/ + false); } function discardedValueVisitor(node) { - return visitorWorker( - node, - /*valueIsDiscarded*/ - true - ); + return visitorWorker(node, /*valueIsDiscarded*/ + true); } function visitExpressionStatement(node) { return factory2.updateExpressionStatement(node, visitNode(node.expression, discardedValueVisitor, isExpression)); @@ -109353,34 +97043,18 @@ ${lanes.join("\n")} const externalModuleName = getExternalModuleNameLiteral(factory2, node, currentSourceFile, host, resolver, compilerOptions); const firstArgument = visitNode(firstOrUndefined(node.arguments), visitor, isExpression); const argument = externalModuleName && (!firstArgument || !isStringLiteral(firstArgument) || firstArgument.text !== externalModuleName.text) ? externalModuleName : firstArgument; - return factory2.createCallExpression( - factory2.createPropertyAccessExpression( - contextObject, - factory2.createIdentifier("import") - ), - /*typeArguments*/ - void 0, - argument ? [argument] : [] - ); + return factory2.createCallExpression(factory2.createPropertyAccessExpression(contextObject, factory2.createIdentifier("import")), /*typeArguments*/ + void 0, argument ? [argument] : []); } function visitDestructuringAssignment(node, valueIsDiscarded) { if (hasExportedReferenceInDestructuringTarget(node.left)) { - return flattenDestructuringAssignment( - node, - visitor, - context, - 0 /* All */, - !valueIsDiscarded - ); + return flattenDestructuringAssignment(node, visitor, context, 0 /* All */, !valueIsDiscarded); } return visitEachChild(node, visitor, context); } function hasExportedReferenceInDestructuringTarget(node) { - if (isAssignmentExpression( - node, - /*excludeCompoundAssignment*/ - true - )) { + if (isAssignmentExpression(node, /*excludeCompoundAssignment*/ + true)) { return hasExportedReferenceInDestructuringTarget(node.left); } else if (isSpreadElement(node)) { return hasExportedReferenceInDestructuringTarget(node.expression); @@ -109484,29 +97158,11 @@ ${lanes.join("\n")} const importDeclaration = resolver.getReferencedImportDeclaration(name); if (importDeclaration) { if (isImportClause(importDeclaration)) { - return setTextRange( - factory2.createPropertyAssignment( - factory2.cloneNode(name), - factory2.createPropertyAccessExpression( - factory2.getGeneratedNameForNode(importDeclaration.parent), - factory2.createIdentifier("default") - ) - ), - /*location*/ - node - ); + return setTextRange(factory2.createPropertyAssignment(factory2.cloneNode(name), factory2.createPropertyAccessExpression(factory2.getGeneratedNameForNode(importDeclaration.parent), factory2.createIdentifier("default"))), /*location*/ + node); } else if (isImportSpecifier(importDeclaration)) { - return setTextRange( - factory2.createPropertyAssignment( - factory2.cloneNode(name), - factory2.createPropertyAccessExpression( - factory2.getGeneratedNameForNode(((_b = (_a = importDeclaration.parent) == null ? void 0 : _a.parent) == null ? void 0 : _b.parent) || importDeclaration), - factory2.cloneNode(importDeclaration.propertyName || importDeclaration.name) - ) - ), - /*location*/ - node - ); + return setTextRange(factory2.createPropertyAssignment(factory2.cloneNode(name), factory2.createPropertyAccessExpression(factory2.getGeneratedNameForNode(((_b = (_a = importDeclaration.parent) == null ? void 0 : _a.parent) == null ? void 0 : _b.parent) || importDeclaration), factory2.cloneNode(importDeclaration.propertyName || importDeclaration.name))), /*location*/ + node); } } } @@ -109536,23 +97192,11 @@ ${lanes.join("\n")} const importDeclaration = resolver.getReferencedImportDeclaration(node); if (importDeclaration) { if (isImportClause(importDeclaration)) { - return setTextRange( - factory2.createPropertyAccessExpression( - factory2.getGeneratedNameForNode(importDeclaration.parent), - factory2.createIdentifier("default") - ), - /*location*/ - node - ); + return setTextRange(factory2.createPropertyAccessExpression(factory2.getGeneratedNameForNode(importDeclaration.parent), factory2.createIdentifier("default")), /*location*/ + node); } else if (isImportSpecifier(importDeclaration)) { - return setTextRange( - factory2.createPropertyAccessExpression( - factory2.getGeneratedNameForNode(((_b = (_a = importDeclaration.parent) == null ? void 0 : _a.parent) == null ? void 0 : _b.parent) || importDeclaration), - factory2.cloneNode(importDeclaration.propertyName || importDeclaration.name) - ), - /*location*/ - node - ); + return setTextRange(factory2.createPropertyAccessExpression(factory2.getGeneratedNameForNode(((_b = (_a = importDeclaration.parent) == null ? void 0 : _a.parent) == null ? void 0 : _b.parent) || importDeclaration), factory2.cloneNode(importDeclaration.propertyName || importDeclaration.name)), /*location*/ + node); } } } @@ -109581,11 +97225,8 @@ ${lanes.join("\n")} let exportedNames; const valueDeclaration = getReferencedDeclaration(name); if (valueDeclaration) { - const exportContainer = resolver.getReferencedExportContainer( - name, - /*prefixLocals*/ - false - ); + const exportContainer = resolver.getReferencedExportContainer(name, /*prefixLocals*/ + false); if (exportContainer && exportContainer.kind === 312 /* SourceFile */) { exportedNames = append(exportedNames, factory2.getDeclarationName(valueDeclaration)); } @@ -109605,24 +97246,20 @@ ${lanes.join("\n")} 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; } @@ -109633,6 +97270,7 @@ ${lanes.join("\n")} var init_system = __esm({ "src/compiler/transformers/module/system.ts"() { "use strict"; + init_ts2(); } }); @@ -109667,18 +97305,12 @@ ${lanes.join("\n")} let result = updateExternalModule(node); currentSourceFile = void 0; if (importRequireStatements) { - result = factory2.updateSourceFile( - result, - setTextRange(factory2.createNodeArray(insertStatementsAfterCustomPrologue(result.statements.slice(), importRequireStatements)), result.statements) - ); + result = factory2.updateSourceFile(result, setTextRange(factory2.createNodeArray(insertStatementsAfterCustomPrologue(result.statements.slice(), importRequireStatements)), result.statements)); } if (!isExternalModule(node) || some(result.statements, isExternalModuleIndicator)) { return result; } - return factory2.updateSourceFile( - result, - setTextRange(factory2.createNodeArray([...result.statements, createEmptyExports(factory2)]), result.statements) - ); + return factory2.updateSourceFile(result, setTextRange(factory2.createNodeArray([...result.statements, createEmptyExports(factory2)]), result.statements)); } return node; } @@ -109689,10 +97321,7 @@ ${lanes.join("\n")} const statementOffset = factory2.copyPrologue(node.statements, statements); append(statements, externalHelpersImportDeclaration); addRange(statements, visitNodes2(node.statements, visitor, isStatement, statementOffset)); - return factory2.updateSourceFile( - node, - setTextRange(factory2.createNodeArray(statements), node.statements) - ); + return factory2.updateSourceFile(node, setTextRange(factory2.createNodeArray(statements), node.statements)); } else { return visitEachChild(node, visitor, context); } @@ -109717,114 +97346,44 @@ ${lanes.join("\n")} } if (!importRequireStatements) { const createRequireName = factory2.createUniqueName("_createRequire", 16 /* Optimistic */ | 32 /* FileLevel */); - const importStatement = factory2.createImportDeclaration( - /*modifiers*/ - void 0, - factory2.createImportClause( - /*isTypeOnly*/ - false, - /*name*/ - void 0, - factory2.createNamedImports([ - factory2.createImportSpecifier( - /*isTypeOnly*/ - false, - factory2.createIdentifier("createRequire"), - createRequireName - ) - ]) - ), - factory2.createStringLiteral("module"), - /*attributes*/ - void 0 - ); + const importStatement = factory2.createImportDeclaration( /*modifiers*/ + void 0, factory2.createImportClause( /*isTypeOnly*/ + false, /*name*/ + void 0, factory2.createNamedImports([factory2.createImportSpecifier( /*isTypeOnly*/ + false, factory2.createIdentifier("createRequire"), createRequireName)])), factory2.createStringLiteral("module"), /*attributes*/ + void 0); const requireHelperName = factory2.createUniqueName("__require", 16 /* Optimistic */ | 32 /* FileLevel */); - const requireStatement = factory2.createVariableStatement( - /*modifiers*/ - void 0, - factory2.createVariableDeclarationList( - [ - factory2.createVariableDeclaration( - requireHelperName, - /*exclamationToken*/ - void 0, - /*type*/ - void 0, - factory2.createCallExpression( - factory2.cloneNode(createRequireName), - /*typeArguments*/ - void 0, - [ - factory2.createPropertyAccessExpression(factory2.createMetaProperty(102 /* ImportKeyword */, factory2.createIdentifier("meta")), factory2.createIdentifier("url")) - ] - ) - ) - ], - /*flags*/ - languageVersion >= 2 /* ES2015 */ ? 2 /* Const */ : 0 /* None */ - ) - ); + const requireStatement = factory2.createVariableStatement( /*modifiers*/ + void 0, factory2.createVariableDeclarationList([factory2.createVariableDeclaration(requireHelperName, /*exclamationToken*/ + void 0, /*type*/ + void 0, factory2.createCallExpression(factory2.cloneNode(createRequireName), /*typeArguments*/ + void 0, [factory2.createPropertyAccessExpression(factory2.createMetaProperty(102 /* ImportKeyword */, factory2.createIdentifier("meta")), factory2.createIdentifier("url"))]))], /*flags*/ + languageVersion >= 2 /* ES2015 */ ? 2 /* Const */ : 0 /* None */)); + importRequireStatements = [importStatement, requireStatement]; } const name = importRequireStatements[1].declarationList.declarations[0].name; Debug.assertNode(name, isIdentifier); - return factory2.createCallExpression( - factory2.cloneNode(name), - /*typeArguments*/ - void 0, - args - ); + return factory2.createCallExpression(factory2.cloneNode(name), /*typeArguments*/ + void 0, args); } function visitImportEqualsDeclaration(node) { Debug.assert(isExternalModuleImportEqualsDeclaration(node), "import= for internal module references should be handled in an earlier transformer."); let statements; - statements = append( - statements, - setOriginalNode( - setTextRange( - factory2.createVariableStatement( - /*modifiers*/ - void 0, - factory2.createVariableDeclarationList( - [ - factory2.createVariableDeclaration( - factory2.cloneNode(node.name), - /*exclamationToken*/ - void 0, - /*type*/ - void 0, - createRequireCall2(node) - ) - ], - /*flags*/ - languageVersion >= 2 /* ES2015 */ ? 2 /* Const */ : 0 /* None */ - ) - ), - node - ), - node - ) - ); + statements = append(statements, setOriginalNode(setTextRange(factory2.createVariableStatement( /*modifiers*/ + void 0, factory2.createVariableDeclarationList([factory2.createVariableDeclaration(factory2.cloneNode(node.name), /*exclamationToken*/ + void 0, /*type*/ + void 0, createRequireCall2(node))], /*flags*/ + languageVersion >= 2 /* ES2015 */ ? 2 /* Const */ : 0 /* None */)), node), node)); statements = appendExportsOfImportEqualsDeclaration(statements, node); return singleOrMany(statements); } function appendExportsOfImportEqualsDeclaration(statements, node) { if (hasSyntacticModifier(node, 32 /* Export */)) { - statements = append( - statements, - factory2.createExportDeclaration( - /*modifiers*/ - void 0, - node.isTypeOnly, - factory2.createNamedExports([factory2.createExportSpecifier( - /*isTypeOnly*/ - false, - /*propertyName*/ - void 0, - idText(node.name) - )]) - ) - ); + statements = append(statements, factory2.createExportDeclaration( /*modifiers*/ + void 0, node.isTypeOnly, factory2.createNamedExports([factory2.createExportSpecifier( /*isTypeOnly*/ + false, /*propertyName*/ + void 0, idText(node.name))]))); } return statements; } @@ -109840,41 +97399,22 @@ ${lanes.join("\n")} } const oldIdentifier = node.exportClause.name; const synthName = factory2.getGeneratedNameForNode(oldIdentifier); - const importDecl = factory2.createImportDeclaration( - /*modifiers*/ - void 0, - factory2.createImportClause( - /*isTypeOnly*/ - false, - /*name*/ - void 0, - factory2.createNamespaceImport( - synthName - ) - ), - node.moduleSpecifier, - node.attributes - ); + const importDecl = factory2.createImportDeclaration( /*modifiers*/ + void 0, factory2.createImportClause( /*isTypeOnly*/ + false, /*name*/ + void 0, factory2.createNamespaceImport(synthName)), node.moduleSpecifier, node.attributes); setOriginalNode(importDecl, node.exportClause); - const exportDecl = isExportNamespaceAsDefaultDeclaration(node) ? factory2.createExportDefault(synthName) : factory2.createExportDeclaration( - /*modifiers*/ - void 0, - /*isTypeOnly*/ - false, - factory2.createNamedExports([factory2.createExportSpecifier( - /*isTypeOnly*/ - false, - synthName, - oldIdentifier - )]) - ); + const exportDecl = isExportNamespaceAsDefaultDeclaration(node) ? factory2.createExportDefault(synthName) : factory2.createExportDeclaration( /*modifiers*/ + void 0, /*isTypeOnly*/ + false, factory2.createNamedExports([factory2.createExportSpecifier( /*isTypeOnly*/ + false, synthName, oldIdentifier)])); setOriginalNode(exportDecl, node); return [importDecl, exportDecl]; } function onEmitNode(hint, node, emitCallback) { if (isSourceFile(node)) { if ((isExternalModule(node) || getIsolatedModules(compilerOptions)) && compilerOptions.importHelpers) { - helperNameSubstitutions = /* @__PURE__ */ new Map(); + helperNameSubstitutions = /* @__PURE__ */new Map(); } previousOnEmitNode(hint, node, emitCallback); helperNameSubstitutions = void 0; @@ -109895,12 +97435,14 @@ ${lanes.join("\n")} if (!substitution) { helperNameSubstitutions.set(name, substitution = factory2.createUniqueName(name, 16 /* Optimistic */ | 32 /* FileLevel */)); } + return substitution; } } var init_esnextAnd2015 = __esm({ "src/compiler/transformers/module/esnextAnd2015.ts"() { "use strict"; + init_ts2(); } }); @@ -109972,6 +97514,7 @@ ${lanes.join("\n")} var init_node = __esm({ "src/compiler/transformers/module/node.ts"() { "use strict"; + init_ts2(); } }); @@ -110238,6 +97781,7 @@ ${lanes.join("\n")} var init_diagnostics = __esm({ "src/compiler/transformers/declarations/diagnostics.ts"() { "use strict"; + init_ts2(); } }); @@ -110245,16 +97789,8 @@ ${lanes.join("\n")} // src/compiler/transformers/declarations.ts function getDeclarationDiagnostics(host, resolver, file) { const compilerOptions = host.getCompilerOptions(); - const result = transformNodes( - resolver, - host, - factory, - compilerOptions, - file ? [file] : filter(host.getSourceFiles(), isSourceFileNotJson), - [transformDeclarations], - /*allowDtsFiles*/ - false - ); + const result = transformNodes(resolver, host, factory, compilerOptions, file ? [file] : filter(host.getSourceFiles(), isSourceFileNotJson), [transformDeclarations], /*allowDtsFiles*/ + false); return result.diagnostics; } function hasInternalAnnotation(range, currentSourceFile) { @@ -110268,30 +97804,18 @@ ${lanes.join("\n")} const previousSibling = paramIdx > 0 ? parseTreeNode.parent.parameters[paramIdx - 1] : void 0; const text = currentSourceFile.text; const commentRanges = previousSibling ? concatenate( - // to handle - // ... parameters, /** @internal */ - // public param: string - getTrailingCommentRanges(text, skipTrivia( - text, - previousSibling.end + 1, - /*stopAfterLineBreak*/ - false, - /*stopAtComments*/ - true - )), - getLeadingCommentRanges(text, node.pos) - ) : getTrailingCommentRanges(text, skipTrivia( - text, - node.pos, - /*stopAfterLineBreak*/ - false, - /*stopAtComments*/ - true - )); + // to handle + // ... parameters, /** @internal */ + // public param: string + getTrailingCommentRanges(text, skipTrivia(text, previousSibling.end + 1, /*stopAfterLineBreak*/ + false, /*stopAtComments*/ + true)), getLeadingCommentRanges(text, node.pos)) : getTrailingCommentRanges(text, skipTrivia(text, node.pos, /*stopAfterLineBreak*/ + false, /*stopAtComments*/ + true)); return commentRanges && commentRanges.length && hasInternalAnnotation(last(commentRanges), currentSourceFile); } const leadingCommentRanges = parseTreeNode && getLeadingCommentRangesOfNode(parseTreeNode, currentSourceFile); - return !!forEach(leadingCommentRanges, (range) => { + return !!forEach(leadingCommentRanges, range => { return hasInternalAnnotation(range, currentSourceFile); }); } @@ -110309,7 +97833,9 @@ ${lanes.join("\n")} let lateStatementReplacementMap; let suppressNewDiagnosticContexts; let exportedModulesFromDeclarationEmit; - const { factory: factory2 } = context; + const { + factory: factory2 + } = context; const host = context.getEmitHost(); const symbolTracker = { trackSymbol, @@ -110333,13 +97859,16 @@ ${lanes.join("\n")} let emittedImports; const resolver = context.getEmitResolver(); const options = context.getCompilerOptions(); - const { noResolve, stripInternal } = options; + const { + noResolve, + stripInternal + } = options; return transformRoot; function recordTypeReferenceDirectivesIfNecessary(typeReferenceDirectives) { if (!typeReferenceDirectives) { return; } - necessaryTypeReferences = necessaryTypeReferences || /* @__PURE__ */ new Set(); + necessaryTypeReferences = necessaryTypeReferences || /* @__PURE__ */new Set(); for (const ref of typeReferenceDirectives) { necessaryTypeReferences.add(ref); } @@ -110393,23 +97922,15 @@ ${lanes.join("\n")} } } function trackSymbol(symbol, enclosingDeclaration2, meaning) { - if (symbol.flags & 262144 /* TypeParameter */) - return false; - const issuedDiagnostic = handleSymbolAccessibilityError(resolver.isSymbolAccessible( - symbol, - enclosingDeclaration2, - meaning, - /*shouldComputeAliasToMarkVisible*/ - true - )); + if (symbol.flags & 262144 /* TypeParameter */) return false; + const issuedDiagnostic = handleSymbolAccessibilityError(resolver.isSymbolAccessible(symbol, enclosingDeclaration2, meaning, /*shouldComputeAliasToMarkVisible*/ + true)); recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForSymbol(symbol, meaning)); return issuedDiagnostic; } function reportPrivateInBaseOfClassExpression(propertyName) { if (errorNameNode || errorFallbackNode) { - context.addDiagnostic( - createDiagnosticForNode(errorNameNode || errorFallbackNode, Diagnostics.Property_0_of_exported_class_expression_may_not_be_private_or_protected, propertyName) - ); + context.addDiagnostic(createDiagnosticForNode(errorNameNode || errorFallbackNode, Diagnostics.Property_0_of_exported_class_expression_may_not_be_private_or_protected, propertyName)); } } function errorDeclarationNameWithFallback() { @@ -110442,14 +97963,11 @@ ${lanes.join("\n")} } function reportNonlocalAugmentation(containingFile, parentSymbol, symbol) { var _a; - const primaryDeclaration = (_a = parentSymbol.declarations) == null ? void 0 : _a.find((d) => getSourceFileOfNode(d) === containingFile); - const augmentingDeclarations = filter(symbol.declarations, (d) => getSourceFileOfNode(d) !== containingFile); + const primaryDeclaration = (_a = parentSymbol.declarations) == null ? void 0 : _a.find(d => getSourceFileOfNode(d) === containingFile); + const augmentingDeclarations = filter(symbol.declarations, d => getSourceFileOfNode(d) !== containingFile); if (primaryDeclaration && augmentingDeclarations) { for (const augmentations of augmentingDeclarations) { - context.addDiagnostic(addRelatedInfo( - createDiagnosticForNode(augmentations, Diagnostics.Declaration_augments_declaration_in_another_file_This_cannot_be_serialized), - createDiagnosticForNode(primaryDeclaration, Diagnostics.This_is_the_declaration_being_augmented_Consider_moving_the_augmenting_declaration_into_the_same_file) - )); + context.addDiagnostic(addRelatedInfo(createDiagnosticForNode(augmentations, Diagnostics.Declaration_augments_declaration_in_another_file_This_cannot_be_serialized), createDiagnosticForNode(primaryDeclaration, Diagnostics.This_is_the_declaration_being_augmented_Consider_moving_the_augmenting_declaration_into_the_same_file))); } } } @@ -110460,7 +97978,7 @@ ${lanes.join("\n")} } function transformDeclarationsForJS(sourceFile, bundled) { const oldDiag = getSymbolAccessibilityDiagnostic; - getSymbolAccessibilityDiagnostic = (s) => s.errorNode && canProduceDiagnostics(s.errorNode) ? createGetSymbolAccessibilityDiagnosticForNode(s.errorNode)(s) : { + getSymbolAccessibilityDiagnostic = s => s.errorNode && canProduceDiagnostics(s.errorNode) ? createGetSymbolAccessibilityDiagnosticForNode(s.errorNode)(s) : { diagnosticMessage: s.errorModuleName ? Diagnostics.Declaration_emit_for_this_file_requires_using_private_name_0_from_module_1_An_explicit_type_annotation_may_unblock_declaration_emit : Diagnostics.Declaration_emit_for_this_file_requires_using_private_name_0_An_explicit_type_annotation_may_unblock_declaration_emit, errorNode: s.errorNode || sourceFile }; @@ -110474,91 +97992,60 @@ ${lanes.join("\n")} } if (node.kind === 313 /* Bundle */) { isBundledEmit = true; - refs = /* @__PURE__ */ new Map(); - libs2 = /* @__PURE__ */ new Map(); + refs = /* @__PURE__ */new Map(); + libs2 = /* @__PURE__ */new Map(); let hasNoDefaultLib = false; - const bundle = factory2.createBundle( - map(node.sourceFiles, (sourceFile) => { - if (sourceFile.isDeclarationFile) - return void 0; - hasNoDefaultLib = hasNoDefaultLib || sourceFile.hasNoDefaultLib; - currentSourceFile = sourceFile; - enclosingDeclaration = sourceFile; - lateMarkedStatements = void 0; - suppressNewDiagnosticContexts = false; - lateStatementReplacementMap = /* @__PURE__ */ new Map(); - getSymbolAccessibilityDiagnostic = throwDiagnostic; - needsScopeFixMarker = false; - resultHasScopeMarker = false; + const bundle = factory2.createBundle(map(node.sourceFiles, sourceFile => { + if (sourceFile.isDeclarationFile) return void 0; + hasNoDefaultLib = hasNoDefaultLib || sourceFile.hasNoDefaultLib; + currentSourceFile = sourceFile; + enclosingDeclaration = sourceFile; + lateMarkedStatements = void 0; + suppressNewDiagnosticContexts = false; + lateStatementReplacementMap = /* @__PURE__ */new Map(); + getSymbolAccessibilityDiagnostic = throwDiagnostic; + needsScopeFixMarker = false; + resultHasScopeMarker = false; + collectReferences(sourceFile, refs); + collectLibs(sourceFile, libs2); + if (isExternalOrCommonJsModule(sourceFile) || isJsonSourceFile(sourceFile)) { + resultHasExternalModuleIndicator = false; + needsDeclare = false; + const statements = isSourceFileJS(sourceFile) ? factory2.createNodeArray(transformDeclarationsForJS(sourceFile, /*bundled*/ + true)) : visitNodes2(sourceFile.statements, visitDeclarationStatements, isStatement); + const newFile = factory2.updateSourceFile(sourceFile, [factory2.createModuleDeclaration([factory2.createModifier(138 /* DeclareKeyword */)], factory2.createStringLiteral(getResolvedExternalModuleName(context.getEmitHost(), sourceFile)), factory2.createModuleBlock(setTextRange(factory2.createNodeArray(transformAndReplaceLatePaintedStatements(statements)), sourceFile.statements)))], /*isDeclarationFile*/ + true, /*referencedFiles*/ + [], /*typeReferences*/ + [], /*hasNoDefaultLib*/ + false, /*libReferences*/ + []); + return newFile; + } + needsDeclare = true; + const updated2 = isSourceFileJS(sourceFile) ? factory2.createNodeArray(transformDeclarationsForJS(sourceFile)) : visitNodes2(sourceFile.statements, visitDeclarationStatements, isStatement); + return factory2.updateSourceFile(sourceFile, transformAndReplaceLatePaintedStatements(updated2), /*isDeclarationFile*/ + true, /*referencedFiles*/ + [], /*typeReferences*/ + [], /*hasNoDefaultLib*/ + false, /*libReferences*/ + []); + }), mapDefined(node.prepends, prepend => { + if (prepend.kind === 315 /* InputFiles */) { + const sourceFile = createUnparsedSourceFile(prepend, "dts", stripInternal); + hasNoDefaultLib = hasNoDefaultLib || !!sourceFile.hasNoDefaultLib; collectReferences(sourceFile, refs); + recordTypeReferenceDirectivesIfNecessary(map(sourceFile.typeReferenceDirectives, ref => [ref.fileName, ref.resolutionMode])); collectLibs(sourceFile, libs2); - if (isExternalOrCommonJsModule(sourceFile) || isJsonSourceFile(sourceFile)) { - resultHasExternalModuleIndicator = false; - needsDeclare = false; - const statements = isSourceFileJS(sourceFile) ? factory2.createNodeArray(transformDeclarationsForJS( - sourceFile, - /*bundled*/ - true - )) : visitNodes2(sourceFile.statements, visitDeclarationStatements, isStatement); - const newFile = factory2.updateSourceFile( - sourceFile, - [factory2.createModuleDeclaration( - [factory2.createModifier(138 /* DeclareKeyword */)], - factory2.createStringLiteral(getResolvedExternalModuleName(context.getEmitHost(), sourceFile)), - factory2.createModuleBlock(setTextRange(factory2.createNodeArray(transformAndReplaceLatePaintedStatements(statements)), sourceFile.statements)) - )], - /*isDeclarationFile*/ - true, - /*referencedFiles*/ - [], - /*typeReferences*/ - [], - /*hasNoDefaultLib*/ - false, - /*libReferences*/ - [] - ); - return newFile; - } - needsDeclare = true; - const updated2 = isSourceFileJS(sourceFile) ? factory2.createNodeArray(transformDeclarationsForJS(sourceFile)) : visitNodes2(sourceFile.statements, visitDeclarationStatements, isStatement); - return factory2.updateSourceFile( - sourceFile, - transformAndReplaceLatePaintedStatements(updated2), - /*isDeclarationFile*/ - true, - /*referencedFiles*/ - [], - /*typeReferences*/ - [], - /*hasNoDefaultLib*/ - false, - /*libReferences*/ - [] - ); - }), - mapDefined(node.prepends, (prepend) => { - if (prepend.kind === 315 /* InputFiles */) { - const sourceFile = createUnparsedSourceFile(prepend, "dts", stripInternal); - hasNoDefaultLib = hasNoDefaultLib || !!sourceFile.hasNoDefaultLib; - collectReferences(sourceFile, refs); - recordTypeReferenceDirectivesIfNecessary(map(sourceFile.typeReferenceDirectives, (ref) => [ref.fileName, ref.resolutionMode])); - collectLibs(sourceFile, libs2); - return sourceFile; - } - return prepend; - }) - ); + return sourceFile; + } + return prepend; + })); bundle.syntheticFileReferences = []; bundle.syntheticTypeReferences = getFileReferencesForUsedTypeReferences(); bundle.syntheticLibReferences = getLibReferences(); bundle.hasNoDefaultLib = hasNoDefaultLib; - const outputFilePath2 = getDirectoryPath(normalizeSlashes(getOutputPathsFor( - node, - host, - /*forceDtsPaths*/ - true - ).declarationFilePath)); + const outputFilePath2 = getDirectoryPath(normalizeSlashes(getOutputPathsFor(node, host, /*forceDtsPaths*/ + true).declarationFilePath)); const referenceVisitor2 = mapReferencesIntoArray(bundle.syntheticFileReferences, outputFilePath2); refs.forEach(referenceVisitor2); return bundle; @@ -110573,17 +98060,13 @@ ${lanes.join("\n")} resultHasExternalModuleIndicator = false; suppressNewDiagnosticContexts = false; lateMarkedStatements = void 0; - lateStatementReplacementMap = /* @__PURE__ */ new Map(); + lateStatementReplacementMap = /* @__PURE__ */new Map(); necessaryTypeReferences = void 0; - refs = collectReferences(currentSourceFile, /* @__PURE__ */ new Map()); - libs2 = collectLibs(currentSourceFile, /* @__PURE__ */ new Map()); + refs = collectReferences(currentSourceFile, /* @__PURE__ */new Map()); + libs2 = collectLibs(currentSourceFile, /* @__PURE__ */new Map()); const references = []; - const outputFilePath = getDirectoryPath(normalizeSlashes(getOutputPathsFor( - node, - host, - /*forceDtsPaths*/ - true - ).declarationFilePath)); + const outputFilePath = getDirectoryPath(normalizeSlashes(getOutputPathsFor(node, host, /*forceDtsPaths*/ + true).declarationFilePath)); const referenceVisitor = mapReferencesIntoArray(references, outputFilePath); let combinedStatements; if (isSourceFileJS(currentSourceFile)) { @@ -110599,20 +98082,16 @@ ${lanes.join("\n")} combinedStatements = setTextRange(factory2.createNodeArray([...combinedStatements, createEmptyExports(factory2)]), combinedStatements); } } - const updated = factory2.updateSourceFile( - node, - combinedStatements, - /*isDeclarationFile*/ - true, - references, - getFileReferencesForUsedTypeReferences(), - node.hasNoDefaultLib, - getLibReferences() - ); + const updated = factory2.updateSourceFile(node, combinedStatements, /*isDeclarationFile*/ + true, references, getFileReferencesForUsedTypeReferences(), node.hasNoDefaultLib, getLibReferences()); updated.exportedModulesFromDeclarationEmit = exportedModulesFromDeclarationEmit; return updated; function getLibReferences() { - return arrayFrom(libs2.keys(), (lib) => ({ fileName: lib, pos: -1, end: -1 })); + return arrayFrom(libs2.keys(), lib => ({ + fileName: lib, + pos: -1, + end: -1 + })); } function getFileReferencesForUsedTypeReferences() { return necessaryTypeReferences ? mapDefined(arrayFrom(necessaryTypeReferences.keys()), getFileReferenceForSpecifierModeTuple) : []; @@ -110630,63 +98109,53 @@ ${lanes.join("\n")} } } } - return { fileName: typeName, pos: -1, end: -1, ...mode ? { resolutionMode: mode } : void 0 }; + return { + fileName: typeName, + pos: -1, + end: -1, + ...(mode ? { + resolutionMode: mode + } : void 0) + }; } function mapReferencesIntoArray(references2, outputFilePath2) { - return (file) => { + return file => { let declFileName; if (file.isDeclarationFile) { declFileName = file.fileName; } else { - if (isBundledEmit && contains(node.sourceFiles, file)) - return; - const paths = getOutputPathsFor( - file, - host, - /*forceDtsPaths*/ - true - ); + if (isBundledEmit && contains(node.sourceFiles, file)) return; + const paths = getOutputPathsFor(file, host, /*forceDtsPaths*/ + true); declFileName = paths.declarationFilePath || paths.jsFilePath || file.fileName; } if (declFileName) { - const specifier = getModuleSpecifier( - options, - currentSourceFile, - toPath(outputFilePath2, host.getCurrentDirectory(), host.getCanonicalFileName), - toPath(declFileName, host.getCurrentDirectory(), host.getCanonicalFileName), - host - ); + const specifier = getModuleSpecifier(options, currentSourceFile, toPath(outputFilePath2, host.getCurrentDirectory(), host.getCanonicalFileName), toPath(declFileName, host.getCurrentDirectory(), host.getCanonicalFileName), host); if (!pathIsRelative(specifier)) { - recordTypeReferenceDirectivesIfNecessary([[ - specifier, - /*mode*/ - void 0 - ]]); + recordTypeReferenceDirectivesIfNecessary([[specifier, /*mode*/ + void 0]]); return; } - let fileName = getRelativePathToDirectoryOrUrl( - outputFilePath2, - declFileName, - host.getCurrentDirectory(), - host.getCanonicalFileName, - /*isAbsolutePathAnUrl*/ - false - ); + let fileName = getRelativePathToDirectoryOrUrl(outputFilePath2, declFileName, host.getCurrentDirectory(), host.getCanonicalFileName, /*isAbsolutePathAnUrl*/ + false); if (startsWith(fileName, "./") && hasExtension(fileName)) { fileName = fileName.substring(2); } if (startsWith(fileName, "node_modules/") || pathContainsNodeModules(fileName)) { return; } - references2.push({ pos: -1, end: -1, fileName }); + references2.push({ + pos: -1, + end: -1, + fileName + }); } }; } } function collectReferences(sourceFile, ret) { - if (noResolve || !isUnparsedSource(sourceFile) && isSourceFileJS(sourceFile)) - return ret; - forEach(sourceFile.referencedFiles, (f) => { + if (noResolve || !isUnparsedSource(sourceFile) && isSourceFileJS(sourceFile)) return ret; + forEach(sourceFile.referencedFiles, f => { const elem = host.getSourceFileFromReference(sourceFile, f); if (elem) { ret.set(getOriginalNodeId(elem), elem); @@ -110695,7 +98164,7 @@ ${lanes.join("\n")} return ret; } function collectLibs(sourceFile, ret) { - forEach(sourceFile.libReferenceDirectives, (ref) => { + forEach(sourceFile.libReferenceDirectives, ref => { const lib = host.getLibFileFromReference(ref); if (lib) { ret.set(toFileNameLowerCase(ref.fileName), true); @@ -110721,22 +98190,10 @@ ${lanes.join("\n")} checkEntityNameVisibility(elem.propertyName.expression, enclosingDeclaration); } if (elem.propertyName && isIdentifier(elem.propertyName) && isIdentifier(elem.name) && !elem.symbol.isReferenced && !isIdentifierANonContextualKeyword(elem.propertyName)) { - return factory2.updateBindingElement( - elem, - elem.dotDotDotToken, - /*propertyName*/ - void 0, - elem.propertyName, - shouldPrintWithInitializer(elem) ? elem.initializer : void 0 - ); + return factory2.updateBindingElement(elem, elem.dotDotDotToken, /*propertyName*/ + void 0, elem.propertyName, shouldPrintWithInitializer(elem) ? elem.initializer : void 0); } - return factory2.updateBindingElement( - elem, - elem.dotDotDotToken, - elem.propertyName, - filterBindingPatternInitializersAndRenamings(elem.name), - shouldPrintWithInitializer(elem) ? elem.initializer : void 0 - ); + return factory2.updateBindingElement(elem, elem.dotDotDotToken, elem.propertyName, filterBindingPatternInitializersAndRenamings(elem.name), shouldPrintWithInitializer(elem) ? elem.initializer : void 0); } } function ensureParameter(p, modifierMask, type) { @@ -110745,21 +98202,10 @@ ${lanes.join("\n")} oldDiag = getSymbolAccessibilityDiagnostic; getSymbolAccessibilityDiagnostic = createGetSymbolAccessibilityDiagnosticForNode(p); } - const newParam = factory2.updateParameterDeclaration( - p, - maskModifiers(factory2, p, modifierMask), - p.dotDotDotToken, - filterBindingPatternInitializersAndRenamings(p.name), - resolver.isOptionalParameter(p) ? p.questionToken || factory2.createToken(58 /* QuestionToken */) : void 0, - ensureType( - p, - type || p.type, - /*ignorePrivate*/ - true - ), - // Ignore private param props, since this type is going straight back into a param - ensureNoInitializer(p) - ); + const newParam = factory2.updateParameterDeclaration(p, maskModifiers(factory2, p, modifierMask), p.dotDotDotToken, filterBindingPatternInitializersAndRenamings(p.name), resolver.isOptionalParameter(p) ? p.questionToken || factory2.createToken(58 /* QuestionToken */) : void 0, ensureType(p, type || p.type, /*ignorePrivate*/ + true), + // Ignore private param props, since this type is going straight back into a param + ensureNoInitializer(p)); if (!suppressNewDiagnosticContexts) { getSymbolAccessibilityDiagnostic = oldDiag; } @@ -110788,9 +98234,11 @@ ${lanes.join("\n")} if (!getParseTreeNode(node)) { return type ? visitNode(type, visitDeclarationSubtree, isTypeNode) : factory2.createKeywordTypeNode(133 /* AnyKeyword */); } + if (node.kind === 178 /* SetAccessor */) { return factory2.createKeywordTypeNode(133 /* AnyKeyword */); } + errorNameNode = node.name; let oldDiag; if (!suppressNewDiagnosticContexts) { @@ -110801,8 +98249,7 @@ ${lanes.join("\n")} return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker)); } if (node.kind === 169 /* Parameter */ || node.kind === 172 /* PropertyDeclaration */ || node.kind === 171 /* PropertySignature */) { - if (isPropertySignature(node) || !node.initializer) - return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker, shouldUseResolverType)); + if (isPropertySignature(node) || !node.initializer) return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker, shouldUseResolverType)); return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker, shouldUseResolverType) || resolver.createTypeOfExpression(node.initializer, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker)); } return cleanup(resolver.createReturnTypeOfSignatureDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker)); @@ -110814,6 +98261,7 @@ ${lanes.join("\n")} return returnValue || factory2.createKeywordTypeNode(133 /* AnyKeyword */); } } + function isDeclarationAndNotVisible(node) { node = getParseTreeNode(node); switch (node.kind) { @@ -110841,7 +98289,7 @@ ${lanes.join("\n")} if (input.body) { return true; } - const overloadSignatures = (_a = input.symbol.declarations) == null ? void 0 : _a.filter((decl) => isFunctionDeclaration(decl) && !decl.body); + const overloadSignatures = (_a = input.symbol.declarations) == null ? void 0 : _a.filter(decl => isFunctionDeclaration(decl) && !decl.body); return !overloadSignatures || overloadSignatures.indexOf(input) === overloadSignatures.length - 1; } function getBindingNameVisible(elem) { @@ -110858,7 +98306,7 @@ ${lanes.join("\n")} if (hasEffectiveModifier(node, 2 /* Private */)) { return factory2.createNodeArray(); } - const newParams = map(params, (p) => ensureParameter(p, modifierMask)); + const newParams = map(params, p => ensureParameter(p, modifierMask)); if (!newParams) { return factory2.createNodeArray(); } @@ -110878,22 +98326,14 @@ ${lanes.join("\n")} const valueParameter = getSetAccessorValueParameter(input); if (valueParameter) { const accessorType = getTypeAnnotationFromAllAccessorDeclarations(input, resolver.getAllAccessorDeclarations(input)); - newValueParameter = ensureParameter( - valueParameter, - /*modifierMask*/ - void 0, - accessorType - ); + newValueParameter = ensureParameter(valueParameter, /*modifierMask*/ + void 0, accessorType); } } if (!newValueParameter) { - newValueParameter = factory2.createParameterDeclaration( - /*modifiers*/ - void 0, - /*dotDotDotToken*/ - void 0, - "value" - ); + newValueParameter = factory2.createParameterDeclaration( /*modifiers*/ + void 0, /*dotDotDotToken*/ + void 0, "value"); } newParams = append(newParams, newValueParameter); } @@ -110917,8 +98357,7 @@ ${lanes.join("\n")} 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) { @@ -110936,17 +98375,10 @@ ${lanes.join("\n")} 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( - decl, - decl.modifiers, - decl.isTypeOnly, - decl.name, - factory2.updateExternalModuleReference(decl.moduleReference, rewriteModuleSpecifier(decl, specifier)) - ); + return factory2.updateImportEqualsDeclaration(decl, decl.modifiers, decl.isTypeOnly, decl.name, factory2.updateExternalModuleReference(decl.moduleReference, rewriteModuleSpecifier(decl, specifier))); } else { const oldDiag = getSymbolAccessibilityDiagnostic; getSymbolAccessibilityDiagnostic = createGetSymbolAccessibilityDiagnosticForNode(decl); @@ -110957,72 +98389,25 @@ ${lanes.join("\n")} } function transformImportDeclaration(decl) { if (!decl.importClause) { - return factory2.updateImportDeclaration( - decl, - decl.modifiers, - decl.importClause, - rewriteModuleSpecifier(decl, decl.moduleSpecifier), - tryGetResolutionModeOverride(decl.attributes) - ); + return factory2.updateImportDeclaration(decl, decl.modifiers, decl.importClause, rewriteModuleSpecifier(decl, decl.moduleSpecifier), tryGetResolutionModeOverride(decl.attributes)); } const visibleDefaultBinding = decl.importClause && decl.importClause.name && resolver.isDeclarationVisible(decl.importClause) ? decl.importClause.name : void 0; if (!decl.importClause.namedBindings) { - return visibleDefaultBinding && factory2.updateImportDeclaration( - decl, - decl.modifiers, - factory2.updateImportClause( - decl.importClause, - decl.importClause.isTypeOnly, - visibleDefaultBinding, - /*namedBindings*/ - void 0 - ), - rewriteModuleSpecifier(decl, decl.moduleSpecifier), - tryGetResolutionModeOverride(decl.attributes) - ); + return visibleDefaultBinding && factory2.updateImportDeclaration(decl, decl.modifiers, factory2.updateImportClause(decl.importClause, decl.importClause.isTypeOnly, visibleDefaultBinding, /*namedBindings*/ + void 0), rewriteModuleSpecifier(decl, decl.moduleSpecifier), tryGetResolutionModeOverride(decl.attributes)); } if (decl.importClause.namedBindings.kind === 274 /* NamespaceImport */) { - const namedBindings = resolver.isDeclarationVisible(decl.importClause.namedBindings) ? decl.importClause.namedBindings : ( - /*namedBindings*/ - void 0 - ); - return visibleDefaultBinding || namedBindings ? factory2.updateImportDeclaration( - decl, - decl.modifiers, - factory2.updateImportClause( - decl.importClause, - decl.importClause.isTypeOnly, - visibleDefaultBinding, - namedBindings - ), - rewriteModuleSpecifier(decl, decl.moduleSpecifier), - tryGetResolutionModeOverride(decl.attributes) - ) : void 0; + const namedBindings = resolver.isDeclarationVisible(decl.importClause.namedBindings) ? decl.importClause.namedBindings : /*namedBindings*/ + void 0; + return visibleDefaultBinding || namedBindings ? factory2.updateImportDeclaration(decl, decl.modifiers, factory2.updateImportClause(decl.importClause, decl.importClause.isTypeOnly, visibleDefaultBinding, namedBindings), rewriteModuleSpecifier(decl, decl.moduleSpecifier), tryGetResolutionModeOverride(decl.attributes)) : void 0; } - const bindingList = mapDefined(decl.importClause.namedBindings.elements, (b) => resolver.isDeclarationVisible(b) ? b : void 0); + const bindingList = mapDefined(decl.importClause.namedBindings.elements, b => resolver.isDeclarationVisible(b) ? b : void 0); if (bindingList && bindingList.length || visibleDefaultBinding) { - return factory2.updateImportDeclaration( - decl, - decl.modifiers, - factory2.updateImportClause( - decl.importClause, - decl.importClause.isTypeOnly, - visibleDefaultBinding, - bindingList && bindingList.length ? factory2.updateNamedImports(decl.importClause.namedBindings, bindingList) : void 0 - ), - rewriteModuleSpecifier(decl, decl.moduleSpecifier), - tryGetResolutionModeOverride(decl.attributes) - ); + return factory2.updateImportDeclaration(decl, decl.modifiers, factory2.updateImportClause(decl.importClause, decl.importClause.isTypeOnly, visibleDefaultBinding, bindingList && bindingList.length ? factory2.updateNamedImports(decl.importClause.namedBindings, bindingList) : void 0), rewriteModuleSpecifier(decl, decl.moduleSpecifier), tryGetResolutionModeOverride(decl.attributes)); } if (resolver.isImportRequiredByAugmentation(decl)) { - return factory2.updateImportDeclaration( - decl, - decl.modifiers, - /*importClause*/ - void 0, - rewriteModuleSpecifier(decl, decl.moduleSpecifier), - tryGetResolutionModeOverride(decl.attributes) - ); + return factory2.updateImportDeclaration(decl, decl.modifiers, /*importClause*/ + void 0, rewriteModuleSpecifier(decl, decl.moduleSpecifier), tryGetResolutionModeOverride(decl.attributes)); } } function tryGetResolutionModeOverride(node) { @@ -111063,19 +98448,15 @@ ${lanes.join("\n")} } } function visitDeclarationSubtree(input) { - if (shouldStripInternal(input)) - return; + if (shouldStripInternal(input)) return; if (isDeclaration(input)) { - if (isDeclarationAndNotVisible(input)) - return; + if (isDeclarationAndNotVisible(input)) return; if (hasDynamicName(input) && !resolver.isLateBound(getParseTreeNode(input))) { 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; @@ -111087,18 +98468,11 @@ ${lanes.join("\n")} 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; - return cleanup(factory2.createPropertyDeclaration( - ensureModifiers(input), - input.name, - /*questionOrExclamationToken*/ - void 0, - /*type*/ - void 0, - /*initializer*/ - void 0 - )); + if (input.symbol && input.symbol.declarations && input.symbol.declarations[0] !== input) return; + return cleanup(factory2.createPropertyDeclaration(ensureModifiers(input), input.name, /*questionOrExclamationToken*/ + void 0, /*type*/ + void 0, /*initializer*/ + void 0)); } } if (canProduceDiagnostic && !suppressNewDiagnosticContexts) { @@ -111112,214 +98486,136 @@ ${lanes.join("\n")} } if (isProcessedComponent(input)) { switch (input.kind) { - case 233 /* ExpressionWithTypeArguments */: { - if (isEntityName(input.expression) || isEntityNameExpression(input.expression)) { - checkEntityNameVisibility(input.expression, enclosingDeclaration); + case 233 /* ExpressionWithTypeArguments */: + { + if (isEntityName(input.expression) || isEntityNameExpression(input.expression)) { + checkEntityNameVisibility(input.expression, enclosingDeclaration); + } + const node = visitEachChild(input, visitDeclarationSubtree, context); + return cleanup(factory2.updateExpressionWithTypeArguments(node, node.expression, node.typeArguments)); + } + case 183 /* TypeReference */: + { + checkEntityNameVisibility(input.typeName, enclosingDeclaration); + const node = visitEachChild(input, visitDeclarationSubtree, context); + return cleanup(factory2.updateTypeReferenceNode(node, node.typeName, node.typeArguments)); } - const node = visitEachChild(input, visitDeclarationSubtree, context); - return cleanup(factory2.updateExpressionWithTypeArguments(node, node.expression, node.typeArguments)); - } - case 183 /* TypeReference */: { - checkEntityNameVisibility(input.typeName, enclosingDeclaration); - const node = visitEachChild(input, visitDeclarationSubtree, context); - return cleanup(factory2.updateTypeReferenceNode(node, node.typeName, node.typeArguments)); - } case 180 /* ConstructSignature */: - return cleanup(factory2.updateConstructSignature( - input, - ensureTypeParams(input, input.typeParameters), - updateParamsList(input, input.parameters), - ensureType(input, input.type) - )); - case 176 /* Constructor */: { - const ctor = factory2.createConstructorDeclaration( - /*modifiers*/ - ensureModifiers(input), - updateParamsList(input, input.parameters, 0 /* None */), - /*body*/ - void 0 - ); - return cleanup(ctor); - } - case 174 /* MethodDeclaration */: { - if (isPrivateIdentifier(input.name)) { - return cleanup( - /*returnValue*/ - void 0 - ); + return cleanup(factory2.updateConstructSignature(input, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type))); + case 176 /* Constructor */: + { + const ctor = factory2.createConstructorDeclaration( /*modifiers*/ + ensureModifiers(input), updateParamsList(input, input.parameters, 0 /* None */), /*body*/ + void 0); + return cleanup(ctor); } - const sig = factory2.createMethodDeclaration( - ensureModifiers(input), - /*asteriskToken*/ - void 0, - input.name, - input.questionToken, - ensureTypeParams(input, input.typeParameters), - updateParamsList(input, input.parameters), - ensureType(input, input.type), - /*body*/ - void 0 - ); - return cleanup(sig); - } - case 177 /* GetAccessor */: { - if (isPrivateIdentifier(input.name)) { - return cleanup( - /*returnValue*/ - void 0 - ); + case 174 /* MethodDeclaration */: + { + if (isPrivateIdentifier(input.name)) { + return cleanup( /*returnValue*/ + void 0); + } + const sig = factory2.createMethodDeclaration(ensureModifiers(input), /*asteriskToken*/ + void 0, input.name, input.questionToken, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type), /*body*/ + void 0); + return cleanup(sig); } - const accessorType = getTypeAnnotationFromAllAccessorDeclarations(input, resolver.getAllAccessorDeclarations(input)); - return cleanup(factory2.updateGetAccessorDeclaration( - input, - ensureModifiers(input), - input.name, - updateAccessorParamsList(input, hasEffectiveModifier(input, 2 /* Private */)), - ensureType(input, accessorType), - /*body*/ - void 0 - )); - } - case 178 /* SetAccessor */: { - if (isPrivateIdentifier(input.name)) { - return cleanup( - /*returnValue*/ - void 0 - ); + case 177 /* GetAccessor */: + { + if (isPrivateIdentifier(input.name)) { + return cleanup( /*returnValue*/ + void 0); + } + const accessorType = getTypeAnnotationFromAllAccessorDeclarations(input, resolver.getAllAccessorDeclarations(input)); + return cleanup(factory2.updateGetAccessorDeclaration(input, ensureModifiers(input), input.name, updateAccessorParamsList(input, hasEffectiveModifier(input, 2 /* Private */)), ensureType(input, accessorType), /*body*/ + void 0)); + } + case 178 /* SetAccessor */: + { + if (isPrivateIdentifier(input.name)) { + return cleanup( /*returnValue*/ + void 0); + } + return cleanup(factory2.updateSetAccessorDeclaration(input, ensureModifiers(input), input.name, updateAccessorParamsList(input, hasEffectiveModifier(input, 2 /* Private */)), /*body*/ + void 0)); } - return cleanup(factory2.updateSetAccessorDeclaration( - input, - ensureModifiers(input), - input.name, - updateAccessorParamsList(input, hasEffectiveModifier(input, 2 /* Private */)), - /*body*/ - void 0 - )); - } case 172 /* PropertyDeclaration */: if (isPrivateIdentifier(input.name)) { - return cleanup( - /*returnValue*/ - void 0 - ); + return cleanup( /*returnValue*/ + void 0); } - return cleanup(factory2.updatePropertyDeclaration( - input, - ensureModifiers(input), - input.name, - input.questionToken, - ensureType(input, input.type), - ensureNoInitializer(input) - )); + return cleanup(factory2.updatePropertyDeclaration(input, ensureModifiers(input), input.name, input.questionToken, ensureType(input, input.type), ensureNoInitializer(input))); case 171 /* PropertySignature */: if (isPrivateIdentifier(input.name)) { - return cleanup( - /*returnValue*/ - void 0 - ); + return cleanup( /*returnValue*/ + void 0); } - return cleanup(factory2.updatePropertySignature( - input, - ensureModifiers(input), - input.name, - input.questionToken, - ensureType(input, input.type) - )); - case 173 /* MethodSignature */: { - if (isPrivateIdentifier(input.name)) { - return cleanup( - /*returnValue*/ - void 0 - ); + return cleanup(factory2.updatePropertySignature(input, ensureModifiers(input), input.name, input.questionToken, ensureType(input, input.type))); + case 173 /* MethodSignature */: + { + if (isPrivateIdentifier(input.name)) { + return cleanup( /*returnValue*/ + void 0); + } + return cleanup(factory2.updateMethodSignature(input, ensureModifiers(input), input.name, input.questionToken, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type))); } - return cleanup(factory2.updateMethodSignature( - input, - ensureModifiers(input), - input.name, - input.questionToken, - ensureTypeParams(input, input.typeParameters), - updateParamsList(input, input.parameters), - ensureType(input, input.type) - )); - } - case 179 /* CallSignature */: { - return cleanup(factory2.updateCallSignature( - input, - ensureTypeParams(input, input.typeParameters), - updateParamsList(input, input.parameters), - ensureType(input, input.type) - )); - } - case 181 /* IndexSignature */: { - return cleanup(factory2.updateIndexSignature( - input, - ensureModifiers(input), - updateParamsList(input, input.parameters), - visitNode(input.type, visitDeclarationSubtree, isTypeNode) || factory2.createKeywordTypeNode(133 /* AnyKeyword */) - )); - } - case 260 /* VariableDeclaration */: { - if (isBindingPattern(input.name)) { - return recreateBindingPattern(input.name); + case 179 /* CallSignature */: + { + return cleanup(factory2.updateCallSignature(input, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type))); } - shouldEnterSuppressNewDiagnosticsContextContext = true; - suppressNewDiagnosticContexts = true; - return cleanup(factory2.updateVariableDeclaration( - input, - input.name, - /*exclamationToken*/ - void 0, - ensureType(input, input.type), - ensureNoInitializer(input) - )); - } - case 168 /* TypeParameter */: { - if (isPrivateMethodTypeParameter(input) && (input.default || input.constraint)) { - return cleanup(factory2.updateTypeParameterDeclaration( - input, - input.modifiers, - input.name, - /*constraint*/ - void 0, - /*defaultType*/ - void 0 - )); + case 181 /* IndexSignature */: + { + return cleanup(factory2.updateIndexSignature(input, ensureModifiers(input), updateParamsList(input, input.parameters), visitNode(input.type, visitDeclarationSubtree, isTypeNode) || factory2.createKeywordTypeNode(133 /* AnyKeyword */))); + } + + case 260 /* VariableDeclaration */: + { + if (isBindingPattern(input.name)) { + return recreateBindingPattern(input.name); + } + shouldEnterSuppressNewDiagnosticsContextContext = true; + suppressNewDiagnosticContexts = true; + return cleanup(factory2.updateVariableDeclaration(input, input.name, /*exclamationToken*/ + void 0, ensureType(input, input.type), ensureNoInitializer(input))); + } + case 168 /* TypeParameter */: + { + if (isPrivateMethodTypeParameter(input) && (input.default || input.constraint)) { + return cleanup(factory2.updateTypeParameterDeclaration(input, input.modifiers, input.name, /*constraint*/ + void 0, /*defaultType*/ + void 0)); + } + return cleanup(visitEachChild(input, visitDeclarationSubtree, context)); + } + case 194 /* ConditionalType */: + { + const checkType = visitNode(input.checkType, visitDeclarationSubtree, isTypeNode); + const extendsType = visitNode(input.extendsType, visitDeclarationSubtree, isTypeNode); + const oldEnclosingDecl = enclosingDeclaration; + enclosingDeclaration = input.trueType; + const trueType = visitNode(input.trueType, visitDeclarationSubtree, isTypeNode); + enclosingDeclaration = oldEnclosingDecl; + const falseType = visitNode(input.falseType, visitDeclarationSubtree, isTypeNode); + Debug.assert(checkType); + Debug.assert(extendsType); + Debug.assert(trueType); + Debug.assert(falseType); + return cleanup(factory2.updateConditionalTypeNode(input, checkType, extendsType, trueType, falseType)); + } + case 184 /* FunctionType */: + { + return cleanup(factory2.updateFunctionTypeNode(input, visitNodes2(input.typeParameters, visitDeclarationSubtree, isTypeParameterDeclaration), updateParamsList(input, input.parameters), Debug.checkDefined(visitNode(input.type, visitDeclarationSubtree, isTypeNode)))); + } + case 185 /* ConstructorType */: + { + return cleanup(factory2.updateConstructorTypeNode(input, ensureModifiers(input), visitNodes2(input.typeParameters, visitDeclarationSubtree, isTypeParameterDeclaration), updateParamsList(input, input.parameters), Debug.checkDefined(visitNode(input.type, visitDeclarationSubtree, isTypeNode)))); + } + case 205 /* ImportType */: + { + if (!isLiteralImportTypeNode(input)) return cleanup(input); + trackReferencedAmbientModuleFromImport(input); + return cleanup(factory2.updateImportTypeNode(input, factory2.updateLiteralTypeNode(input.argument, rewriteModuleSpecifier(input, input.argument.literal)), input.attributes, input.qualifier, visitNodes2(input.typeArguments, visitDeclarationSubtree, isTypeNode), input.isTypeOf)); } - return cleanup(visitEachChild(input, visitDeclarationSubtree, context)); - } - case 194 /* ConditionalType */: { - const checkType = visitNode(input.checkType, visitDeclarationSubtree, isTypeNode); - const extendsType = visitNode(input.extendsType, visitDeclarationSubtree, isTypeNode); - const oldEnclosingDecl = enclosingDeclaration; - enclosingDeclaration = input.trueType; - const trueType = visitNode(input.trueType, visitDeclarationSubtree, isTypeNode); - enclosingDeclaration = oldEnclosingDecl; - const falseType = visitNode(input.falseType, visitDeclarationSubtree, isTypeNode); - Debug.assert(checkType); - Debug.assert(extendsType); - Debug.assert(trueType); - Debug.assert(falseType); - return cleanup(factory2.updateConditionalTypeNode(input, checkType, extendsType, trueType, falseType)); - } - case 184 /* FunctionType */: { - return cleanup(factory2.updateFunctionTypeNode(input, visitNodes2(input.typeParameters, visitDeclarationSubtree, isTypeParameterDeclaration), updateParamsList(input, input.parameters), Debug.checkDefined(visitNode(input.type, visitDeclarationSubtree, isTypeNode)))); - } - case 185 /* ConstructorType */: { - return cleanup(factory2.updateConstructorTypeNode(input, ensureModifiers(input), visitNodes2(input.typeParameters, visitDeclarationSubtree, isTypeParameterDeclaration), updateParamsList(input, input.parameters), Debug.checkDefined(visitNode(input.type, visitDeclarationSubtree, isTypeNode)))); - } - case 205 /* ImportType */: { - if (!isLiteralImportTypeNode(input)) - return cleanup(input); - trackReferencedAmbientModuleFromImport(input); - return cleanup(factory2.updateImportTypeNode( - input, - factory2.updateLiteralTypeNode(input.argument, rewriteModuleSpecifier(input, input.argument.literal)), - input.attributes, - input.qualifier, - visitNodes2(input.typeArguments, visitDeclarationSubtree, isTypeNode), - input.isTypeOf - )); - } default: Debug.assertNever(input, `Attempted to process unhandled node kind: ${Debug.formatSyntaxKind(input.kind)}`); } @@ -111327,6 +98623,7 @@ ${lanes.join("\n")} if (isTupleTypeNode(input) && getLineAndCharacterOfPosition(currentSourceFile, input.pos).line === getLineAndCharacterOfPosition(currentSourceFile, input.end).line) { setEmitFlags(input, 1 /* SingleLine */); } + return cleanup(visitEachChild(input, visitDeclarationSubtree, context)); function cleanup(returnValue) { if (returnValue && canProduceDiagnostic && hasDynamicName(input)) { @@ -111350,57 +98647,47 @@ ${lanes.join("\n")} function isPrivateMethodTypeParameter(node) { return node.parent.kind === 174 /* MethodDeclaration */ && hasEffectiveModifier(node.parent, 2 /* Private */); } + function visitDeclarationStatements(input) { if (!isPreservedDeclarationStatement(input)) { return; } - if (shouldStripInternal(input)) - return; + if (shouldStripInternal(input)) return; switch (input.kind) { - case 278 /* ExportDeclaration */: { - if (isSourceFile(input.parent)) { - resultHasExternalModuleIndicator = true; + case 278 /* ExportDeclaration */: + { + if (isSourceFile(input.parent)) { + resultHasExternalModuleIndicator = true; + } + resultHasScopeMarker = true; + trackReferencedAmbientModuleFromImport(input); + return factory2.updateExportDeclaration(input, input.modifiers, input.isTypeOnly, input.exportClause, rewriteModuleSpecifier(input, input.moduleSpecifier), tryGetResolutionModeOverride(input.attributes)); } - resultHasScopeMarker = true; - trackReferencedAmbientModuleFromImport(input); - return factory2.updateExportDeclaration( - input, - input.modifiers, - input.isTypeOnly, - input.exportClause, - rewriteModuleSpecifier(input, input.moduleSpecifier), - tryGetResolutionModeOverride(input.attributes) - ); - } - case 277 /* ExportAssignment */: { - if (isSourceFile(input.parent)) { - resultHasExternalModuleIndicator = true; + case 277 /* ExportAssignment */: + { + if (isSourceFile(input.parent)) { + resultHasExternalModuleIndicator = true; + } + resultHasScopeMarker = true; + if (input.expression.kind === 80 /* Identifier */) { + return input; + } else { + const newId = factory2.createUniqueName("_default", 16 /* Optimistic */); + getSymbolAccessibilityDiagnostic = () => ({ + diagnosticMessage: Diagnostics.Default_export_of_the_module_has_or_is_using_private_name_0, + errorNode: input + }); + errorFallbackNode = input; + const varDecl = factory2.createVariableDeclaration(newId, /*exclamationToken*/ + void 0, resolver.createTypeOfExpression(input.expression, input, declarationEmitNodeBuilderFlags, symbolTracker), /*initializer*/ + void 0); + errorFallbackNode = void 0; + const statement = factory2.createVariableStatement(needsDeclare ? [factory2.createModifier(138 /* DeclareKeyword */)] : [], factory2.createVariableDeclarationList([varDecl], 2 /* Const */)); + preserveJsDoc(statement, input); + removeAllComments(input); + return [statement, factory2.updateExportAssignment(input, input.modifiers, newId)]; + } } - resultHasScopeMarker = true; - if (input.expression.kind === 80 /* Identifier */) { - return input; - } else { - const newId = factory2.createUniqueName("_default", 16 /* Optimistic */); - getSymbolAccessibilityDiagnostic = () => ({ - diagnosticMessage: Diagnostics.Default_export_of_the_module_has_or_is_using_private_name_0, - errorNode: input - }); - errorFallbackNode = input; - const varDecl = factory2.createVariableDeclaration( - newId, - /*exclamationToken*/ - void 0, - resolver.createTypeOfExpression(input.expression, input, declarationEmitNodeBuilderFlags, symbolTracker), - /*initializer*/ - void 0 - ); - errorFallbackNode = void 0; - const statement = factory2.createVariableStatement(needsDeclare ? [factory2.createModifier(138 /* DeclareKeyword */)] : [], factory2.createVariableDeclarationList([varDecl], 2 /* Const */)); - preserveJsDoc(statement, input); - removeAllComments(input); - return [statement, factory2.updateExportAssignment(input, input.modifiers, newId)]; - } - } } const result = transformTopLevelDeclaration(input); lateStatementReplacementMap.set(getOriginalNodeId(input), result); @@ -111418,43 +98705,37 @@ ${lanes.join("\n")} if (isAmbientModule(updated) || updated.flags & 32 /* Namespace */) { return updated; } - const fixed = factory2.createModuleDeclaration( - updated.modifiers, - updated.name, - updated.body, - updated.flags | 32 /* Namespace */ - ); + const fixed = factory2.createModuleDeclaration(updated.modifiers, updated.name, updated.body, updated.flags | 32 /* Namespace */); + setOriginalNode(fixed, updated); setTextRange(fixed, updated); return fixed; } function transformTopLevelDeclaration(input) { if (lateMarkedStatements) { - while (orderedRemoveItem(lateMarkedStatements, input)) - ; + while (orderedRemoveItem(lateMarkedStatements, input)); } - if (shouldStripInternal(input)) - return; + if (shouldStripInternal(input)) return; switch (input.kind) { - case 271 /* ImportEqualsDeclaration */: { - const transformed = transformImportEqualsDeclaration(input); - if (transformed) { - trackReferencedAmbientModuleFromImport(input); + case 271 /* ImportEqualsDeclaration */: + { + const transformed = transformImportEqualsDeclaration(input); + if (transformed) { + trackReferencedAmbientModuleFromImport(input); + } + return transformed; } - return transformed; - } - case 272 /* ImportDeclaration */: { - const transformed = transformImportDeclaration(input); - if (transformed) { - trackReferencedAmbientModuleFromImport(input); + case 272 /* ImportDeclaration */: + { + const transformed = transformImportDeclaration(input); + if (transformed) { + trackReferencedAmbientModuleFromImport(input); + } + return transformed; } - return transformed; - } } - if (isDeclaration(input) && isDeclarationAndNotVisible(input)) - return; - if (isFunctionLike(input) && resolver.isImplementationOfOverload(input)) - return; + if (isDeclaration(input) && isDeclarationAndNotVisible(input)) return; + if (isFunctionLike(input) && resolver.isImplementationOfOverload(input)) return; let previousEnclosingDeclaration; if (isEnclosingDeclaration(input)) { previousEnclosingDeclaration = enclosingDeclaration; @@ -111467,322 +98748,206 @@ ${lanes.join("\n")} } const previousNeedsDeclare = needsDeclare; switch (input.kind) { - case 265 /* TypeAliasDeclaration */: { - needsDeclare = false; - const clean2 = cleanup(factory2.updateTypeAliasDeclaration( - input, - ensureModifiers(input), - input.name, - visitNodes2(input.typeParameters, visitDeclarationSubtree, isTypeParameterDeclaration), - Debug.checkDefined(visitNode(input.type, visitDeclarationSubtree, isTypeNode)) - )); - needsDeclare = previousNeedsDeclare; - return clean2; - } - case 264 /* InterfaceDeclaration */: { - return cleanup(factory2.updateInterfaceDeclaration( - input, - ensureModifiers(input), - input.name, - ensureTypeParams(input, input.typeParameters), - transformHeritageClauses(input.heritageClauses), - visitNodes2(input.members, visitDeclarationSubtree, isTypeElement) - )); - } - case 262 /* FunctionDeclaration */: { - const clean2 = cleanup(factory2.updateFunctionDeclaration( - input, - ensureModifiers(input), - /*asteriskToken*/ - void 0, - input.name, - ensureTypeParams(input, input.typeParameters), - updateParamsList(input, input.parameters), - ensureType(input, input.type), - /*body*/ - void 0 - )); - if (clean2 && resolver.isExpandoFunctionDeclaration(input) && shouldEmitFunctionProperties(input)) { - const props = resolver.getPropertiesOfContainerFunction(input); - const fakespace = parseNodeFactory.createModuleDeclaration( - /*modifiers*/ - void 0, - clean2.name || factory2.createIdentifier("_default"), - factory2.createModuleBlock([]), - 32 /* Namespace */ - ); - setParent(fakespace, enclosingDeclaration); - fakespace.locals = createSymbolTable(props); - fakespace.symbol = props[0].parent; - const exportMappings = []; - let declarations = mapDefined(props, (p) => { - if (!isExpandoPropertyDeclaration(p.valueDeclaration)) { - return void 0; - } - const nameStr = unescapeLeadingUnderscores(p.escapedName); - if (!isIdentifierText(nameStr, 99 /* ESNext */)) { - return void 0; - } - getSymbolAccessibilityDiagnostic = createGetSymbolAccessibilityDiagnosticForNode(p.valueDeclaration); - const type = resolver.createTypeOfDeclaration(p.valueDeclaration, fakespace, declarationEmitNodeBuilderFlags, symbolTracker); - getSymbolAccessibilityDiagnostic = oldDiag; - const isNonContextualKeywordName = isStringANonContextualKeyword(nameStr); - const name = isNonContextualKeywordName ? factory2.getGeneratedNameForNode(p.valueDeclaration) : factory2.createIdentifier(nameStr); - if (isNonContextualKeywordName) { - exportMappings.push([name, nameStr]); - } - const varDecl = factory2.createVariableDeclaration( - name, - /*exclamationToken*/ - void 0, - type, - /*initializer*/ - void 0 - ); - return factory2.createVariableStatement(isNonContextualKeywordName ? void 0 : [factory2.createToken(95 /* ExportKeyword */)], factory2.createVariableDeclarationList([varDecl])); - }); - if (!exportMappings.length) { - declarations = mapDefined(declarations, (declaration) => factory2.replaceModifiers(declaration, 0 /* None */)); - } else { - declarations.push(factory2.createExportDeclaration( - /*modifiers*/ - void 0, - /*isTypeOnly*/ - false, - factory2.createNamedExports(map(exportMappings, ([gen, exp]) => { - return factory2.createExportSpecifier( - /*isTypeOnly*/ - false, - gen, - exp - ); - })) - )); - } - const namespaceDecl = factory2.createModuleDeclaration(ensureModifiers(input), input.name, factory2.createModuleBlock(declarations), 32 /* Namespace */); - if (!hasEffectiveModifier(clean2, 2048 /* Default */)) { - return [clean2, namespaceDecl]; - } - const modifiers = factory2.createModifiersFromModifierFlags(getEffectiveModifierFlags(clean2) & ~2080 /* ExportDefault */ | 128 /* Ambient */); - const cleanDeclaration = factory2.updateFunctionDeclaration( - clean2, - modifiers, - /*asteriskToken*/ - void 0, - clean2.name, - clean2.typeParameters, - clean2.parameters, - clean2.type, - /*body*/ - void 0 - ); - const namespaceDeclaration = factory2.updateModuleDeclaration( - namespaceDecl, - modifiers, - namespaceDecl.name, - namespaceDecl.body - ); - const exportDefaultDeclaration = factory2.createExportAssignment( - /*modifiers*/ - void 0, - /*isExportEquals*/ - false, - namespaceDecl.name - ); - if (isSourceFile(input.parent)) { - resultHasExternalModuleIndicator = true; - } - resultHasScopeMarker = true; - return [cleanDeclaration, namespaceDeclaration, exportDefaultDeclaration]; - } else { + case 265 /* TypeAliasDeclaration */: + { + needsDeclare = false; + const clean2 = cleanup(factory2.updateTypeAliasDeclaration(input, ensureModifiers(input), input.name, visitNodes2(input.typeParameters, visitDeclarationSubtree, isTypeParameterDeclaration), Debug.checkDefined(visitNode(input.type, visitDeclarationSubtree, isTypeNode)))); + needsDeclare = previousNeedsDeclare; return clean2; } - } - case 267 /* ModuleDeclaration */: { - needsDeclare = false; - const inner = input.body; - if (inner && inner.kind === 268 /* ModuleBlock */) { - const oldNeedsScopeFix = needsScopeFixMarker; - const oldHasScopeFix = resultHasScopeMarker; - resultHasScopeMarker = false; - needsScopeFixMarker = false; - const statements = visitNodes2(inner.statements, visitDeclarationStatements, isStatement); - let lateStatements = transformAndReplaceLatePaintedStatements(statements); - if (input.flags & 33554432 /* Ambient */) { - needsScopeFixMarker = false; - } - if (!isGlobalScopeAugmentation(input) && !hasScopeMarker2(lateStatements) && !resultHasScopeMarker) { - if (needsScopeFixMarker) { - lateStatements = factory2.createNodeArray([...lateStatements, createEmptyExports(factory2)]); - } else { - lateStatements = visitNodes2(lateStatements, stripExportModifiers, isStatement); - } - } - const body = factory2.updateModuleBlock(inner, lateStatements); - needsDeclare = previousNeedsDeclare; - needsScopeFixMarker = oldNeedsScopeFix; - resultHasScopeMarker = oldHasScopeFix; - const mods = ensureModifiers(input); - return cleanup(updateModuleDeclarationAndKeyword( - input, - mods, - isExternalModuleAugmentation(input) ? rewriteModuleSpecifier(input, input.name) : input.name, - body - )); - } else { - needsDeclare = previousNeedsDeclare; - const mods = ensureModifiers(input); - needsDeclare = false; - visitNode(inner, visitDeclarationStatements); - const id = getOriginalNodeId(inner); - const body = lateStatementReplacementMap.get(id); - lateStatementReplacementMap.delete(id); - return cleanup(updateModuleDeclarationAndKeyword( - input, - mods, - input.name, - body - )); + case 264 /* InterfaceDeclaration */: + { + return cleanup(factory2.updateInterfaceDeclaration(input, ensureModifiers(input), input.name, ensureTypeParams(input, input.typeParameters), transformHeritageClauses(input.heritageClauses), visitNodes2(input.members, visitDeclarationSubtree, isTypeElement))); } - } - case 263 /* ClassDeclaration */: { - errorNameNode = input.name; - errorFallbackNode = input; - const modifiers = factory2.createNodeArray(ensureModifiers(input)); - const typeParameters = ensureTypeParams(input, input.typeParameters); - const ctor = getFirstConstructorWithBody(input); - let parameterProperties; - if (ctor) { - const oldDiag2 = getSymbolAccessibilityDiagnostic; - parameterProperties = compact(flatMap(ctor.parameters, (param) => { - if (!hasSyntacticModifier(param, 31 /* ParameterPropertyModifier */) || shouldStripInternal(param)) - return; - getSymbolAccessibilityDiagnostic = createGetSymbolAccessibilityDiagnosticForNode(param); - if (param.name.kind === 80 /* Identifier */) { - return preserveJsDoc( - factory2.createPropertyDeclaration( - ensureModifiers(param), - param.name, - param.questionToken, - ensureType(param, param.type), - ensureNoInitializer(param) - ), - param - ); - } else { - return walkBindingPattern(param.name); - } - function walkBindingPattern(pattern) { - let elems; - for (const elem of pattern.elements) { - if (isOmittedExpression(elem)) - continue; - if (isBindingPattern(elem.name)) { - elems = concatenate(elems, walkBindingPattern(elem.name)); - } - elems = elems || []; - elems.push(factory2.createPropertyDeclaration( - ensureModifiers(param), - elem.name, - /*questionOrExclamationToken*/ - void 0, - ensureType( - elem, - /*type*/ - void 0 - ), - /*initializer*/ - void 0 - )); + case 262 /* FunctionDeclaration */: + { + const clean2 = cleanup(factory2.updateFunctionDeclaration(input, ensureModifiers(input), /*asteriskToken*/ + void 0, input.name, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type), /*body*/ + void 0)); + if (clean2 && resolver.isExpandoFunctionDeclaration(input) && shouldEmitFunctionProperties(input)) { + const props = resolver.getPropertiesOfContainerFunction(input); + const fakespace = parseNodeFactory.createModuleDeclaration( /*modifiers*/ + void 0, clean2.name || factory2.createIdentifier("_default"), factory2.createModuleBlock([]), 32 /* Namespace */); + + setParent(fakespace, enclosingDeclaration); + fakespace.locals = createSymbolTable(props); + fakespace.symbol = props[0].parent; + const exportMappings = []; + let declarations = mapDefined(props, p => { + if (!isExpandoPropertyDeclaration(p.valueDeclaration)) { + return void 0; } - return elems; + const nameStr = unescapeLeadingUnderscores(p.escapedName); + if (!isIdentifierText(nameStr, 99 /* ESNext */)) { + return void 0; + } + getSymbolAccessibilityDiagnostic = createGetSymbolAccessibilityDiagnosticForNode(p.valueDeclaration); + const type = resolver.createTypeOfDeclaration(p.valueDeclaration, fakespace, declarationEmitNodeBuilderFlags, symbolTracker); + getSymbolAccessibilityDiagnostic = oldDiag; + const isNonContextualKeywordName = isStringANonContextualKeyword(nameStr); + const name = isNonContextualKeywordName ? factory2.getGeneratedNameForNode(p.valueDeclaration) : factory2.createIdentifier(nameStr); + if (isNonContextualKeywordName) { + exportMappings.push([name, nameStr]); + } + const varDecl = factory2.createVariableDeclaration(name, /*exclamationToken*/ + void 0, type, /*initializer*/ + void 0); + return factory2.createVariableStatement(isNonContextualKeywordName ? void 0 : [factory2.createToken(95 /* ExportKeyword */)], factory2.createVariableDeclarationList([varDecl])); + }); + if (!exportMappings.length) { + declarations = mapDefined(declarations, declaration => factory2.replaceModifiers(declaration, 0 /* None */)); + } else { + declarations.push(factory2.createExportDeclaration( /*modifiers*/ + void 0, /*isTypeOnly*/ + false, factory2.createNamedExports(map(exportMappings, ([gen, exp]) => { + return factory2.createExportSpecifier( /*isTypeOnly*/ + false, gen, exp); + })))); } - })); - getSymbolAccessibilityDiagnostic = oldDiag2; - } - const hasPrivateIdentifier = some(input.members, (member) => !!member.name && isPrivateIdentifier(member.name)); - const privateIdentifier = hasPrivateIdentifier ? [ - factory2.createPropertyDeclaration( - /*modifiers*/ - void 0, - factory2.createPrivateIdentifier("#private"), - /*questionOrExclamationToken*/ - void 0, - /*type*/ - void 0, - /*initializer*/ - void 0 - ) - ] : void 0; - const memberNodes = concatenate(concatenate(privateIdentifier, parameterProperties), visitNodes2(input.members, visitDeclarationSubtree, isClassElement)); - const members = factory2.createNodeArray(memberNodes); - const extendsClause = getEffectiveBaseTypeNode(input); - if (extendsClause && !isEntityNameExpression(extendsClause.expression) && extendsClause.expression.kind !== 106 /* NullKeyword */) { - const oldId = input.name ? unescapeLeadingUnderscores(input.name.escapedText) : "default"; - const newId = factory2.createUniqueName(`${oldId}_base`, 16 /* Optimistic */); - getSymbolAccessibilityDiagnostic = () => ({ - diagnosticMessage: Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1, - errorNode: extendsClause, - typeName: input.name - }); - const varDecl = factory2.createVariableDeclaration( - newId, - /*exclamationToken*/ - void 0, - resolver.createTypeOfExpression(extendsClause.expression, input, declarationEmitNodeBuilderFlags, symbolTracker), - /*initializer*/ - void 0 - ); - const statement = factory2.createVariableStatement(needsDeclare ? [factory2.createModifier(138 /* DeclareKeyword */)] : [], factory2.createVariableDeclarationList([varDecl], 2 /* Const */)); - const heritageClauses = factory2.createNodeArray(map(input.heritageClauses, (clause) => { - if (clause.token === 96 /* ExtendsKeyword */) { - const oldDiag2 = getSymbolAccessibilityDiagnostic; - getSymbolAccessibilityDiagnostic = createGetSymbolAccessibilityDiagnosticForNode(clause.types[0]); - const newClause = factory2.updateHeritageClause(clause, map(clause.types, (t) => factory2.updateExpressionWithTypeArguments(t, newId, visitNodes2(t.typeArguments, visitDeclarationSubtree, isTypeNode)))); - getSymbolAccessibilityDiagnostic = oldDiag2; - return newClause; + const namespaceDecl = factory2.createModuleDeclaration(ensureModifiers(input), input.name, factory2.createModuleBlock(declarations), 32 /* Namespace */); + if (!hasEffectiveModifier(clean2, 2048 /* Default */)) { + return [clean2, namespaceDecl]; } - return factory2.updateHeritageClause(clause, visitNodes2(factory2.createNodeArray(filter(clause.types, (t) => isEntityNameExpression(t.expression) || t.expression.kind === 106 /* NullKeyword */)), visitDeclarationSubtree, isExpressionWithTypeArguments)); - })); - return [ - statement, - cleanup(factory2.updateClassDeclaration( - input, - modifiers, - input.name, - typeParameters, - heritageClauses, - members - )) - ]; - } else { - const heritageClauses = transformHeritageClauses(input.heritageClauses); - return cleanup(factory2.updateClassDeclaration( - input, - modifiers, - input.name, - typeParameters, - heritageClauses, - members - )); + const modifiers = factory2.createModifiersFromModifierFlags(getEffectiveModifierFlags(clean2) & ~2080 /* ExportDefault */ | 128 /* Ambient */); + const cleanDeclaration = factory2.updateFunctionDeclaration(clean2, modifiers, /*asteriskToken*/ + void 0, clean2.name, clean2.typeParameters, clean2.parameters, clean2.type, /*body*/ + void 0); + const namespaceDeclaration = factory2.updateModuleDeclaration(namespaceDecl, modifiers, namespaceDecl.name, namespaceDecl.body); + const exportDefaultDeclaration = factory2.createExportAssignment( /*modifiers*/ + void 0, /*isExportEquals*/ + false, namespaceDecl.name); + if (isSourceFile(input.parent)) { + resultHasExternalModuleIndicator = true; + } + resultHasScopeMarker = true; + return [cleanDeclaration, namespaceDeclaration, exportDefaultDeclaration]; + } else { + return clean2; + } } - } - case 243 /* VariableStatement */: { - return cleanup(transformVariableStatement(input)); - } - case 266 /* EnumDeclaration */: { - return cleanup(factory2.updateEnumDeclaration( - input, - factory2.createNodeArray(ensureModifiers(input)), - input.name, - factory2.createNodeArray(mapDefined(input.members, (m) => { - if (shouldStripInternal(m)) - return; + case 267 /* ModuleDeclaration */: + { + needsDeclare = false; + const inner = input.body; + if (inner && inner.kind === 268 /* ModuleBlock */) { + const oldNeedsScopeFix = needsScopeFixMarker; + const oldHasScopeFix = resultHasScopeMarker; + resultHasScopeMarker = false; + needsScopeFixMarker = false; + const statements = visitNodes2(inner.statements, visitDeclarationStatements, isStatement); + let lateStatements = transformAndReplaceLatePaintedStatements(statements); + if (input.flags & 33554432 /* Ambient */) { + needsScopeFixMarker = false; + } + if (!isGlobalScopeAugmentation(input) && !hasScopeMarker2(lateStatements) && !resultHasScopeMarker) { + if (needsScopeFixMarker) { + lateStatements = factory2.createNodeArray([...lateStatements, createEmptyExports(factory2)]); + } else { + lateStatements = visitNodes2(lateStatements, stripExportModifiers, isStatement); + } + } + const body = factory2.updateModuleBlock(inner, lateStatements); + needsDeclare = previousNeedsDeclare; + needsScopeFixMarker = oldNeedsScopeFix; + resultHasScopeMarker = oldHasScopeFix; + const mods = ensureModifiers(input); + return cleanup(updateModuleDeclarationAndKeyword(input, mods, isExternalModuleAugmentation(input) ? rewriteModuleSpecifier(input, input.name) : input.name, body)); + } else { + needsDeclare = previousNeedsDeclare; + const mods = ensureModifiers(input); + needsDeclare = false; + visitNode(inner, visitDeclarationStatements); + const id = getOriginalNodeId(inner); + const body = lateStatementReplacementMap.get(id); + lateStatementReplacementMap.delete(id); + return cleanup(updateModuleDeclarationAndKeyword(input, mods, input.name, body)); + } + } + case 263 /* ClassDeclaration */: + { + errorNameNode = input.name; + errorFallbackNode = input; + const modifiers = factory2.createNodeArray(ensureModifiers(input)); + const typeParameters = ensureTypeParams(input, input.typeParameters); + const ctor = getFirstConstructorWithBody(input); + let parameterProperties; + if (ctor) { + const oldDiag2 = getSymbolAccessibilityDiagnostic; + parameterProperties = compact(flatMap(ctor.parameters, param => { + if (!hasSyntacticModifier(param, 31 /* ParameterPropertyModifier */) || shouldStripInternal(param)) return; + getSymbolAccessibilityDiagnostic = createGetSymbolAccessibilityDiagnosticForNode(param); + if (param.name.kind === 80 /* Identifier */) { + return preserveJsDoc(factory2.createPropertyDeclaration(ensureModifiers(param), param.name, param.questionToken, ensureType(param, param.type), ensureNoInitializer(param)), param); + } else { + return walkBindingPattern(param.name); + } + function walkBindingPattern(pattern) { + let elems; + for (const elem of pattern.elements) { + if (isOmittedExpression(elem)) continue; + if (isBindingPattern(elem.name)) { + elems = concatenate(elems, walkBindingPattern(elem.name)); + } + elems = elems || []; + elems.push(factory2.createPropertyDeclaration(ensureModifiers(param), elem.name, /*questionOrExclamationToken*/ + void 0, ensureType(elem, /*type*/ + void 0), /*initializer*/ + void 0)); + } + return elems; + } + })); + getSymbolAccessibilityDiagnostic = oldDiag2; + } + const hasPrivateIdentifier = some(input.members, member => !!member.name && isPrivateIdentifier(member.name)); + const privateIdentifier = hasPrivateIdentifier ? [factory2.createPropertyDeclaration( /*modifiers*/ + void 0, factory2.createPrivateIdentifier("#private"), /*questionOrExclamationToken*/ + void 0, /*type*/ + void 0, /*initializer*/ + void 0)] : void 0; + const memberNodes = concatenate(concatenate(privateIdentifier, parameterProperties), visitNodes2(input.members, visitDeclarationSubtree, isClassElement)); + const members = factory2.createNodeArray(memberNodes); + const extendsClause = getEffectiveBaseTypeNode(input); + if (extendsClause && !isEntityNameExpression(extendsClause.expression) && extendsClause.expression.kind !== 106 /* NullKeyword */) { + const oldId = input.name ? unescapeLeadingUnderscores(input.name.escapedText) : "default"; + const newId = factory2.createUniqueName(`${oldId}_base`, 16 /* Optimistic */); + getSymbolAccessibilityDiagnostic = () => ({ + diagnosticMessage: Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1, + errorNode: extendsClause, + typeName: input.name + }); + const varDecl = factory2.createVariableDeclaration(newId, /*exclamationToken*/ + void 0, resolver.createTypeOfExpression(extendsClause.expression, input, declarationEmitNodeBuilderFlags, symbolTracker), /*initializer*/ + void 0); + const statement = factory2.createVariableStatement(needsDeclare ? [factory2.createModifier(138 /* DeclareKeyword */)] : [], factory2.createVariableDeclarationList([varDecl], 2 /* Const */)); + const heritageClauses = factory2.createNodeArray(map(input.heritageClauses, clause => { + if (clause.token === 96 /* ExtendsKeyword */) { + const oldDiag2 = getSymbolAccessibilityDiagnostic; + getSymbolAccessibilityDiagnostic = createGetSymbolAccessibilityDiagnosticForNode(clause.types[0]); + const newClause = factory2.updateHeritageClause(clause, map(clause.types, t => factory2.updateExpressionWithTypeArguments(t, newId, visitNodes2(t.typeArguments, visitDeclarationSubtree, isTypeNode)))); + getSymbolAccessibilityDiagnostic = oldDiag2; + return newClause; + } + return factory2.updateHeritageClause(clause, visitNodes2(factory2.createNodeArray(filter(clause.types, t => isEntityNameExpression(t.expression) || t.expression.kind === 106 /* NullKeyword */)), visitDeclarationSubtree, isExpressionWithTypeArguments)); + })); + return [statement, cleanup(factory2.updateClassDeclaration(input, modifiers, input.name, typeParameters, heritageClauses, members))]; + } else { + const heritageClauses = transformHeritageClauses(input.heritageClauses); + return cleanup(factory2.updateClassDeclaration(input, modifiers, input.name, typeParameters, heritageClauses, members)); + } + } + case 243 /* VariableStatement */: + { + return cleanup(transformVariableStatement(input)); + } + case 266 /* EnumDeclaration */: + { + return cleanup(factory2.updateEnumDeclaration(input, factory2.createNodeArray(ensureModifiers(input)), input.name, factory2.createNodeArray(mapDefined(input.members, m => { + if (shouldStripInternal(m)) return; const constValue = resolver.getConstantValue(m); return preserveJsDoc(factory2.updateEnumMember(m, m.name, constValue !== void 0 ? typeof constValue === "string" ? factory2.createStringLiteral(constValue) : factory2.createNumericLiteral(constValue) : void 0), m); - })) - )); - } + })))); + } } return Debug.assertNever(input, `Unhandled top-level node in declaration emit: ${Debug.formatSyntaxKind(input.kind)}`); function cleanup(node) { @@ -111804,11 +98969,9 @@ ${lanes.join("\n")} } } 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)) { @@ -111822,30 +98985,21 @@ ${lanes.join("\n")} return factory2.updateVariableStatement(input, modifiers, declList); } function recreateBindingPattern(d) { - return flatten(mapDefined(d.elements, (e) => recreateBindingElement(e))); + return flatten(mapDefined(d.elements, e => recreateBindingElement(e))); } function recreateBindingElement(e) { if (e.kind === 232 /* OmittedExpression */) { return; } if (e.name) { - if (!getBindingNameVisible(e)) - return; + if (!getBindingNameVisible(e)) return; if (isBindingPattern(e.name)) { return recreateBindingPattern(e.name); } else { - return factory2.createVariableDeclaration( - e.name, - /*exclamationToken*/ - void 0, - ensureType( - e, - /*type*/ - void 0 - ), - /*initializer*/ - void 0 - ); + return factory2.createVariableDeclaration(e.name, /*exclamationToken*/ + void 0, ensureType(e, /*type*/ + void 0), /*initializer*/ + void 0); } } } @@ -111878,7 +99032,7 @@ ${lanes.join("\n")} const currentFlags = getEffectiveModifierFlags(node); const newFlags = ensureModifierFlags(node); if (currentFlags === newFlags) { - return visitArray(node.modifiers, (n) => tryCast(n, isModifier), isModifier); + return visitArray(node.modifiers, n => tryCast(n, isModifier), isModifier); } return factory2.createModifiersFromModifierFlags(newFlags); } @@ -111890,6 +99044,7 @@ ${lanes.join("\n")} mask2 ^= 128 /* Ambient */; additions = 0 /* None */; } + return maskModifierFlags(node, mask2, additions); } function getTypeAnnotationFromAllAccessorDeclarations(node, accessors) { @@ -111905,19 +99060,9 @@ ${lanes.join("\n")} return accessorType; } function transformHeritageClauses(nodes) { - return factory2.createNodeArray(filter( - map(nodes, (clause) => factory2.updateHeritageClause( - clause, - visitNodes2( - factory2.createNodeArray(filter(clause.types, (t) => { - return isEntityNameExpression(t.expression) || clause.token === 96 /* ExtendsKeyword */ && t.expression.kind === 106 /* NullKeyword */; - })), - visitDeclarationSubtree, - isExpressionWithTypeArguments - ) - )), - (clause) => clause.types && !!clause.types.length - )); + return factory2.createNodeArray(filter(map(nodes, clause => factory2.updateHeritageClause(clause, visitNodes2(factory2.createNodeArray(filter(clause.types, t => { + return isEntityNameExpression(t.expression) || clause.token === 96 /* ExtendsKeyword */ && t.expression.kind === 106 /* NullKeyword */; + })), visitDeclarationSubtree, isExpressionWithTypeArguments))), clause => clause.types && !!clause.types.length)); } } function isAlwaysType(node) { @@ -111934,9 +99079,11 @@ ${lanes.join("\n")} if (flags & 2048 /* Default */ && !(flags & 32 /* Export */)) { flags ^= 32 /* Export */; } + if (flags & 2048 /* Default */ && flags & 128 /* Ambient */) { flags ^= 128 /* Ambient */; } + return flags; } function getTypeAnnotationFromAccessor(accessor) { @@ -112000,6 +99147,7 @@ ${lanes.join("\n")} var init_declarations = __esm({ "src/compiler/transformers/declarations.ts"() { "use strict"; + init_ts2(); init_ts_moduleSpecifiers(); declarationEmitNodeBuilderFlags = 1024 /* MultilineObjectLiterals */ | 2048 /* WriteClassExpressionAsTypeLiteral */ | 4096 /* UseTypeOfFunction */ | 8 /* UseStructuralFallback */ | 524288 /* AllowEmptyTuple */ | 4 /* GenerateNamesForShadowedTypeParams */ | 1 /* NoTruncation */; @@ -112030,8 +99178,7 @@ ${lanes.join("\n")} }; } 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); @@ -112087,10 +99234,10 @@ ${lanes.join("\n")} return transformers; } function wrapCustomTransformer(transformer) { - return (node) => isBundle(node) ? transformer.transformBundle(node) : transformer.transformSourceFile(node); + return node => isBundle(node) ? transformer.transformBundle(node) : transformer.transformSourceFile(node); } function wrapCustomTransformerFactory(transformer, handleDefault) { - return (context) => { + return context => { const customTransformer = transformer(context); return typeof customTransformer === "function" ? handleDefault(context, customTransformer) : wrapCustomTransformer(customTransformer); }; @@ -112178,8 +99325,8 @@ ${lanes.join("\n")} disposeEmitNodes(getSourceFileOfNode(getParseTreeNode(node))); } mark("beforeTransform"); - const transformersWithContext = transformers.map((t) => t(context)); - const transformation = (node) => { + const transformersWithContext = transformers.map(t => t(context)); + const transformation = node => { for (const transform2 of transformersWithContext) { node = transform2(node); } @@ -112188,7 +99335,13 @@ ${lanes.join("\n")} state = 1 /* Initialized */; const transformed = []; for (const node of nodes) { - (_a = tracing) == null ? void 0 : _a.push(tracing.Phase.Emit, "transformNodes", node.kind === 312 /* SourceFile */ ? { path: node.path } : { kind: node.kind, pos: node.pos, end: node.end }); + (_a = tracing) == null ? void 0 : _a.push(tracing.Phase.Emit, "transformNodes", node.kind === 312 /* SourceFile */ ? { + path: node.path + } : { + kind: node.kind, + pos: node.pos, + end: node.end + }); transformed.push((allowDtsFiles ? transformation : transformRoot)(node)); (_b = tracing) == null ? void 0 : _b.pop(); } @@ -112210,6 +99363,7 @@ ${lanes.join("\n")} Debug.assert(state < 2 /* Completed */, "Cannot modify the transformation context after transformation has completed."); enabledSyntaxKindFeatures[kind] |= 1 /* Substitution */; } + function isSubstitutionEnabled(node) { return (enabledSyntaxKindFeatures[node.kind] & 1 /* Substitution */) !== 0 && (getEmitFlags(node) & 8 /* NoSubstitution */) === 0; } @@ -112221,6 +99375,7 @@ ${lanes.join("\n")} Debug.assert(state < 2 /* Completed */, "Cannot modify the transformation context after transformation has completed."); enabledSyntaxKindFeatures[kind] |= 2 /* EmitNotifications */; } + function isEmitNotificationEnabled(node) { return (enabledSyntaxKindFeatures[node.kind] & 2 /* EmitNotifications */) !== 0 || (getEmitFlags(node) & 4 /* AdviseOnEmitNode */) !== 0; } @@ -112247,6 +99402,7 @@ ${lanes.join("\n")} lexicalEnvironmentFlags |= 2 /* VariablesHoistedInParameters */; } } + function hoistFunctionDeclaration(func) { Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization."); Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed."); @@ -112281,6 +99437,7 @@ ${lanes.join("\n")} lexicalEnvironmentStatements = void 0; lexicalEnvironmentFlags = 0 /* None */; } + function suspendLexicalEnvironment() { Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization."); Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed."); @@ -112303,11 +99460,8 @@ ${lanes.join("\n")} statements = [...lexicalEnvironmentFunctionDeclarations]; } if (lexicalEnvironmentVariableDeclarations) { - const statement = factory2.createVariableStatement( - /*modifiers*/ - void 0, - factory2.createVariableDeclarationList(lexicalEnvironmentVariableDeclarations) - ); + const statement = factory2.createVariableStatement( /*modifiers*/ + void 0, factory2.createVariableDeclarationList(lexicalEnvironmentVariableDeclarations)); setEmitFlags(statement, 2097152 /* CustomPrologue */); if (!statements) { statements = [statement]; @@ -112352,16 +99506,8 @@ ${lanes.join("\n")} function endBlockScope() { Debug.assert(state > 0 /* Uninitialized */, "Cannot end a block scope during initialization."); Debug.assert(state < 2 /* Completed */, "Cannot end a block scope after transformation has completed."); - const statements = some(blockScopedVariableDeclarations) ? [ - factory2.createVariableStatement( - /*modifiers*/ - void 0, - factory2.createVariableDeclarationList( - blockScopedVariableDeclarations.map((identifier) => factory2.createVariableDeclaration(identifier)), - 1 /* Let */ - ) - ) - ] : void 0; + const statements = some(blockScopedVariableDeclarations) ? [factory2.createVariableStatement( /*modifiers*/ + void 0, factory2.createVariableDeclarationList(blockScopedVariableDeclarations.map(identifier => factory2.createVariableDeclaration(identifier)), 1 /* Let */))] : void 0; blockScopeStackOffset--; blockScopedVariableDeclarations = blockScopedVariableDeclarationsStack[blockScopeStackOffset]; if (blockScopeStackOffset === 0) { @@ -112407,13 +99553,18 @@ ${lanes.join("\n")} } } } + var noTransformers, nullTransformationContext; var init_transformer = __esm({ "src/compiler/transformer.ts"() { "use strict"; + init_ts2(); init_ts_performance(); - noTransformers = { scriptTransformers: emptyArray, declarationTransformers: emptyArray }; + noTransformers = { + scriptTransformers: emptyArray, + declarationTransformers: emptyArray + }; nullTransformationContext = { factory, // eslint-disable-line object-shorthand @@ -112450,6 +99601,7 @@ ${lanes.join("\n")} function isBuildInfoFile(file) { return fileExtensionIs(file, ".tsbuildinfo" /* TsBuildInfo */); } + function forEachEmittedFile(host, action, sourceFilesOrTargetSourceFile, forceDtsEmit = false, onlyBuildInfo, includeBuildInfo) { const sourceFiles = isArray(sourceFilesOrTargetSourceFile) ? sourceFilesOrTargetSourceFile : getSourceFilesToEmit(host, sourceFilesOrTargetSourceFile, forceDtsEmit); const options = host.getCompilerOptions(); @@ -112473,38 +99625,30 @@ ${lanes.join("\n")} } 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 = outFile(options); 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, - configFileExtensionLess, - /*ignoreCase*/ - true - )) : combinePaths(options.outDir, getBaseFileName(configFileExtensionLess)) : configFileExtensionLess; + buildInfoExtensionLess = options.outDir ? options.rootDir ? resolvePath(options.outDir, getRelativePathFromDirectory(options.rootDir, configFileExtensionLess, /*ignoreCase*/ + true)) : combinePaths(options.outDir, getBaseFileName(configFileExtensionLess)) : configFileExtensionLess; } return buildInfoExtensionLess + ".tsbuildinfo" /* TsBuildInfo */; } + function getOutputPathsForBundle(options, forceDtsPaths) { const outPath = outFile(options); const jsFilePath = options.emitDeclarationOnly ? void 0 : outPath; @@ -112512,7 +99656,13 @@ ${lanes.join("\n")} const declarationFilePath = forceDtsPaths || getEmitDeclarations(options) ? removeFileExtension(outPath) + ".d.ts" /* Dts */ : void 0; const declarationMapPath = declarationFilePath && getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : void 0; const buildInfoPath = getTsBuildInfoEmitOutputFilePath(options); - return { jsFilePath, sourceMapFilePath, declarationFilePath, declarationMapPath, buildInfoPath }; + return { + jsFilePath, + sourceMapFilePath, + declarationFilePath, + declarationMapPath, + buildInfoPath + }; } function getOutputPathsFor(sourceFile, host, forceDtsPaths) { const options = host.getCompilerOptions(); @@ -112526,7 +99676,13 @@ ${lanes.join("\n")} const sourceMapFilePath = !jsFilePath || isJsonSourceFile(sourceFile) ? void 0 : getSourceMapFilePath(jsFilePath, options); const declarationFilePath = forceDtsPaths || getEmitDeclarations(options) && !isJsonFile ? getDeclarationEmitOutputFilePath(sourceFile.fileName, host) : void 0; const declarationMapPath = declarationFilePath && getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : void 0; - return { jsFilePath, sourceMapFilePath, declarationFilePath, declarationMapPath, buildInfoPath: void 0 }; + return { + jsFilePath, + sourceMapFilePath, + declarationFilePath, + declarationMapPath, + buildInfoPath: void 0 + }; } } function getSourceMapFilePath(jsFilePath, options) { @@ -112535,31 +99691,25 @@ ${lanes.join("\n")} function getOutputExtension(fileName, options) { return fileExtensionIs(fileName, ".json" /* Json */) ? ".json" /* Json */ : options.jsx === 1 /* Preserve */ && fileExtensionIsOneOf(fileName, [".jsx" /* Jsx */, ".tsx" /* Tsx */]) ? ".jsx" /* Jsx */ : fileExtensionIsOneOf(fileName, [".mts" /* Mts */, ".mjs" /* Mjs */]) ? ".mjs" /* Mjs */ : fileExtensionIsOneOf(fileName, [".cts" /* Cts */, ".cjs" /* Cjs */]) ? ".cjs" /* Cjs */ : ".js" /* Js */; } + function getOutputPathWithoutChangingExt(inputFileName, configFile, ignoreCase, outputDir, getCommonSourceDirectory2) { - return outputDir ? resolvePath( - outputDir, - getRelativePathFromDirectory(getCommonSourceDirectory2 ? getCommonSourceDirectory2() : getCommonSourceDirectoryOfConfig(configFile, ignoreCase), inputFileName, ignoreCase) - ) : inputFileName; + return outputDir ? resolvePath(outputDir, getRelativePathFromDirectory(getCommonSourceDirectory2 ? getCommonSourceDirectory2() : getCommonSourceDirectoryOfConfig(configFile, ignoreCase), inputFileName, ignoreCase)) : inputFileName; } function getOutputDeclarationFileName(inputFileName, configFile, ignoreCase, getCommonSourceDirectory2) { - return changeExtension( - getOutputPathWithoutChangingExt(inputFileName, configFile, ignoreCase, configFile.options.declarationDir || configFile.options.outDir, getCommonSourceDirectory2), - getDeclarationEmitExtensionForPath(inputFileName) - ); + return changeExtension(getOutputPathWithoutChangingExt(inputFileName, configFile, ignoreCase, configFile.options.declarationDir || configFile.options.outDir, getCommonSourceDirectory2), getDeclarationEmitExtensionForPath(inputFileName)); } function getOutputJSFileName(inputFileName, configFile, ignoreCase, getCommonSourceDirectory2) { - if (configFile.options.emitDeclarationOnly) - return void 0; + if (configFile.options.emitDeclarationOnly) return void 0; const isJsonFile = fileExtensionIs(inputFileName, ".json" /* Json */); - const outputFileName = changeExtension( - getOutputPathWithoutChangingExt(inputFileName, configFile, ignoreCase, configFile.options.outDir, getCommonSourceDirectory2), - getOutputExtension(inputFileName, configFile.options) - ); + const outputFileName = changeExtension(getOutputPathWithoutChangingExt(inputFileName, configFile, ignoreCase, configFile.options.outDir, getCommonSourceDirectory2), getOutputExtension(inputFileName, configFile.options)); return !isJsonFile || comparePaths(inputFileName, outputFileName, Debug.checkDefined(configFile.options.configFilePath), ignoreCase) !== 0 /* EqualTo */ ? outputFileName : void 0; } function createAddOutput() { let outputs; - return { addOutput, getOutputs }; + return { + addOutput, + getOutputs + }; function addOutput(path) { if (path) { (outputs || (outputs = [])).push(path); @@ -112570,11 +99720,14 @@ ${lanes.join("\n")} } } function getSingleOutputFileNames(configFile, addOutput) { - const { jsFilePath, sourceMapFilePath, declarationFilePath, declarationMapPath, buildInfoPath } = getOutputPathsForBundle( - configFile.options, - /*forceDtsPaths*/ - false - ); + const { + jsFilePath, + sourceMapFilePath, + declarationFilePath, + declarationMapPath, + buildInfoPath + } = getOutputPathsForBundle(configFile.options, /*forceDtsPaths*/ + false); addOutput(jsFilePath); addOutput(sourceMapFilePath); addOutput(declarationFilePath); @@ -112582,12 +99735,10 @@ ${lanes.join("\n")} 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`); } @@ -112615,16 +99766,17 @@ ${lanes.join("\n")} } return commonSourceDirectory; } - function getCommonSourceDirectoryOfConfig({ options, fileNames }, ignoreCase) { - return getCommonSourceDirectory( - options, - () => filter(fileNames, (file) => !(options.noEmitForJsFiles && fileExtensionIsOneOf(file, supportedJSExtensionsFlat)) && !isDeclarationFileName(file)), - getDirectoryPath(normalizeSlashes(Debug.checkDefined(options.configFilePath))), - createGetCanonicalFileName(!ignoreCase) - ); + function getCommonSourceDirectoryOfConfig({ + options, + fileNames + }, ignoreCase) { + return getCommonSourceDirectory(options, () => filter(fileNames, file => !(options.noEmitForJsFiles && fileExtensionIsOneOf(file, supportedJSExtensionsFlat)) && !isDeclarationFileName(file)), getDirectoryPath(normalizeSlashes(Debug.checkDefined(options.configFilePath))), createGetCanonicalFileName(!ignoreCase)); } function getAllProjectOutputs(configFile, ignoreCase) { - const { addOutput, getOutputs } = createAddOutput(); + const { + addOutput, + getOutputs + } = createAddOutput(); if (outFile(configFile.options)) { getSingleOutputFileNames(configFile, addOutput); } else { @@ -112639,7 +99791,10 @@ ${lanes.join("\n")} function getOutputFileNames(commandLine, inputFileName, ignoreCase) { inputFileName = normalizePath(inputFileName); Debug.assert(contains(commandLine.fileNames, inputFileName), `Expected fileName to be present in command line`); - const { addOutput, getOutputs } = createAddOutput(); + const { + addOutput, + getOutputs + } = createAddOutput(); if (outFile(commandLine.options)) { getSingleOutputFileNames(commandLine, addOutput); } else { @@ -112649,50 +99804,45 @@ ${lanes.join("\n")} } function getFirstProjectOutput(configFile, ignoreCase) { if (outFile(configFile.options)) { - const { jsFilePath, declarationFilePath } = getOutputPathsForBundle( - configFile.options, - /*forceDtsPaths*/ - false - ); + const { + jsFilePath, + declarationFilePath + } = getOutputPathsForBundle(configFile.options, /*forceDtsPaths*/ + false); return Debug.checkDefined(jsFilePath || declarationFilePath, `project ${configFile.options.configFilePath} expected to have at least one output`); } const getCommonSourceDirectory2 = memoize(() => getCommonSourceDirectoryOfConfig(configFile, ignoreCase)); 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 emitFiles(resolver, host, targetSourceFile, { scriptTransformers, declarationTransformers }, emitOnly, onlyBuildInfo, forceDtsEmit) { + function emitFiles(resolver, host, targetSourceFile, { + scriptTransformers, + declarationTransformers + }, emitOnly, onlyBuildInfo, forceDtsEmit) { var compilerOptions = host.getCompilerOptions(); var sourceMapDataList = compilerOptions.sourceMap || compilerOptions.inlineSourceMap || getAreDeclarationMapsEnabled(compilerOptions) ? [] : void 0; var emittedFilesList = compilerOptions.listEmittedFiles ? [] : void 0; var emitterDiagnostics = createDiagnosticCollection(); var newLine = getNewLineCharacter(compilerOptions); var writer = createTextWriter(newLine); - var { enter, exit } = createTimer("printTime", "beforePrint", "afterPrint"); + var { + enter, + exit + } = createTimer("printTime", "beforePrint", "afterPrint"); var bundleBuildInfo; var emitSkipped = false; enter(); - forEachEmittedFile( - host, - emitSourceFileOrBundle, - getSourceFilesToEmit(host, targetSourceFile, forceDtsEmit), - forceDtsEmit, - onlyBuildInfo, - !targetSourceFile - ); + forEachEmittedFile(host, emitSourceFileOrBundle, getSourceFilesToEmit(host, targetSourceFile, forceDtsEmit), forceDtsEmit, onlyBuildInfo, !targetSourceFile); exit(); return { emitSkipped, @@ -112700,23 +99850,35 @@ ${lanes.join("\n")} emittedFiles: emittedFilesList, sourceMaps: sourceMapDataList }; - function emitSourceFileOrBundle({ jsFilePath, sourceMapFilePath, declarationFilePath, declarationMapPath, buildInfoPath }, sourceFileOrBundle) { + function emitSourceFileOrBundle({ + jsFilePath, + sourceMapFilePath, + declarationFilePath, + declarationMapPath, + buildInfoPath + }, sourceFileOrBundle) { var _a, _b, _c, _d, _e, _f; let buildInfoDirectory; if (buildInfoPath && sourceFileOrBundle && isBundle(sourceFileOrBundle)) { buildInfoDirectory = getDirectoryPath(getNormalizedAbsolutePath(buildInfoPath, host.getCurrentDirectory())); bundleBuildInfo = { commonSourceDirectory: relativeToBuildInfo(host.getCommonSourceDirectory()), - sourceFiles: sourceFileOrBundle.sourceFiles.map((file) => relativeToBuildInfo(getNormalizedAbsolutePath(file.fileName, host.getCurrentDirectory()))) + sourceFiles: sourceFileOrBundle.sourceFiles.map(file => relativeToBuildInfo(getNormalizedAbsolutePath(file.fileName, host.getCurrentDirectory()))) }; } - (_a = tracing) == null ? void 0 : _a.push(tracing.Phase.Emit, "emitJsFileOrBundle", { jsFilePath }); + (_a = tracing) == null ? void 0 : _a.push(tracing.Phase.Emit, "emitJsFileOrBundle", { + jsFilePath + }); emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath, relativeToBuildInfo); (_b = tracing) == null ? void 0 : _b.pop(); - (_c = tracing) == null ? void 0 : _c.push(tracing.Phase.Emit, "emitDeclarationFileOrBundle", { declarationFilePath }); + (_c = tracing) == null ? void 0 : _c.push(tracing.Phase.Emit, "emitDeclarationFileOrBundle", { + declarationFilePath + }); emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath, relativeToBuildInfo); (_d = tracing) == null ? void 0 : _d.pop(); - (_e = tracing) == null ? void 0 : _e.push(tracing.Phase.Emit, "emitBuildInfo", { buildInfoPath }); + (_e = tracing) == null ? void 0 : _e.push(tracing.Phase.Emit, "emitBuildInfo", { + buildInfoPath + }); emitBuildInfo(bundleBuildInfo, buildInfoPath); (_f = tracing) == null ? void 0 : _f.pop(); if (!emitSkipped && emittedFilesList) { @@ -112745,28 +99907,18 @@ ${lanes.join("\n")} } } function emitBuildInfo(bundle, buildInfoPath) { - if (!buildInfoPath || targetSourceFile || emitSkipped) - return; + if (!buildInfoPath || targetSourceFile || emitSkipped) return; if (host.isEmitBlocked(buildInfoPath)) { emitSkipped = true; return; } - const buildInfo = host.getBuildInfo(bundle) || createBuildInfo( - /*program*/ - void 0, - bundle - ); - writeFile( - host, - emitterDiagnostics, - buildInfoPath, - getBuildInfoText(buildInfo), - /*writeByteOrderMark*/ - false, - /*sourceFiles*/ - void 0, - { buildInfo } - ); + const buildInfo = host.getBuildInfo(bundle) || createBuildInfo( /*program*/ + void 0, bundle); + writeFile(host, emitterDiagnostics, buildInfoPath, getBuildInfoText(buildInfo), /*writeByteOrderMark*/ + false, /*sourceFiles*/ + void 0, { + buildInfo + }); } function emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath, relativeToBuildInfo) { if (!sourceFileOrBundle || emitOnly || !jsFilePath) { @@ -112776,16 +99928,8 @@ ${lanes.join("\n")} emitSkipped = true; return; } - const transform2 = transformNodes( - resolver, - host, - factory, - compilerOptions, - [sourceFileOrBundle], - scriptTransformers, - /*allowDtsFiles*/ - false - ); + const transform2 = transformNodes(resolver, host, factory, compilerOptions, [sourceFileOrBundle], scriptTransformers, /*allowDtsFiles*/ + false); const printerOptions = { removeComments: compilerOptions.removeComments, newLine: compilerOptions.newLine, @@ -112810,15 +99954,12 @@ ${lanes.join("\n")} Debug.assert(transform2.transformed.length === 1, "Should only see one output from the transform"); printSourceFileOrBundle(jsFilePath, sourceMapFilePath, transform2, printer, compilerOptions); transform2.dispose(); - if (bundleBuildInfo) - bundleBuildInfo.js = printer.bundleFileInfo; + if (bundleBuildInfo) bundleBuildInfo.js = printer.bundleFileInfo; } function emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath, relativeToBuildInfo) { - 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; @@ -112827,16 +99968,8 @@ ${lanes.join("\n")} if (emitOnly && !getEmitDeclarations(compilerOptions)) { filesForEmit.forEach(collectLinkedAliases); } - const declarationTransform = transformNodes( - resolver, - host, - factory, - compilerOptions, - inputListOrBundle, - declarationTransformers, - /*allowDtsFiles*/ - false - ); + const declarationTransform = transformNodes(resolver, host, factory, compilerOptions, inputListOrBundle, declarationTransformers, /*allowDtsFiles*/ + false); if (length(declarationTransform.diagnostics)) { for (const diagnostic of declarationTransform.diagnostics) { emitterDiagnostics.add(diagnostic); @@ -112869,40 +100002,28 @@ ${lanes.join("\n")} emitSkipped = emitSkipped || declBlocked; if (!declBlocked || forceDtsEmit) { Debug.assert(declarationTransform.transformed.length === 1, "Should only see one output from the decl transform"); - printSourceFileOrBundle( - declarationFilePath, - declarationMapPath, - declarationTransform, - declarationPrinter, - { - sourceMap: printerOptions.sourceMap, - sourceRoot: compilerOptions.sourceRoot, - mapRoot: compilerOptions.mapRoot, - extendedDiagnostics: compilerOptions.extendedDiagnostics - // Explicitly do not passthru either `inline` option - } - ); + printSourceFileOrBundle(declarationFilePath, declarationMapPath, declarationTransform, declarationPrinter, { + sourceMap: printerOptions.sourceMap, + sourceRoot: compilerOptions.sourceRoot, + mapRoot: compilerOptions.mapRoot, + extendedDiagnostics: compilerOptions.extendedDiagnostics + // Explicitly do not passthru either `inline` option + }); } + declarationTransform.dispose(); - if (bundleBuildInfo) - bundleBuildInfo.dts = declarationPrinter.bundleFileInfo; + if (bundleBuildInfo) bundleBuildInfo.dts = declarationPrinter.bundleFileInfo; } function collectLinkedAliases(node) { if (isExportAssignment(node)) { if (node.expression.kind === 80 /* Identifier */) { - resolver.collectLinkedAliases( - node.expression, - /*setVisibility*/ - true - ); + resolver.collectLinkedAliases(node.expression, /*setVisibility*/ + true); } return; } else if (isExportSpecifier(node)) { - resolver.collectLinkedAliases( - node.propertyName || node.name, - /*setVisibility*/ - true - ); + resolver.collectLinkedAliases(node.propertyName || node.name, /*setVisibility*/ + true); return; } forEachChild(node, collectLinkedAliases); @@ -112914,13 +100035,7 @@ ${lanes.join("\n")} const sourceFiles = bundle ? bundle.sourceFiles : [sourceFile]; let sourceMapGenerator; if (shouldEmitSourceMaps(mapOptions, sourceFileOrBundle)) { - sourceMapGenerator = createSourceMapGenerator( - host, - getBaseFileName(normalizeSlashes(jsFilePath)), - getSourceRoot(mapOptions), - getSourceMapDirectory(mapOptions, jsFilePath, sourceFile), - mapOptions - ); + sourceMapGenerator = createSourceMapGenerator(host, getBaseFileName(normalizeSlashes(jsFilePath)), getSourceRoot(mapOptions), getSourceMapDirectory(mapOptions, jsFilePath, sourceFile), mapOptions); } if (bundle) { printer.writeBundle(bundle, writer, sourceMapGenerator); @@ -112935,52 +100050,39 @@ ${lanes.join("\n")} sourceMap: sourceMapGenerator.toJSON() }); } - const sourceMappingURL = getSourceMappingURL( - mapOptions, - sourceMapGenerator, - jsFilePath, - sourceMapFilePath, - sourceFile - ); + const sourceMappingURL = getSourceMappingURL(mapOptions, sourceMapGenerator, jsFilePath, sourceMapFilePath, sourceFile); if (sourceMappingURL) { - if (!writer.isAtStartOfLine()) - writer.rawWrite(newLine); + if (!writer.isAtStartOfLine()) writer.rawWrite(newLine); sourceMapUrlPos = writer.getTextPos(); writer.writeComment(`//# ${"sourceMappingURL"}=${sourceMappingURL}`); } if (sourceMapFilePath) { const sourceMap = sourceMapGenerator.toString(); - writeFile( - host, - emitterDiagnostics, - sourceMapFilePath, - sourceMap, - /*writeByteOrderMark*/ - false, - sourceFiles - ); - if (printer.bundleFileInfo) - printer.bundleFileInfo.mapHash = computeSignature(sourceMap, host); + writeFile(host, emitterDiagnostics, sourceMapFilePath, sourceMap, /*writeByteOrderMark*/ + false, sourceFiles); + if (printer.bundleFileInfo) printer.bundleFileInfo.mapHash = computeSignature(sourceMap, host); } } else { writer.writeLine(); } const text = writer.getText(); - writeFile(host, emitterDiagnostics, jsFilePath, text, !!compilerOptions.emitBOM, sourceFiles, { sourceMapUrlPos, diagnostics: transform2.diagnostics }); - if (printer.bundleFileInfo) - printer.bundleFileInfo.hash = computeSignature(text, host); + writeFile(host, emitterDiagnostics, jsFilePath, text, !!compilerOptions.emitBOM, sourceFiles, { + sourceMapUrlPos, + diagnostics: transform2.diagnostics + }); + if (printer.bundleFileInfo) printer.bundleFileInfo.hash = computeSignature(text, host); writer.clear(); } function shouldEmitSourceMaps(mapOptions, sourceFileOrBundle) { return (mapOptions.sourceMap || mapOptions.inlineSourceMap) && (sourceFileOrBundle.kind !== 312 /* SourceFile */ || !fileExtensionIs(sourceFileOrBundle.fileName, ".json" /* Json */)); } + function getSourceRoot(mapOptions) { const sourceRoot = normalizeSlashes(mapOptions.sourceRoot || ""); 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) { @@ -113007,18 +100109,12 @@ ${lanes.join("\n")} } if (getRootLength(sourceMapDir) === 0) { sourceMapDir = combinePaths(host.getCommonSourceDirectory(), sourceMapDir); - return encodeURI( - getRelativePathToDirectoryOrUrl( - getDirectoryPath(normalizePath(filePath)), - // get the relative sourceMapDir path based on jsFilePath - combinePaths(sourceMapDir, sourceMapFile), - // this is where user expects to see sourceMap - host.getCurrentDirectory(), - host.getCanonicalFileName, - /*isAbsolutePathAnUrl*/ - true - ) - ); + return encodeURI(getRelativePathToDirectoryOrUrl(getDirectoryPath(normalizePath(filePath)), + // get the relative sourceMapDir path based on jsFilePath + combinePaths(sourceMapDir, sourceMapFile), + // this is where user expects to see sourceMap + host.getCurrentDirectory(), host.getCanonicalFileName, /*isAbsolutePathAnUrl*/ + true)); } else { return encodeURI(combinePaths(sourceMapDir, sourceMapFile)); } @@ -113027,7 +100123,11 @@ ${lanes.join("\n")} } } function createBuildInfo(program, bundle) { - return { bundle, program, version }; + return { + bundle, + program, + version + }; } function getBuildInfoText(buildInfo) { return JSON.stringify(buildInfo); @@ -113038,24 +100138,21 @@ ${lanes.join("\n")} function createSourceFilesFromBundleBuildInfo(bundle, buildInfoDirectory, host) { var _a; const jsBundle = Debug.checkDefined(bundle.js); - const prologueMap = ((_a = jsBundle.sources) == null ? void 0 : _a.prologues) && arrayToMap(jsBundle.sources.prologues, (prologueInfo) => prologueInfo.file); + const prologueMap = ((_a = jsBundle.sources) == null ? void 0 : _a.prologues) && arrayToMap(jsBundle.sources.prologues, prologueInfo => prologueInfo.file); return bundle.sourceFiles.map((fileName, index) => { + var _ref35, _ref36; const prologueInfo = prologueMap == null ? void 0 : prologueMap.get(index); - const statements = prologueInfo == null ? void 0 : prologueInfo.directives.map((directive) => { + const statements = prologueInfo == null ? void 0 : prologueInfo.directives.map(directive => { const literal = setTextRange(factory.createStringLiteral(directive.expression.text), directive.expression); const statement = setTextRange(factory.createExpressionStatement(literal), directive); setParent(literal, statement); return statement; }); const eofToken = factory.createToken(1 /* EndOfFileToken */); - const sourceFile = factory.createSourceFile(statements ?? [], eofToken, 0 /* None */); - sourceFile.fileName = getRelativePathFromDirectory( - host.getCurrentDirectory(), - getNormalizedAbsolutePath(fileName, buildInfoDirectory), - !host.useCaseSensitiveFileNames() - ); - sourceFile.text = (prologueInfo == null ? void 0 : prologueInfo.text) ?? ""; - setTextRangePosWidth(sourceFile, 0, (prologueInfo == null ? void 0 : prologueInfo.text.length) ?? 0); + const sourceFile = factory.createSourceFile(statements !== null && statements !== void 0 ? statements : [], eofToken, 0 /* None */); + sourceFile.fileName = getRelativePathFromDirectory(host.getCurrentDirectory(), getNormalizedAbsolutePath(fileName, buildInfoDirectory), !host.useCaseSensitiveFileNames()); + sourceFile.text = (_ref35 = prologueInfo == null ? void 0 : prologueInfo.text) !== null && _ref35 !== void 0 ? _ref35 : ""; + setTextRangePosWidth(sourceFile, 0, (_ref36 = prologueInfo == null ? void 0 : prologueInfo.text.length) !== null && _ref36 !== void 0 ? _ref36 : 0); setEachParent(sourceFile.statements, sourceFile); setTextRangePosWidth(eofToken, sourceFile.end, 0); setParent(eofToken, sourceFile); @@ -113064,13 +100161,8 @@ ${lanes.join("\n")} } function emitUsingBuildInfo(config, host, getCommandLine, customTransformers) { var _a, _b; - (_a = tracing) == null ? void 0 : _a.push( - tracing.Phase.Emit, - "emitUsingBuildInfo", - {}, - /*separateBeginAndEnd*/ - true - ); + (_a = tracing) == null ? void 0 : _a.push(tracing.Phase.Emit, "emitUsingBuildInfo", {}, /*separateBeginAndEnd*/ + true); mark("beforeEmit"); const result = emitUsingBuildInfoWorker(config, host, getCommandLine, customTransformers); mark("afterEmit"); @@ -113079,53 +100171,34 @@ ${lanes.join("\n")} return result; } function emitUsingBuildInfoWorker(config, host, getCommandLine, customTransformers) { - const { buildInfoPath, jsFilePath, sourceMapFilePath, declarationFilePath, declarationMapPath } = getOutputPathsForBundle( - config.options, - /*forceDtsPaths*/ - false - ); - const buildInfo = host.getBuildInfo(buildInfoPath, config.options.configFilePath); - if (!buildInfo) - return buildInfoPath; - if (!buildInfo.bundle || !buildInfo.bundle.js || declarationFilePath && !buildInfo.bundle.dts) - return buildInfoPath; - const jsFileText = host.readFile(Debug.checkDefined(jsFilePath)); - if (!jsFileText) - return jsFilePath; - if (computeSignature(jsFileText, host) !== buildInfo.bundle.js.hash) - return jsFilePath; - const sourceMapText = sourceMapFilePath && host.readFile(sourceMapFilePath); - if (sourceMapFilePath && !sourceMapText || config.options.inlineSourceMap) - return sourceMapFilePath || "inline sourcemap decoding"; - if (sourceMapFilePath && computeSignature(sourceMapText, host) !== buildInfo.bundle.js.mapHash) - return sourceMapFilePath; - const declarationText = declarationFilePath && host.readFile(declarationFilePath); - if (declarationFilePath && !declarationText) - return declarationFilePath; - if (declarationFilePath && computeSignature(declarationText, host) !== buildInfo.bundle.dts.hash) - return declarationFilePath; - const declarationMapText = declarationMapPath && host.readFile(declarationMapPath); - if (declarationMapPath && !declarationMapText || config.options.inlineSourceMap) - return declarationMapPath || "inline sourcemap decoding"; - if (declarationMapPath && computeSignature(declarationMapText, host) !== buildInfo.bundle.dts.mapHash) - return declarationMapPath; - const buildInfoDirectory = getDirectoryPath(getNormalizedAbsolutePath(buildInfoPath, host.getCurrentDirectory())); - const ownPrependInput = createInputFilesWithFileTexts( - jsFilePath, - jsFileText, - sourceMapFilePath, - sourceMapText, - declarationFilePath, - declarationText, - declarationMapPath, - declarationMapText, + const { buildInfoPath, - buildInfo, - /*oldFileOfCurrentEmit*/ - true - ); + jsFilePath, + sourceMapFilePath, + declarationFilePath, + declarationMapPath + } = getOutputPathsForBundle(config.options, /*forceDtsPaths*/ + false); + const buildInfo = host.getBuildInfo(buildInfoPath, config.options.configFilePath); + if (!buildInfo) return buildInfoPath; + if (!buildInfo.bundle || !buildInfo.bundle.js || declarationFilePath && !buildInfo.bundle.dts) return buildInfoPath; + const jsFileText = host.readFile(Debug.checkDefined(jsFilePath)); + if (!jsFileText) return jsFilePath; + if (computeSignature(jsFileText, host) !== buildInfo.bundle.js.hash) return jsFilePath; + const sourceMapText = sourceMapFilePath && host.readFile(sourceMapFilePath); + if (sourceMapFilePath && !sourceMapText || config.options.inlineSourceMap) return sourceMapFilePath || "inline sourcemap decoding"; + if (sourceMapFilePath && computeSignature(sourceMapText, host) !== buildInfo.bundle.js.mapHash) return sourceMapFilePath; + const declarationText = declarationFilePath && host.readFile(declarationFilePath); + if (declarationFilePath && !declarationText) return declarationFilePath; + if (declarationFilePath && computeSignature(declarationText, host) !== buildInfo.bundle.dts.hash) return declarationFilePath; + const declarationMapText = declarationMapPath && host.readFile(declarationMapPath); + if (declarationMapPath && !declarationMapText || config.options.inlineSourceMap) return declarationMapPath || "inline sourcemap decoding"; + if (declarationMapPath && computeSignature(declarationMapText, host) !== buildInfo.bundle.dts.mapHash) return declarationMapPath; + const buildInfoDirectory = getDirectoryPath(getNormalizedAbsolutePath(buildInfoPath, host.getCurrentDirectory())); + const ownPrependInput = createInputFilesWithFileTexts(jsFilePath, jsFileText, sourceMapFilePath, sourceMapText, declarationFilePath, declarationText, declarationMapPath, declarationMapText, buildInfoPath, buildInfo, /*oldFileOfCurrentEmit*/ + true); const outputFiles = []; - const prependNodes = createPrependNodes(config.projectReferences, getCommandLine, (f) => host.readFile(f), host); + const prependNodes = createPrependNodes(config.projectReferences, getCommandLine, f => host.readFile(f), host); const sourceFilesForJsEmit = createSourceFilesFromBundleBuildInfo(buildInfo.bundle, buildInfoDirectory, host); let changedDtsText; let changedDtsData; @@ -113146,40 +100219,45 @@ ${lanes.join("\n")} writeFile: (name, text, writeByteOrderMark, _onError, _sourceFiles, data) => { switch (name) { case jsFilePath: - if (jsFileText === text) - return; + if (jsFileText === text) return; break; case sourceMapFilePath: - if (sourceMapText === text) - return; + if (sourceMapText === text) return; break; case buildInfoPath: break; case declarationFilePath: - if (declarationText === text) - return; + if (declarationText === text) return; changedDtsText = text; changedDtsData = data; break; case declarationMapPath: - if (declarationMapText === text) - return; + if (declarationMapText === text) return; break; default: Debug.fail(`Unexpected path: ${name}`); } - outputFiles.push({ name, text, writeByteOrderMark, data }); + outputFiles.push({ + name, + text, + writeByteOrderMark, + data + }); }, isEmitBlocked: returnFalse, - readFile: (f) => host.readFile(f), - fileExists: (f) => host.fileExists(f), + readFile: f => host.readFile(f), + fileExists: f => host.fileExists(f), useCaseSensitiveFileNames: () => host.useCaseSensitiveFileNames(), - getBuildInfo: (bundle) => { + getBuildInfo: bundle => { const program = buildInfo.program; if (program && changedDtsText !== void 0 && config.options.composite) { program.outSignature = computeSignature(changedDtsText, host, changedDtsData); } - const { js, dts, sourceFiles } = buildInfo.bundle; + const { + js, + dts, + sourceFiles + } = buildInfo.bundle; bundle.js.sources = js.sources; if (dts) { bundle.dts.sources = dts.sources; @@ -113192,13 +100270,8 @@ ${lanes.join("\n")} getFileIncludeReasons: notImplemented, createHash: maybeBind(host, host.createHash) }; - emitFiles( - notImplementedResolver, - emitHost, - /*targetSourceFile*/ - void 0, - getTransformers(config.options, customTransformers) - ); + emitFiles(notImplementedResolver, emitHost, /*targetSourceFile*/ + void 0, getTransformers(config.options, customTransformers)); return outputFiles; } function createPrinter(printerOptions = {}, handlers = {}) { @@ -113218,7 +100291,7 @@ ${lanes.join("\n")} var omitBraceSourcePositions = !!printerOptions.omitBraceSourceMapPositions; var newLine = getNewLineCharacter(printerOptions); var moduleKind = getEmitModuleKind(printerOptions); - var bundledHelpers = /* @__PURE__ */ new Map(); + var bundledHelpers = /* @__PURE__ */new Map(); var currentSourceFile; var nodeIdToGeneratedName; var nodeIdToGeneratedPrivateName; @@ -113240,7 +100313,9 @@ ${lanes.join("\n")} var ownWriter; var write = writeBase; var isOwnFileEmit; - var bundleFileInfo = printerOptions.writeBundleFileInfo ? { sections: [] } : void 0; + var bundleFileInfo = printerOptions.writeBundleFileInfo ? { + sections: [] + } : void 0; var relativeToBuildInfo = bundleFileInfo ? Debug.checkDefined(printerOptions.relativeToBuildInfo) : void 0; var recordInternalSection = printerOptions.recordInternalSection; var sourceFileTextPos = 0; @@ -113260,10 +100335,13 @@ ${lanes.join("\n")} var commentsDisabled = !!printerOptions.removeComments; var lastSubstitution; var currentParenthesizerRule; - var { enter: enterComment, exit: exitComment } = createTimerIf(extendedDiagnostics, "commentTime", "beforeComment", "afterComment"); + var { + enter: enterComment, + exit: exitComment + } = createTimerIf(extendedDiagnostics, "commentTime", "beforeComment", "afterComment"); var parenthesizer = factory.parenthesizer; var typeArgumentParenthesizerRuleSelector = { - select: (index) => index === 0 ? parenthesizer.parenthesizeLeadingTypeArgument : void 0 + select: index => index === 0 ? parenthesizer.parenthesizeLeadingTypeArgument : void 0 }; var emitBinaryExpression = createEmitBinaryExpression(); reset2(); @@ -113308,21 +100386,13 @@ ${lanes.join("\n")} return endPrint(); } function printBundle(bundle) { - writeBundle( - bundle, - beginPrint(), - /*sourceMapGenerator*/ - void 0 - ); + writeBundle(bundle, beginPrint(), /*sourceMapGenerator*/ + void 0); return endPrint(); } function printFile(sourceFile) { - writeFile2( - sourceFile, - beginPrint(), - /*sourceMapGenerator*/ - void 0 - ); + writeFile2(sourceFile, beginPrint(), /*sourceMapGenerator*/ + void 0); return endPrint(); } function printUnparsedSource(unparsed) { @@ -113331,31 +100401,21 @@ ${lanes.join("\n")} } function writeNode(hint, node, sourceFile, output) { const previousWriter = writer; - setWriter( - output, - /*_sourceMapGenerator*/ - void 0 - ); + setWriter(output, /*_sourceMapGenerator*/ + void 0); print(hint, node, sourceFile); reset2(); writer = previousWriter; } function writeList(format, nodes, sourceFile, output) { const previousWriter = writer; - setWriter( - output, - /*_sourceMapGenerator*/ - void 0 - ); + setWriter(output, /*_sourceMapGenerator*/ + void 0); if (sourceFile) { setSourceFile(sourceFile); } - emitList( - /*parentNode*/ - void 0, - nodes, - format - ); + emitList( /*parentNode*/ + void 0, nodes, format); reset2(); writer = previousWriter; } @@ -113367,7 +100427,11 @@ ${lanes.join("\n")} if (last2 && last2.kind === kind) { last2.end = end; } else { - bundleFileInfo.sections.push({ pos, end, kind }); + bundleFileInfo.sections.push({ + pos, + end, + kind + }); } } function recordBundleFileInternalSectionStart(node) { @@ -113406,21 +100470,14 @@ ${lanes.join("\n")} writeLine(); const pos = writer.getTextPos(); const savedSections = bundleFileInfo && bundleFileInfo.sections; - if (savedSections) - bundleFileInfo.sections = []; - print( - 4 /* Unspecified */, - prepend, - /*sourceFile*/ - void 0 - ); + if (savedSections) bundleFileInfo.sections = []; + print(4 /* Unspecified */, prepend, /*sourceFile*/ + void 0); if (bundleFileInfo) { const newSections = bundleFileInfo.sections; bundleFileInfo.sections = savedSections; - if (prepend.oldFileOfCurrentEmit) - bundleFileInfo.sections.push(...newSections); - else { - newSections.forEach((section) => Debug.assert(isBundleFileTextLike(section))); + if (prepend.oldFileOfCurrentEmit) bundleFileInfo.sections.push(...newSections);else { + newSections.forEach(section => Debug.assert(isBundleFileTextLike(section))); bundleFileInfo.sections.push({ pos, end: writer.getTextPos(), @@ -113440,14 +100497,12 @@ ${lanes.join("\n")} if (recordBundleFileTextLikeSection(end)) { const prologues = getPrologueDirectivesFromBundledSourceFiles(bundle); if (prologues) { - if (!bundleFileInfo.sources) - bundleFileInfo.sources = {}; + if (!bundleFileInfo.sources) bundleFileInfo.sources = {}; bundleFileInfo.sources.prologues = prologues; } const helpers = getHelpersFromBundledSourceFiles(bundle); if (helpers) { - if (!bundleFileInfo.sources) - bundleFileInfo.sources = {}; + if (!bundleFileInfo.sources) bundleFileInfo.sources = {}; bundleFileInfo.sources.helpers = helpers; } } @@ -113457,17 +100512,10 @@ ${lanes.join("\n")} } function writeUnparsedSource(unparsed, output) { const previousWriter = writer; - setWriter( - output, - /*_sourceMapGenerator*/ - void 0 - ); - print( - 4 /* Unspecified */, - unparsed, - /*sourceFile*/ - void 0 - ); + setWriter(output, /*_sourceMapGenerator*/ + void 0); + print(4 /* Unspecified */, unparsed, /*sourceFile*/ + void 0); reset2(); writer = previousWriter; } @@ -113493,12 +100541,8 @@ ${lanes.join("\n")} if (sourceFile) { setSourceFile(sourceFile); } - pipelineEmit( - hint, - node, - /*parenthesizerRule*/ - void 0 - ); + pipelineEmit(hint, node, /*parenthesizerRule*/ + void 0); } function setSourceFile(sourceFile) { currentSourceFile = sourceFile; @@ -113520,9 +100564,9 @@ ${lanes.join("\n")} nodeIdToGeneratedName = []; nodeIdToGeneratedPrivateName = []; autoGeneratedIdToGeneratedName = []; - generatedNames = /* @__PURE__ */ new Set(); + generatedNames = /* @__PURE__ */new Set(); formattedNameTempFlagsStack = []; - formattedNameTempFlags = /* @__PURE__ */ new Map(); + formattedNameTempFlags = /* @__PURE__ */new Map(); privateNameTempFlagsStack = []; privateNameTempFlags = 0 /* Auto */; tempFlagsStack = []; @@ -113534,36 +100578,26 @@ ${lanes.join("\n")} currentSourceFile = void 0; currentLineMap = void 0; detachedCommentsInfo = void 0; - setWriter( - /*output*/ - void 0, - /*_sourceMapGenerator*/ - void 0 - ); + setWriter( /*output*/ + void 0, /*_sourceMapGenerator*/ + void 0); } function getCurrentLineMap() { return currentLineMap || (currentLineMap = getLineStarts(Debug.checkDefined(currentSourceFile))); } function emit(node, parenthesizerRule) { - if (node === void 0) - return; + if (node === void 0) return; const prevSourceFileTextKind = recordBundleFileInternalSectionStart(node); pipelineEmit(4 /* Unspecified */, node, parenthesizerRule); recordBundleFileInternalSectionEnd(prevSourceFileTextKind); } function emitIdentifierName(node) { - if (node === void 0) - return; - pipelineEmit( - 2 /* IdentifierName */, - node, - /*parenthesizerRule*/ - void 0 - ); + if (node === void 0) return; + pipelineEmit(2 /* IdentifierName */, node, /*parenthesizerRule*/ + void 0); } function emitExpression(node, parenthesizerRule) { - if (node === void 0) - return; + if (node === void 0) return; pipelineEmit(1 /* Expression */, node, parenthesizerRule); } function emitJsxAttributeValue(node) { @@ -113643,35 +100677,23 @@ ${lanes.join("\n")} 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 === 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 === 5 /* EmbeddedStatement */) { Debug.assertNode(node, isEmptyStatement); - return emitEmptyStatement( - /*isEmbeddedStatement*/ - true - ); + return emitEmptyStatement( /*isEmbeddedStatement*/ + true); } if (hint === 4 /* Unspecified */) { switch (node.kind) { case 16 /* TemplateHead */: case 17 /* TemplateMiddle */: case 18 /* TemplateTail */: - return emitLiteral( - node, - /*jsxAttributeEscape*/ - false - ); + return emitLiteral(node, /*jsxAttributeEscape*/ + false); case 80 /* Identifier */: return emitIdentifier(node); case 81 /* PrivateIdentifier */: @@ -113770,10 +100792,8 @@ ${lanes.join("\n")} case 243 /* VariableStatement */: return emitVariableStatement(node); case 242 /* EmptyStatement */: - return emitEmptyStatement( - /*isEmbeddedStatement*/ - false - ); + return emitEmptyStatement( /*isEmbeddedStatement*/ + false); case 244 /* ExpressionStatement */: return emitExpressionStatement(node); case 245 /* IfStatement */: @@ -113994,11 +101014,8 @@ ${lanes.join("\n")} case 11 /* StringLiteral */: case 14 /* RegularExpressionLiteral */: case 15 /* NoSubstitutionTemplateLiteral */: - return emitLiteral( - node, - /*jsxAttributeEscape*/ - false - ); + return emitLiteral(node, /*jsxAttributeEscape*/ + false); case 80 /* Identifier */: return emitIdentifier(node); case 81 /* PrivateIdentifier */: @@ -114083,10 +101100,8 @@ ${lanes.join("\n")} 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) { @@ -114108,12 +101123,11 @@ ${lanes.join("\n")} if (moduleKind === 0 /* None */ || printerOptions.noEmitHelpers) { return void 0; } - const bundledHelpers2 = /* @__PURE__ */ new Map(); + const bundledHelpers2 = /* @__PURE__ */new Map(); for (const sourceFile of bundle.sourceFiles) { const shouldSkip = getExternalHelpersModuleName(sourceFile) !== void 0; const helpers = getSortedEmitHelpers(sourceFile); - if (!helpers) - continue; + if (!helpers) continue; for (const helper of helpers) { if (!helper.scoped && !shouldSkip && !bundledHelpers2.get(helper.name)) { bundledHelpers2.set(helper.name, true); @@ -114140,8 +101154,7 @@ ${lanes.join("\n")} if (helpers) { for (const helper of helpers) { if (!helper.scoped) { - if (shouldSkip) - continue; + if (shouldSkip) continue; if (shouldBundle) { if (bundledHelpers.get(helper.name)) { continue; @@ -114157,8 +101170,12 @@ ${lanes.join("\n")} } else { writeLines(helper.text(makeFileLevelOptimisticUniqueName)); } - if (bundleFileInfo) - bundleFileInfo.sections.push({ pos, end: writer.getTextPos(), kind: "emitHelpers" /* EmitHelpers */, data: helper.name }); + if (bundleFileInfo) bundleFileInfo.sections.push({ + pos, + end: writer.getTextPos(), + kind: "emitHelpers" /* EmitHelpers */, + data: helper.name + }); helpersEmitted = true; } } @@ -114170,11 +101187,8 @@ ${lanes.join("\n")} return helpers && stableSort(helpers, compareEmitHelpers); } function emitNumericOrBigIntLiteral(node) { - emitLiteral( - node, - /*jsxAttributeEscape*/ - false - ); + emitLiteral(node, /*jsxAttributeEscape*/ + false); } function emitLiteral(node, jsxAttributeEscape) { const text = getLiteralTextOfNode(node, printerOptions.neverAsciiEscape, jsxAttributeEscape); @@ -114197,13 +101211,10 @@ ${lanes.join("\n")} const pos = getTextPosWithWriteLine(); writeUnparsedNode(unparsed); if (bundleFileInfo) { - updateOrPushBundleFileTextLike( - pos, - writer.getTextPos(), - unparsed.kind === 309 /* UnparsedText */ ? "text" /* Text */ : "internal" /* Internal */ - ); + updateOrPushBundleFileTextLike(pos, writer.getTextPos(), unparsed.kind === 309 /* UnparsedText */ ? "text" /* Text */ : "internal" /* Internal */); } } + function emitUnparsedSyntheticReference(unparsed) { const pos = getTextPosWithWriteLine(); writeUnparsedNode(unparsed); @@ -114226,12 +101237,8 @@ ${lanes.join("\n")} } function emitPlaceholder(hint, node, snippet) { nonEscapingWrite(`\${${snippet.order}:`); - pipelineEmitWithHintWorker( - hint, - node, - /*allowSnippets*/ - false - ); + pipelineEmitWithHintWorker(hint, node, /*allowSnippets*/ + false); nonEscapingWrite(`}`); } function emitTabStop(hint, node, snippet) { @@ -114241,19 +101248,14 @@ ${lanes.join("\n")} } function emitIdentifier(node) { const writeText = node.symbol ? writeSymbol : write; - writeText(getTextOfNode2( - node, - /*includeTrivia*/ - false - ), node.symbol); + writeText(getTextOfNode2(node, /*includeTrivia*/ + false), node.symbol); emitList(node, getIdentifierTypeArguments(node), 53776 /* TypeParameters */); } + function emitPrivateIdentifier(node) { - write(getTextOfNode2( - node, - /*includeTrivia*/ - false - )); + write(getTextOfNode2(node, /*includeTrivia*/ + false)); } function emitQualifiedName(node) { emitEntityName(node.left); @@ -114293,12 +101295,8 @@ ${lanes.join("\n")} } } function emitParameter(node) { - emitDecoratorsAndModifiers( - node, - node.modifiers, - /*allowDecorators*/ - true - ); + emitDecoratorsAndModifiers(node, node.modifiers, /*allowDecorators*/ + true); emit(node.dotDotDotToken); emitNodeWithWriter(node.name, writeParameter); emit(node.questionToken); @@ -114321,12 +101319,8 @@ ${lanes.join("\n")} writeTrailingSemicolon(); } function emitPropertyDeclaration(node) { - emitDecoratorsAndModifiers( - node, - node.modifiers, - /*allowDecorators*/ - true - ); + emitDecoratorsAndModifiers(node, node.modifiers, /*allowDecorators*/ + true); emit(node.name); emit(node.questionToken); emit(node.exclamationToken); @@ -114346,12 +101340,8 @@ ${lanes.join("\n")} popNameGenerationScope(node); } function emitMethodDeclaration(node) { - emitDecoratorsAndModifiers( - node, - node.modifiers, - /*allowDecorators*/ - true - ); + emitDecoratorsAndModifiers(node, node.modifiers, /*allowDecorators*/ + true); emit(node.asteriskToken); emit(node.name); emit(node.questionToken); @@ -114362,22 +101352,14 @@ ${lanes.join("\n")} emitBlockFunctionBody(node.body); } function emitConstructor(node) { - emitDecoratorsAndModifiers( - node, - node.modifiers, - /*allowDecorators*/ - false - ); + emitDecoratorsAndModifiers(node, node.modifiers, /*allowDecorators*/ + false); writeKeyword("constructor"); emitSignatureAndBody(node, emitSignatureHead); } function emitAccessorDeclaration(node) { - const pos = emitDecoratorsAndModifiers( - node, - node.modifiers, - /*allowDecorators*/ - true - ); + const pos = emitDecoratorsAndModifiers(node, node.modifiers, /*allowDecorators*/ + true); const token = node.kind === 177 /* GetAccessor */ ? 139 /* GetKeyword */ : 153 /* SetKeyword */; emitTokenWithComment(token, pos, writeKeyword, node); writeSpace(); @@ -114403,12 +101385,8 @@ ${lanes.join("\n")} popNameGenerationScope(node); } function emitIndexSignature(node) { - emitDecoratorsAndModifiers( - node, - node.modifiers, - /*allowDecorators*/ - false - ); + emitDecoratorsAndModifiers(node, node.modifiers, /*allowDecorators*/ + false); emitParametersForIndexSignature(node, node.parameters); emitTypeAnnotation(node.type); writeTrailingSemicolon(); @@ -114485,11 +101463,8 @@ ${lanes.join("\n")} emitTypeArguments(node, node.typeArguments); } function emitTypeLiteral(node) { - pushPrivateNameGenerationScope( - 0 /* Auto */, - /*newReservedMemberNames*/ - void 0 - ); + pushPrivateNameGenerationScope(0 /* Auto */, /*newReservedMemberNames*/ + void 0); writePunctuation("{"); const flags = getEmitFlags(node) & 1 /* SingleLine */ ? 768 /* SingleLineTypeLiteralMembers */ : 32897 /* MultiLineTypeLiteralMembers */; emitList(node, node.members, flags | 524288 /* NoSpaceIfEmpty */); @@ -114620,6 +101595,7 @@ ${lanes.join("\n")} emit(node.head); emitList(node, node.templateSpans, 262144 /* TemplateExpressionSpans */); } + function emitImportTypeNode(node) { if (node.isTypeOf) { writeKeyword("typeof"); @@ -114674,11 +101650,8 @@ ${lanes.join("\n")} emitExpressionList(node, elements, 8914 /* ArrayLiteralExpressionElements */ | preferNewLine, parenthesizer.parenthesizeExpressionForDisallowedComma); } function emitObjectLiteralExpression(node) { - pushPrivateNameGenerationScope( - 0 /* Auto */, - /*newReservedMemberNames*/ - void 0 - ); + pushPrivateNameGenerationScope(0 /* Auto */, /*newReservedMemberNames*/ + void 0); forEach(node.properties, generateMemberNames); const indentedFlag = getEmitFlags(node) & 131072 /* Indented */; if (indentedFlag) { @@ -114697,11 +101670,8 @@ ${lanes.join("\n")} const token = node.questionDotToken || setTextRangePosEnd(factory.createToken(25 /* DotToken */), node.expression.end, node.name.pos); const linesBeforeDot = getLinesBetweenNodes(node, node.expression, token); const linesAfterDot = getLinesBetweenNodes(node, token, node.name); - writeLinesAndIndent( - linesBeforeDot, - /*writeSpaceIfNotIndenting*/ - false - ); + writeLinesAndIndent(linesBeforeDot, /*writeSpaceIfNotIndenting*/ + false); const shouldEmitDotDot = token.kind !== 29 /* QuestionDotToken */ && mayNeedDotDotForPropertyAccess(node.expression) && !writer.hasTrailingComment() && !writer.hasTrailingWhitespace(); if (shouldEmitDotDot) { writePunctuation("."); @@ -114711,24 +101681,17 @@ ${lanes.join("\n")} } else { emitTokenWithComment(token.kind, node.expression.end, writePunctuation, node); } - writeLinesAndIndent( - linesAfterDot, - /*writeSpaceIfNotIndenting*/ - false - ); + writeLinesAndIndent(linesAfterDot, /*writeSpaceIfNotIndenting*/ + false); emit(node.name); decreaseIndentIf(linesBeforeDot, linesAfterDot); } function mayNeedDotDotForPropertyAccess(expression) { expression = skipPartiallyEmittedExpressions(expression); if (isNumericLiteral(expression)) { - const text = getLiteralTextOfNode( - expression, - /*neverAsciiEscape*/ - true, - /*jsxAttributeEscape*/ - false - ); + const text = getLiteralTextOfNode(expression, /*neverAsciiEscape*/ + true, /*jsxAttributeEscape*/ + false); return !(expression.numericLiteralFlags & 448 /* WithSpecifier */) && !text.includes(tokenToString(25 /* DotToken */)) && !text.includes(String.fromCharCode(69 /* E */)) && !text.includes(String.fromCharCode(101 /* e */)); } else if (isAccessExpression(expression)) { const constantValue = getConstantValue(expression); @@ -114790,11 +101753,8 @@ ${lanes.join("\n")} function emitParenthesizedExpression(node) { const openParenPos = emitTokenWithComment(21 /* OpenParenToken */, node.pos, writePunctuation, node); const indented = writeLineSeparatorsAndIndentBefore(node.expression, node); - emitExpression( - node.expression, - /*parenthesizerRule*/ - void 0 - ); + emitExpression(node.expression, /*parenthesizerRule*/ + void 0); writeLineSeparatorsAfter(node.expression, node); decreaseIndentIf(indented); emitTokenWithComment(22 /* CloseParenToken */, node.expression ? node.expression.end : openParenPos, writePunctuation, node); @@ -114845,20 +101805,14 @@ ${lanes.join("\n")} const operand = node.operand; return operand.kind === 224 /* PrefixUnaryExpression */ && (node.operator === 40 /* PlusToken */ && (operand.operator === 40 /* PlusToken */ || operand.operator === 46 /* PlusPlusToken */) || node.operator === 41 /* MinusToken */ && (operand.operator === 41 /* MinusToken */ || operand.operator === 47 /* MinusMinusToken */)); } + function emitPostfixUnaryExpression(node) { emitExpression(node.operand, parenthesizer.parenthesizeOperandOfPostfixUnary); writeTokenText(node.operator, writeOperator); } function createEmitBinaryExpression() { - return createBinaryExpressionTrampoline( - onEnter, - onLeft, - onOperator, - onRight, - onExit, - /*foldState*/ - void 0 - ); + return createBinaryExpressionTrampoline(onEnter, onLeft, onOperator, onRight, onExit, /*foldState*/ + void 0); function onEnter(node, state) { if (state) { state.stackIndex++; @@ -114869,10 +101823,8 @@ ${lanes.join("\n")} 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 = { @@ -114897,16 +101849,10 @@ ${lanes.join("\n")} writeLinesAndIndent(linesBeforeOperator, isCommaOperator); emitLeadingCommentsOfPosition(operatorToken.pos); writeTokenNode(operatorToken, operatorToken.kind === 103 /* InKeyword */ ? writeKeyword : writeOperator); - emitTrailingCommentsOfPosition( - operatorToken.end, - /*prefixSpace*/ - true - ); - writeLinesAndIndent( - linesAfterOperator, - /*writeSpaceIfNotIndenting*/ - true - ); + emitTrailingCommentsOfPosition(operatorToken.end, /*prefixSpace*/ + true); + writeLinesAndIndent(linesAfterOperator, /*writeSpaceIfNotIndenting*/ + true); } function onRight(next, _workArea, parent2) { return maybeEmitExpression(next, parent2, "right"); @@ -114923,10 +101869,8 @@ ${lanes.join("\n")} 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--; } @@ -114955,30 +101899,18 @@ ${lanes.join("\n")} const linesBeforeColon = getLinesBetweenNodes(node, node.whenTrue, node.colonToken); const linesAfterColon = getLinesBetweenNodes(node, node.colonToken, node.whenFalse); emitExpression(node.condition, parenthesizer.parenthesizeConditionOfConditionalExpression); - writeLinesAndIndent( - linesBeforeQuestion, - /*writeSpaceIfNotIndenting*/ - true - ); + writeLinesAndIndent(linesBeforeQuestion, /*writeSpaceIfNotIndenting*/ + true); emit(node.questionToken); - writeLinesAndIndent( - linesAfterQuestion, - /*writeSpaceIfNotIndenting*/ - true - ); + writeLinesAndIndent(linesAfterQuestion, /*writeSpaceIfNotIndenting*/ + true); emitExpression(node.whenTrue, parenthesizer.parenthesizeBranchOfConditionalExpression); decreaseIndentIf(linesBeforeQuestion, linesAfterQuestion); - writeLinesAndIndent( - linesBeforeColon, - /*writeSpaceIfNotIndenting*/ - true - ); + writeLinesAndIndent(linesBeforeColon, /*writeSpaceIfNotIndenting*/ + true); emit(node.colonToken); - writeLinesAndIndent( - linesAfterColon, - /*writeSpaceIfNotIndenting*/ - true - ); + writeLinesAndIndent(linesAfterColon, /*writeSpaceIfNotIndenting*/ + true); emitExpression(node.whenFalse, parenthesizer.parenthesizeBranchOfConditionalExpression); decreaseIndentIf(linesBeforeColon, linesAfterColon); } @@ -114986,6 +101918,7 @@ ${lanes.join("\n")} emit(node.head); emitList(node, node.templateSpans, 262144 /* TemplateExpressionSpans */); } + function emitYieldExpression(node) { emitTokenWithComment(127 /* YieldKeyword */, node.pos, writeKeyword, node); emit(node.asteriskToken); @@ -115004,11 +101937,8 @@ ${lanes.join("\n")} emitTypeArguments(node, node.typeArguments); } function emitAsExpression(node) { - emitExpression( - node.expression, - /*parenthesizerRule*/ - void 0 - ); + emitExpression(node.expression, /*parenthesizerRule*/ + void 0); if (node.type) { writeSpace(); writeKeyword("as"); @@ -115021,11 +101951,8 @@ ${lanes.join("\n")} writeOperator("!"); } function emitSatisfiesExpression(node) { - emitExpression( - node.expression, - /*parenthesizerRule*/ - void 0 - ); + emitExpression(node.expression, /*parenthesizerRule*/ + void 0); if (node.type) { writeSpace(); writeKeyword("satisfies"); @@ -115043,39 +101970,22 @@ ${lanes.join("\n")} emit(node.literal); } function emitBlock(node) { - emitBlockStatements( - node, - /*forceSingleLine*/ - !node.multiLine && isEmptyBlock(node) - ); + emitBlockStatements(node, /*forceSingleLine*/ + !node.multiLine && isEmptyBlock(node)); } function emitBlockStatements(node, forceSingleLine) { - emitTokenWithComment( - 19 /* OpenBraceToken */, - node.pos, - writePunctuation, - /*contextNode*/ - node - ); + emitTokenWithComment(19 /* OpenBraceToken */, node.pos, writePunctuation, /*contextNode*/ + node); const format = forceSingleLine || getEmitFlags(node) & 1 /* SingleLine */ ? 768 /* SingleLineBlockStatements */ : 129 /* MultiLineBlockStatements */; emitList(node, node.statements, format); - emitTokenWithComment( - 20 /* CloseBraceToken */, - node.statements.end, - writePunctuation, - /*contextNode*/ - node, - /*indentLeading*/ - !!(format & 1 /* MultiLine */) - ); + emitTokenWithComment(20 /* CloseBraceToken */, node.statements.end, writePunctuation, /*contextNode*/ + node, /*indentLeading*/ + !!(format & 1 /* MultiLine */)); } + function emitVariableStatement(node) { - emitDecoratorsAndModifiers( - node, - node.modifiers, - /*allowDecorators*/ - false - ); + emitDecoratorsAndModifiers(node, node.modifiers, /*allowDecorators*/ + false); emit(node.declarationList); writeTrailingSemicolon(); } @@ -115135,13 +102045,8 @@ ${lanes.join("\n")} function emitForStatement(node) { const openParenPos = emitTokenWithComment(99 /* ForKeyword */, node.pos, writeKeyword, node); writeSpace(); - let pos = emitTokenWithComment( - 21 /* OpenParenToken */, - openParenPos, - writePunctuation, - /*contextNode*/ - node - ); + let pos = emitTokenWithComment(21 /* OpenParenToken */, openParenPos, writePunctuation, /*contextNode*/ + node); emitForBinding(node.initializer); pos = emitTokenWithComment(27 /* SemicolonToken */, node.initializer ? node.initializer.end : pos, writePunctuation, node); emitExpressionWithLeadingSpace(node.condition); @@ -115218,13 +102123,9 @@ ${lanes.join("\n")} } if (isSimilarNode && contextNode.end !== pos) { const isJsxExprContext = contextNode.kind === 294 /* JsxExpression */; - emitTrailingCommentsOfPosition( - pos, - /*prefixSpace*/ - !isJsxExprContext, - /*forceNoNewline*/ - isJsxExprContext - ); + emitTrailingCommentsOfPosition(pos, /*prefixSpace*/ + !isJsxExprContext, /*forceNoNewline*/ + isJsxExprContext); } return pos; } @@ -115232,16 +102133,12 @@ ${lanes.join("\n")} return node.kind === 2 /* SingleLineCommentTrivia */ || !!node.hasTrailingNewLine; } function willEmitLeadingNewLine(node) { - if (!currentSourceFile) - return false; - if (some(getLeadingCommentRanges(currentSourceFile.text, node.pos), commentWillEmitNewLine)) - return true; - if (some(getSyntheticLeadingComments(node), commentWillEmitNewLine)) - return true; + if (!currentSourceFile) return false; + if (some(getLeadingCommentRanges(currentSourceFile.text, node.pos), 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); } @@ -115264,13 +102161,8 @@ ${lanes.join("\n")} return parenthesizeExpressionForNoAsi(parenthesizer.parenthesizeExpressionForDisallowedComma(node)); } function emitReturnStatement(node) { - emitTokenWithComment( - 107 /* ReturnKeyword */, - node.pos, - writeKeyword, - /*contextNode*/ - node - ); + emitTokenWithComment(107 /* ReturnKeyword */, node.pos, writeKeyword, /*contextNode*/ + node); emitExpressionWithLeadingSpace(node.expression && parenthesizeExpressionForNoAsi(node.expression), parenthesizeExpressionForNoAsi); writeTrailingSemicolon(); } @@ -115322,11 +102214,12 @@ ${lanes.join("\n")} writeTrailingSemicolon(); } function emitVariableDeclaration(node) { + var _ref37, _ref38; var _a, _b, _c; emit(node.name); emit(node.exclamationToken); emitTypeAnnotation(node.type); - emitInitializer(node.initializer, ((_a = node.type) == null ? void 0 : _a.end) ?? ((_c = (_b = node.name.emitNode) == null ? void 0 : _b.typeNode) == null ? void 0 : _c.end) ?? node.name.end, node, parenthesizer.parenthesizeExpressionForDisallowedComma); + emitInitializer(node.initializer, (_ref37 = (_ref38 = (_a = node.type) == null ? void 0 : _a.end) !== null && _ref38 !== void 0 ? _ref38 : (_c = (_b = node.name.emitNode) == null ? void 0 : _b.typeNode) == null ? void 0 : _c.end) !== null && _ref37 !== void 0 ? _ref37 : node.name.end, node, parenthesizer.parenthesizeExpressionForDisallowedComma); } function emitVariableDeclarationList(node) { if (isVarAwaitUsing(node)) { @@ -115340,16 +102233,13 @@ ${lanes.join("\n")} writeSpace(); emitList(node, node.declarations, 528 /* VariableDeclarationList */); } + function emitFunctionDeclaration(node) { emitFunctionDeclarationOrExpression(node); } function emitFunctionDeclarationOrExpression(node) { - emitDecoratorsAndModifiers( - node, - node.modifiers, - /*allowDecorators*/ - false - ); + emitDecoratorsAndModifiers(node, node.modifiers, /*allowDecorators*/ + false); writeKeyword("function"); emit(node.asteriskToken); writeSpace(); @@ -115422,11 +102312,8 @@ ${lanes.join("\n")} onAfterEmitNode == null ? void 0 : onAfterEmitNode(body); } function emitBlockFunctionBodyOnSingleLine(body) { - emitBlockFunctionBodyWorker( - body, - /*emitBlockFunctionBodyOnSingleLine*/ - true - ); + emitBlockFunctionBodyWorker(body, /*emitBlockFunctionBodyOnSingleLine*/ + true); } function emitBlockFunctionBodyWorker(body, emitBlockFunctionBodyOnSingleLine2) { const statementOffset = emitPrologueDirectives(body.statements); @@ -115437,32 +102324,19 @@ ${lanes.join("\n")} emitList(body, body.statements, 768 /* SingleLineFunctionBodyStatements */); increaseIndent(); } else { - emitList( - body, - body.statements, - 1 /* MultiLineFunctionBodyStatements */, - /*parenthesizerRule*/ - void 0, - statementOffset - ); + emitList(body, body.statements, 1 /* MultiLineFunctionBodyStatements */, /*parenthesizerRule*/ + void 0, statementOffset); } } function emitClassDeclaration(node) { emitClassDeclarationOrExpression(node); } function emitClassDeclarationOrExpression(node) { - pushPrivateNameGenerationScope( - 0 /* Auto */, - /*newReservedMemberNames*/ - void 0 - ); + pushPrivateNameGenerationScope(0 /* Auto */, /*newReservedMemberNames*/ + void 0); forEach(node.members, generateMemberNames); - emitDecoratorsAndModifiers( - node, - node.modifiers, - /*allowDecorators*/ - true - ); + emitDecoratorsAndModifiers(node, node.modifiers, /*allowDecorators*/ + true); emitTokenWithComment(86 /* ClassKeyword */, moveRangePastModifiers(node).pos, writeKeyword, node); if (node.name) { writeSpace(); @@ -115484,17 +102358,10 @@ ${lanes.join("\n")} popPrivateNameGenerationScope(); } function emitInterfaceDeclaration(node) { - pushPrivateNameGenerationScope( - 0 /* Auto */, - /*newReservedMemberNames*/ - void 0 - ); - emitDecoratorsAndModifiers( - node, - node.modifiers, - /*allowDecorators*/ - false - ); + pushPrivateNameGenerationScope(0 /* Auto */, /*newReservedMemberNames*/ + void 0); + emitDecoratorsAndModifiers(node, node.modifiers, /*allowDecorators*/ + false); writeKeyword("interface"); writeSpace(); emit(node.name); @@ -115507,12 +102374,8 @@ ${lanes.join("\n")} popPrivateNameGenerationScope(); } function emitTypeAliasDeclaration(node) { - emitDecoratorsAndModifiers( - node, - node.modifiers, - /*allowDecorators*/ - false - ); + emitDecoratorsAndModifiers(node, node.modifiers, /*allowDecorators*/ + false); writeKeyword("type"); writeSpace(); emit(node.name); @@ -115524,12 +102387,8 @@ ${lanes.join("\n")} writeTrailingSemicolon(); } function emitEnumDeclaration(node) { - emitDecoratorsAndModifiers( - node, - node.modifiers, - /*allowDecorators*/ - false - ); + emitDecoratorsAndModifiers(node, node.modifiers, /*allowDecorators*/ + false); writeKeyword("enum"); writeSpace(); emit(node.name); @@ -115539,20 +102398,15 @@ ${lanes.join("\n")} writePunctuation("}"); } function emitModuleDeclaration(node) { - emitDecoratorsAndModifiers( - node, - node.modifiers, - /*allowDecorators*/ - false - ); + emitDecoratorsAndModifiers(node, node.modifiers, /*allowDecorators*/ + false); if (~node.flags & 2048 /* GlobalAugmentation */) { writeKeyword(node.flags & 32 /* Namespace */ ? "namespace" : "module"); writeSpace(); } emit(node.name); let body = node.body; - if (!body) - return writeTrailingSemicolon(); + if (!body) return writeTrailingSemicolon(); while (body && isModuleDeclaration(body)) { writePunctuation("."); emit(body.name); @@ -115564,32 +102418,19 @@ ${lanes.join("\n")} function emitModuleBlock(node) { pushNameGenerationScope(node); forEach(node.statements, generateNames); - emitBlockStatements( - node, - /*forceSingleLine*/ - isEmptyBlock(node) - ); + emitBlockStatements(node, /*forceSingleLine*/ + isEmptyBlock(node)); popNameGenerationScope(node); } function emitCaseBlock(node) { emitTokenWithComment(19 /* OpenBraceToken */, node.pos, writePunctuation, node); emitList(node, node.clauses, 129 /* CaseBlockClauses */); - emitTokenWithComment( - 20 /* CloseBraceToken */, - node.clauses.end, - writePunctuation, - node, - /*indentLeading*/ - true - ); + emitTokenWithComment(20 /* CloseBraceToken */, node.clauses.end, writePunctuation, node, /*indentLeading*/ + true); } function emitImportEqualsDeclaration(node) { - emitDecoratorsAndModifiers( - node, - node.modifiers, - /*allowDecorators*/ - false - ); + emitDecoratorsAndModifiers(node, node.modifiers, /*allowDecorators*/ + false); emitTokenWithComment(102 /* ImportKeyword */, node.modifiers ? node.modifiers.end : node.pos, writeKeyword, node); writeSpace(); if (node.isTypeOnly) { @@ -115611,12 +102452,8 @@ ${lanes.join("\n")} } } function emitImportDeclaration(node) { - emitDecoratorsAndModifiers( - node, - node.modifiers, - /*allowDecorators*/ - false - ); + emitDecoratorsAndModifiers(node, node.modifiers, /*allowDecorators*/ + false); emitTokenWithComment(102 /* ImportKeyword */, node.modifiers ? node.modifiers.end : node.pos, writeKeyword, node); writeSpace(); if (node.importClause) { @@ -115665,19 +102502,12 @@ ${lanes.join("\n")} emitTokenWithComment(90 /* DefaultKeyword */, nextPos, writeKeyword, node); } writeSpace(); - emitExpression( - node.expression, - node.isExportEquals ? parenthesizer.getParenthesizeRightSideOfBinaryForOperator(64 /* EqualsToken */) : parenthesizer.parenthesizeExpressionOfExportDefault - ); + emitExpression(node.expression, node.isExportEquals ? parenthesizer.getParenthesizeRightSideOfBinaryForOperator(64 /* EqualsToken */) : parenthesizer.parenthesizeExpressionOfExportDefault); writeTrailingSemicolon(); } function emitExportDeclaration(node) { - emitDecoratorsAndModifiers( - node, - node.modifiers, - /*allowDecorators*/ - false - ); + emitDecoratorsAndModifiers(node, node.modifiers, /*allowDecorators*/ + false); let nextPos = emitTokenWithComment(95 /* ExportKeyword */, node.pos, writeKeyword, node); writeSpace(); if (node.isTypeOnly) { @@ -115707,6 +102537,7 @@ ${lanes.join("\n")} const elements = node.elements; emitList(node, elements, 526226 /* ImportAttributes */); } + function emitImportAttribute(node) { emit(node.name); writePunctuation(":"); @@ -115811,6 +102642,7 @@ ${lanes.join("\n")} function emitJsxAttributes(node) { emitList(node, node.properties, 262656 /* JsxElementAttributes */); } + function emitJsxAttribute(node) { emit(node.name); emitNodeWithPrefix("=", writePunctuation, node.initializer, emitJsxAttributeValue); @@ -115872,8 +102704,9 @@ ${lanes.join("\n")} emitCaseOrDefaultClauseRest(node, node.statements, pos); } function emitCaseOrDefaultClauseRest(parentNode, statements, colonPos) { - const emitAsSingleStatement = statements.length === 1 && // treat synthesized nodes as located on the same line for emit purposes - (!currentSourceFile || nodeIsSynthesized(parentNode) || nodeIsSynthesized(statements[0]) || rangeStartPositionsAreOnSameLine(parentNode, statements[0], currentSourceFile)); + const emitAsSingleStatement = statements.length === 1 && ( + // treat synthesized nodes as located on the same line for emit purposes + !currentSourceFile || nodeIsSynthesized(parentNode) || nodeIsSynthesized(statements[0]) || rangeStartPositionsAreOnSameLine(parentNode, statements[0], currentSourceFile)); let format = 163969 /* CaseOrDefaultClauseStatements */; if (emitAsSingleStatement) { writeToken(59 /* ColonToken */, colonPos, writePunctuation, parentNode); @@ -115890,6 +102723,7 @@ ${lanes.join("\n")} writeSpace(); emitList(node, node.types, 528 /* HeritageClauseTypes */); } + function emitCatchClause(node) { const openParenPos = emitTokenWithComment(85 /* CatchKeyword */, node.pos, writeKeyword, node); writeSpace(); @@ -115954,6 +102788,7 @@ ${lanes.join("\n")} emitList(node, node.tags, 33 /* JSDocComment */); } } + writeSpace(); write("*/"); } @@ -116033,13 +102868,16 @@ ${lanes.join("\n")} function emitJSDocTypeLiteral(lit) { emitList(lit, factory.createNodeArray(lit.jsDocPropertyTags), 33 /* JSDocComment */); } + function emitJSDocSignature(sig) { if (sig.typeParameters) { emitList(sig, factory.createNodeArray(sig.typeParameters), 33 /* JSDocComment */); } + if (sig.parameters) { emitList(sig, factory.createNodeArray(sig.parameters), 33 /* JSDocComment */); } + if (sig.type) { writeLine(); writeSpace(); @@ -116102,15 +102940,17 @@ ${lanes.join("\n")} } } 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) { const pos = writer.getTextPos(); writeComment(`/// `); - if (bundleFileInfo) - bundleFileInfo.sections.push({ pos, end: writer.getTextPos(), kind: "no-default-lib" /* NoDefaultLib */ }); + if (bundleFileInfo) bundleFileInfo.sections.push({ + pos, + end: writer.getTextPos(), + kind: "no-default-lib" /* NoDefaultLib */ + }); writeLine(); } if (currentSourceFile && currentSourceFile.moduleName) { @@ -116130,23 +102970,35 @@ ${lanes.join("\n")} for (const directive of files) { const pos = writer.getTextPos(); writeComment(`/// `); - if (bundleFileInfo) - bundleFileInfo.sections.push({ pos, end: writer.getTextPos(), kind: "reference" /* Reference */, data: directive.fileName }); + if (bundleFileInfo) bundleFileInfo.sections.push({ + pos, + end: writer.getTextPos(), + kind: "reference" /* Reference */, + data: directive.fileName + }); writeLine(); } for (const directive of types) { const pos = writer.getTextPos(); const resolutionMode = directive.resolutionMode && directive.resolutionMode !== (currentSourceFile == null ? void 0 : currentSourceFile.impliedNodeFormat) ? `resolution-mode="${directive.resolutionMode === 99 /* ESNext */ ? "import" : "require"}"` : ""; writeComment(`/// `); - if (bundleFileInfo) - bundleFileInfo.sections.push({ pos, end: writer.getTextPos(), kind: !directive.resolutionMode ? "type" /* Type */ : directive.resolutionMode === 99 /* ESNext */ ? "type-import" /* TypeResolutionModeImport */ : "type-require" /* TypeResolutionModeRequire */, data: directive.fileName }); + if (bundleFileInfo) bundleFileInfo.sections.push({ + pos, + end: writer.getTextPos(), + kind: !directive.resolutionMode ? "type" /* Type */ : directive.resolutionMode === 99 /* ESNext */ ? "type-import" /* TypeResolutionModeImport */ : "type-require" /* TypeResolutionModeRequire */, + data: directive.fileName + }); writeLine(); } for (const directive of libs2) { const pos = writer.getTextPos(); writeComment(`/// `); - if (bundleFileInfo) - bundleFileInfo.sections.push({ pos, end: writer.getTextPos(), kind: "lib" /* Lib */, data: directive.fileName }); + if (bundleFileInfo) bundleFileInfo.sections.push({ + pos, + end: writer.getTextPos(), + kind: "lib" /* Lib */, + data: directive.fileName + }); writeLine(); } } @@ -116155,16 +103007,10 @@ ${lanes.join("\n")} pushNameGenerationScope(node); forEach(node.statements, generateNames); emitHelpers(node); - const index = findIndex(statements, (statement) => !isPrologueDirective(statement)); + const index = findIndex(statements, statement => !isPrologueDirective(statement)); emitTripleSlashDirectivesIfNeeded(node); - emitList( - node, - statements, - 1 /* MultiLine */, - /*parenthesizerRule*/ - void 0, - index === -1 ? statements.length : index - ); + emitList(node, statements, 1 /* MultiLine */, /*parenthesizerRule*/ + void 0, index === -1 ? statements.length : index); popNameGenerationScope(node); } function emitPartiallyEmittedExpression(node) { @@ -116178,13 +103024,8 @@ ${lanes.join("\n")} } } function emitCommaList(node) { - emitExpressionList( - node, - node.elements, - 528 /* CommaListElements */, - /*parenthesizerRule*/ - void 0 - ); + emitExpressionList(node, node.elements, 528 /* CommaListElements */, /*parenthesizerRule*/ + void 0); } function emitPrologueDirectives(statements, sourceFile, seenPrologueDirectives, recordBundleFileSection) { let needsToSetSourceFile = !!sourceFile; @@ -116200,8 +103041,12 @@ ${lanes.join("\n")} writeLine(); const pos = writer.getTextPos(); emit(statement); - if (recordBundleFileSection && bundleFileInfo) - bundleFileInfo.sections.push({ pos, end: writer.getTextPos(), kind: "prologue" /* Prologue */, data: statement.expression.text }); + if (recordBundleFileSection && bundleFileInfo) bundleFileInfo.sections.push({ + pos, + end: writer.getTextPos(), + kind: "prologue" /* Prologue */, + data: statement.expression.text + }); if (seenPrologueDirectives) { seenPrologueDirectives.add(statement.expression.text); } @@ -116218,8 +103063,12 @@ ${lanes.join("\n")} writeLine(); const pos = writer.getTextPos(); emit(prologue); - if (bundleFileInfo) - bundleFileInfo.sections.push({ pos, end: writer.getTextPos(), kind: "prologue" /* Prologue */, data: prologue.data }); + if (bundleFileInfo) bundleFileInfo.sections.push({ + pos, + end: writer.getTextPos(), + kind: "prologue" /* Prologue */, + data: prologue.data + }); if (seenPrologueDirectives) { seenPrologueDirectives.add(prologue.data); } @@ -116230,34 +103079,27 @@ ${lanes.join("\n")} if (isSourceFile(sourceFileOrBundle)) { emitPrologueDirectives(sourceFileOrBundle.statements, sourceFileOrBundle); } else { - const seenPrologueDirectives = /* @__PURE__ */ new Set(); + const seenPrologueDirectives = /* @__PURE__ */new Set(); for (const prepend of sourceFileOrBundle.prepends) { emitUnparsedPrologues(prepend.prologues, seenPrologueDirectives); } for (const sourceFile of sourceFileOrBundle.sourceFiles) { - emitPrologueDirectives( - sourceFile.statements, - sourceFile, - seenPrologueDirectives, - /*recordBundleFileSection*/ - true - ); + emitPrologueDirectives(sourceFile.statements, sourceFile, seenPrologueDirectives, /*recordBundleFileSection*/ + true); } setSourceFile(void 0); } } function getPrologueDirectivesFromBundledSourceFiles(bundle) { - const seenPrologueDirectives = /* @__PURE__ */ new Set(); + const seenPrologueDirectives = /* @__PURE__ */new Set(); let prologues; for (let index = 0; index < bundle.sourceFiles.length; index++) { const sourceFile = bundle.sourceFiles[index]; let directives; let end = 0; for (const statement of sourceFile.statements) { - if (!isPrologueDirective(statement)) - break; - if (seenPrologueDirectives.has(statement.expression.text)) - continue; + if (!isPrologueDirective(statement)) break; + if (seenPrologueDirectives.has(statement.expression.text)) continue; seenPrologueDirectives.add(statement.expression.text); (directives || (directives = [])).push({ pos: statement.pos, @@ -116270,8 +103112,11 @@ ${lanes.join("\n")} }); end = end < statement.end ? statement.end : end; } - if (directives) - (prologues || (prologues = [])).push({ file: index, text: sourceFile.text.substring(0, end), directives }); + if (directives) (prologues || (prologues = [])).push({ + file: index, + text: sourceFile.text.substring(0, end), + directives + }); } return prologues; } @@ -116298,8 +103143,7 @@ ${lanes.join("\n")} } } function emitNodeWithWriter(node, writer2) { - if (!node) - return; + if (!node) return; const savedWrite = write; write = writer2; emit(node); @@ -116333,25 +103177,16 @@ ${lanes.join("\n")} } pos++; } - const textRange = { pos: -1, end: -1 }; - if (start === 0) - textRange.pos = modifiers.pos; - if (pos === modifiers.length - 1) - textRange.end = modifiers.end; + const textRange = { + pos: -1, + end: -1 + }; + if (start === 0) textRange.pos = modifiers.pos; + if (pos === modifiers.length - 1) textRange.end = modifiers.end; if (lastMode === "modifiers" || allowDecorators) { - emitNodeListItems( - emit, - node, - modifiers, - lastMode === "modifiers" ? 2359808 /* Modifiers */ : 2146305 /* Decorators */, - /*parenthesizerRule*/ - void 0, - start, - pos - start, - /*hasTrailingComma*/ - false, - textRange - ); + emitNodeListItems(emit, node, modifiers, lastMode === "modifiers" ? 2359808 /* Modifiers */ : 2146305 /* Decorators */, /*parenthesizerRule*/ + void 0, start, pos - start, /*hasTrailingComma*/ + false, textRange); } start = pos; lastMode = mode; @@ -116437,9 +103272,11 @@ ${lanes.join("\n")} } emitList(parentNode, typeParameters, 53776 /* TypeParameters */); } + function emitParameters(parentNode, parameters) { emitList(parentNode, parameters, 2576 /* Parameters */); } + function canEmitSimpleArrowHead(parentNode, parameters) { const parameter = singleOrUndefined(parameters); return parameter && parameter.pos === parentNode.pos && isArrowFunction(parentNode) && !parentNode.type && !some(parentNode.modifiers) && !some(parentNode.typeParameters) && !some(parameter.modifiers) && !parameter.dotDotDotToken && !parameter.questionToken && !parameter.type && !parameter.initializer && isIdentifier(parameter.name); @@ -116454,6 +103291,7 @@ ${lanes.join("\n")} function emitParametersForIndexSignature(parentNode, parameters) { emitList(parentNode, parameters, 8848 /* IndexSignatureParameters */); } + function writeDelimiter(format) { switch (format & 60 /* DelimitersMask */) { case 0 /* None */: @@ -116477,15 +103315,7 @@ ${lanes.join("\n")} } } function emitList(parentNode, children, format, parenthesizerRule, start, count) { - emitNodeList( - emit, - parentNode, - children, - format | (parentNode && getEmitFlags(parentNode) & 2 /* MultiLine */ ? 65536 /* PreferNewLine */ : 0), - parenthesizerRule, - start, - count - ); + emitNodeList(emit, parentNode, children, format | (parentNode && getEmitFlags(parentNode) & 2 /* MultiLine */ ? 65536 /* PreferNewLine */ : 0), parenthesizerRule, start, count); } function emitExpressionList(parentNode, children, format, parenthesizerRule, start, count) { emitNodeList(emitExpression, parentNode, children, format, parenthesizerRule, start, count); @@ -116504,11 +103334,8 @@ ${lanes.join("\n")} if (format & 15360 /* BracketsMask */) { writePunctuation(getOpeningBracket(format)); if (isEmpty && children) { - emitTrailingCommentsOfPosition( - children.pos, - /*prefixSpace*/ - true - ); + emitTrailingCommentsOfPosition(children.pos, /*prefixSpace*/ + true); } } onBeforeEmitNodeArray == null ? void 0 : onBeforeEmitNodeArray(children); @@ -116568,13 +103395,9 @@ ${lanes.join("\n")} } if (shouldEmitInterveningComments && format & 60 /* DelimitersMask */ && !positionIsSynthesized(child.pos)) { const commentRange = getCommentRange(child); - emitTrailingCommentsOfPosition( - commentRange.pos, - /*prefixSpace*/ - !!(format & 512 /* SpaceBetweenSiblings */), - /*forceNoNewline*/ - true - ); + emitTrailingCommentsOfPosition(commentRange.pos, /*prefixSpace*/ + !!(format & 512 /* SpaceBetweenSiblings */), /*forceNoNewline*/ + true); } writeLine(separatingLineTerminatorCount); shouldEmitInterveningComments = false; @@ -116749,14 +103572,7 @@ ${lanes.join("\n")} } if (currentSourceFile && parentNode && !positionIsSynthesized(parentNode.pos) && !nodeIsSynthesized(firstChild) && (!firstChild.parent || getOriginalNode(firstChild.parent) === getOriginalNode(parentNode))) { if (preserveSourceNewlines) { - return getEffectiveLines( - (includeComments) => getLinesBetweenPositionAndPrecedingNonWhitespaceCharacter( - firstChild.pos, - parentNode.pos, - currentSourceFile, - includeComments - ) - ); + return getEffectiveLines(includeComments => getLinesBetweenPositionAndPrecedingNonWhitespaceCharacter(firstChild.pos, parentNode.pos, currentSourceFile, includeComments)); } return rangeStartPositionsAreOnSameLine(parentNode, firstChild, currentSourceFile) ? 0 : 1; } @@ -116775,14 +103591,7 @@ ${lanes.join("\n")} return 0; } else if (currentSourceFile && !nodeIsSynthesized(previousNode) && !nodeIsSynthesized(nextNode)) { if (preserveSourceNewlines && siblingNodePositionsAreComparable(previousNode, nextNode)) { - return getEffectiveLines( - (includeComments) => getLinesBetweenRangeEndAndRangeStart( - previousNode, - nextNode, - currentSourceFile, - includeComments - ) - ); + return getEffectiveLines(includeComments => getLinesBetweenRangeEndAndRangeStart(previousNode, nextNode, currentSourceFile, includeComments)); } else if (!preserveSourceNewlines && originalNodesHaveSameParent(previousNode, nextNode)) { return rangeEndIsOnSameLineAsRangeStart(previousNode, nextNode, currentSourceFile) ? 0 : 1; } @@ -116806,14 +103615,7 @@ ${lanes.join("\n")} if (currentSourceFile && parentNode && !positionIsSynthesized(parentNode.pos) && !nodeIsSynthesized(lastChild) && (!lastChild.parent || lastChild.parent === parentNode)) { if (preserveSourceNewlines) { const end = childrenTextRange && !positionIsSynthesized(childrenTextRange.end) ? childrenTextRange.end : lastChild.end; - return getEffectiveLines( - (includeComments) => getLinesBetweenPositionAndNextNonWhitespaceCharacter( - end, - parentNode.end, - currentSourceFile, - includeComments - ) - ); + return getEffectiveLines(includeComments => getLinesBetweenPositionAndNextNonWhitespaceCharacter(end, parentNode.end, currentSourceFile, includeComments)); } return rangeEndPositionsAreOnSameLine(parentNode, lastChild, currentSourceFile) ? 0 : 1; } @@ -116828,37 +103630,25 @@ ${lanes.join("\n")} } function getEffectiveLines(getLineDifference) { Debug.assert(!!preserveSourceNewlines); - const lines = getLineDifference( - /*includeComments*/ - true - ); + const lines = getLineDifference( /*includeComments*/ + true); if (lines === 0) { - return getLineDifference( - /*includeComments*/ - false - ); + return getLineDifference( /*includeComments*/ + false); } return lines; } function writeLineSeparatorsAndIndentBefore(node, parent2) { const leadingNewlines = preserveSourceNewlines && getLeadingLineTerminatorCount(parent2, node, 0 /* None */); if (leadingNewlines) { - writeLinesAndIndent( - leadingNewlines, - /*writeSpaceIfNotIndenting*/ - false - ); + writeLinesAndIndent(leadingNewlines, /*writeSpaceIfNotIndenting*/ + false); } return !!leadingNewlines; } function writeLineSeparatorsAfter(node, parent2) { - const trailingNewlines = preserveSourceNewlines && getClosingLineTerminatorCount( - parent2, - node, - 0 /* None */, - /*childrenTextRange*/ - void 0 - ); + const trailingNewlines = preserveSourceNewlines && getClosingLineTerminatorCount(parent2, node, 0 /* None */, /*childrenTextRange*/ + void 0); if (trailingNewlines) { writeLine(trailingNewlines); } @@ -116885,14 +103675,7 @@ ${lanes.join("\n")} } if (currentSourceFile && !nodeIsSynthesized(parent2) && !nodeIsSynthesized(node1) && !nodeIsSynthesized(node2)) { if (preserveSourceNewlines) { - return getEffectiveLines( - (includeComments) => getLinesBetweenRangeEndAndRangeStart( - node1, - node2, - currentSourceFile, - includeComments - ) - ); + return getEffectiveLines(includeComments => getLinesBetweenRangeEndAndRangeStart(node1, node2, currentSourceFile, includeComments)); } return rangeEndIsOnSameLineAsRangeStart(node1, node2, currentSourceFile) ? 0 : 1; } @@ -116965,7 +103748,7 @@ ${lanes.join("\n")} } function reserveNameInNestedScopes(name) { if (!reservedNames || reservedNames === lastOrUndefined(reservedNamesStack)) { - reservedNames = /* @__PURE__ */ new Set(); + reservedNames = /* @__PURE__ */new Set(); } reservedNames.add(name); } @@ -116981,13 +103764,12 @@ ${lanes.join("\n")} } function reservePrivateNameInNestedScopes(name) { if (!reservedPrivateNames || reservedPrivateNames === lastOrUndefined(reservedPrivateNamesStack)) { - reservedPrivateNames = /* @__PURE__ */ new Set(); + reservedPrivateNames = /* @__PURE__ */new Set(); } reservedPrivateNames.add(name); } function generateNames(node) { - if (!node) - return; + if (!node) return; switch (node.kind) { case 241 /* Block */: forEach(node.statements, generateNames); @@ -117072,8 +103854,7 @@ ${lanes.join("\n")} } } function generateMemberNames(node) { - if (!node) - return; + if (!node) return; switch (node.kind) { case 303 /* PropertyAssignment */: case 304 /* ShorthandPropertyAssignment */: @@ -117106,7 +103887,7 @@ ${lanes.join("\n")} function generateNameCached(node, privateName, flags, prefix, suffix) { const nodeId = getNodeId(node); const cache = privateName ? nodeIdToGeneratedPrivateName : nodeIdToGeneratedName; - return cache[nodeId] || (cache[nodeId] = generateNameForNode(node, privateName, flags ?? 0 /* None */, formatGeneratedNamePart(prefix, generateName), formatGeneratedNamePart(suffix))); + return cache[nodeId] || (cache[nodeId] = generateNameForNode(node, privateName, flags !== null && flags !== void 0 ? flags : 0 /* None */, formatGeneratedNamePart(prefix, generateName), formatGeneratedNamePart(suffix))); } function isUniqueName(name, privateName) { return isFileLevelUniqueNameInCurrentFile(name, privateName) && !isReservedName(name, privateName) && !generatedNames.has(name); @@ -117129,16 +103910,18 @@ ${lanes.join("\n")} return true; } function getTempFlags(formattedNameKey) { + var _ref39; switch (formattedNameKey) { case "": return tempFlags; case "#": return privateNameTempFlags; default: - return (formattedNameTempFlags == null ? void 0 : formattedNameTempFlags.get(formattedNameKey)) ?? 0 /* Auto */; + return (_ref39 = formattedNameTempFlags == null ? void 0 : formattedNameTempFlags.get(formattedNameKey)) !== null && _ref39 !== void 0 ? _ref39 : 0 /* Auto */; } } function setTempFlags(formattedNameKey, flags) { + var _formattedNameTempFla; switch (formattedNameKey) { case "": tempFlags = flags; @@ -117147,7 +103930,7 @@ ${lanes.join("\n")} privateNameTempFlags = flags; break; default: - formattedNameTempFlags ?? (formattedNameTempFlags = /* @__PURE__ */ new Map()); + (_formattedNameTempFla = formattedNameTempFlags) !== null && _formattedNameTempFla !== void 0 ? _formattedNameTempFla : formattedNameTempFlags = /* @__PURE__ */new Map(); formattedNameTempFlags.set(formattedNameKey, flags); break; } @@ -117230,114 +104013,60 @@ ${lanes.join("\n")} } } function makeFileLevelOptimisticUniqueName(name) { - return makeUniqueName2( - name, - isFileLevelUniqueNameInCurrentFile, - /*optimistic*/ - true, - /*scoped*/ - false, - /*privateName*/ - false, - /*prefix*/ - "", - /*suffix*/ - "" - ); + return makeUniqueName2(name, isFileLevelUniqueNameInCurrentFile, /*optimistic*/ + true, /*scoped*/ + false, /*privateName*/ + false, /*prefix*/ + "", /*suffix*/ + ""); } function generateNameForModuleOrEnum(node) { const name = getTextOfNode2(node.name); - return isUniqueLocalName(name, tryCast(node, canHaveLocals)) ? name : makeUniqueName2( - name, - isUniqueName, - /*optimistic*/ - false, - /*scoped*/ - false, - /*privateName*/ - false, - /*prefix*/ - "", - /*suffix*/ - "" - ); + return isUniqueLocalName(name, tryCast(node, canHaveLocals)) ? name : makeUniqueName2(name, isUniqueName, /*optimistic*/ + false, /*scoped*/ + false, /*privateName*/ + false, /*prefix*/ + "", /*suffix*/ + ""); } function generateNameForImportOrExportDeclaration(node) { const expr = getExternalModuleName(node); const baseName = isStringLiteral(expr) ? makeIdentifierFromModuleName(expr.text) : "module"; - return makeUniqueName2( - baseName, - isUniqueName, - /*optimistic*/ - false, - /*scoped*/ - false, - /*privateName*/ - false, - /*prefix*/ - "", - /*suffix*/ - "" - ); + return makeUniqueName2(baseName, isUniqueName, /*optimistic*/ + false, /*scoped*/ + false, /*privateName*/ + false, /*prefix*/ + "", /*suffix*/ + ""); } function generateNameForExportDefault() { - return makeUniqueName2( - "default", - isUniqueName, - /*optimistic*/ - false, - /*scoped*/ - false, - /*privateName*/ - false, - /*prefix*/ - "", - /*suffix*/ - "" - ); + return makeUniqueName2("default", isUniqueName, /*optimistic*/ + false, /*scoped*/ + false, /*privateName*/ + false, /*prefix*/ + "", /*suffix*/ + ""); } function generateNameForClassExpression() { - return makeUniqueName2( - "class", - isUniqueName, - /*optimistic*/ - false, - /*scoped*/ - false, - /*privateName*/ - false, - /*prefix*/ - "", - /*suffix*/ - "" - ); + return makeUniqueName2("class", isUniqueName, /*optimistic*/ + false, /*scoped*/ + false, /*privateName*/ + false, /*prefix*/ + "", /*suffix*/ + ""); } function generateNameForMethodOrAccessor(node, privateName, prefix, suffix) { if (isIdentifier(node.name)) { return generateNameCached(node.name, privateName); } - return makeTempVariableName( - 0 /* Auto */, - /*reservedInNestedScopes*/ - false, - privateName, - prefix, - suffix - ); + return makeTempVariableName(0 /* Auto */, /*reservedInNestedScopes*/ + false, privateName, prefix, suffix); } function generateNameForNode(node, privateName, flags, prefix, suffix) { switch (node.kind) { case 80 /* Identifier */: case 81 /* PrivateIdentifier */: - return makeUniqueName2( - getTextOfNode2(node), - isUniqueName, - !!(flags & 16 /* Optimistic */), - !!(flags & 8 /* ReservedInNestedScopes */), - privateName, - prefix, - suffix - ); + return makeUniqueName2(getTextOfNode2(node), isUniqueName, !!(flags & 16 /* Optimistic */), !!(flags & 8 /* ReservedInNestedScopes */), privateName, prefix, suffix); case 267 /* ModuleDeclaration */: case 266 /* EnumDeclaration */: Debug.assert(!prefix && !suffix && !privateName); @@ -117347,21 +104076,16 @@ ${lanes.join("\n")} Debug.assert(!prefix && !suffix && !privateName); return generateNameForImportOrExportDeclaration(node); case 262 /* FunctionDeclaration */: - case 263 /* ClassDeclaration */: { - Debug.assert(!prefix && !suffix && !privateName); - const name = node.name; - if (name && !isGeneratedIdentifier(name)) { - return generateNameForNode( - name, - /*privateName*/ - false, - flags, - prefix, - suffix - ); + case 263 /* ClassDeclaration */: + { + Debug.assert(!prefix && !suffix && !privateName); + const name = node.name; + if (name && !isGeneratedIdentifier(name)) { + return generateNameForNode(name, /*privateName*/ + false, flags, prefix, suffix); + } + return generateNameForExportDefault(); } - return generateNameForExportDefault(); - } case 277 /* ExportAssignment */: Debug.assert(!prefix && !suffix && !privateName); return generateNameForExportDefault(); @@ -117373,23 +104097,11 @@ ${lanes.join("\n")} case 178 /* SetAccessor */: return generateNameForMethodOrAccessor(node, privateName, prefix, suffix); case 167 /* ComputedPropertyName */: - return makeTempVariableName( - 0 /* Auto */, - /*reservedInNestedScopes*/ - true, - privateName, - prefix, - suffix - ); + return makeTempVariableName(0 /* Auto */, /*reservedInNestedScopes*/ + true, privateName, prefix, suffix); default: - return makeTempVariableName( - 0 /* Auto */, - /*reservedInNestedScopes*/ - false, - privateName, - prefix, - suffix - ); + return makeTempVariableName(0 /* Auto */, /*reservedInNestedScopes*/ + false, privateName, prefix, suffix); } } function makeName(name) { @@ -117401,31 +104113,13 @@ ${lanes.join("\n")} return makeTempVariableName(0 /* Auto */, !!(autoGenerate.flags & 8 /* ReservedInNestedScopes */), isPrivateIdentifier(name), prefix, suffix); case 2 /* Loop */: Debug.assertNode(name, isIdentifier); - return makeTempVariableName( - 268435456 /* _i */, - !!(autoGenerate.flags & 8 /* ReservedInNestedScopes */), - /*privateName*/ - false, - prefix, - suffix - ); + return makeTempVariableName(268435456 /* _i */, !!(autoGenerate.flags & 8 /* ReservedInNestedScopes */), /*privateName*/ + false, prefix, suffix); case 3 /* Unique */: - return makeUniqueName2( - idText(name), - autoGenerate.flags & 32 /* FileLevel */ ? isFileLevelUniqueNameInCurrentFile : isUniqueName, - !!(autoGenerate.flags & 16 /* Optimistic */), - !!(autoGenerate.flags & 8 /* ReservedInNestedScopes */), - isPrivateIdentifier(name), - prefix, - suffix - ); + return makeUniqueName2(idText(name), autoGenerate.flags & 32 /* FileLevel */ ? isFileLevelUniqueNameInCurrentFile : isUniqueName, !!(autoGenerate.flags & 16 /* Optimistic */), !!(autoGenerate.flags & 8 /* ReservedInNestedScopes */), isPrivateIdentifier(name), prefix, suffix); } - return Debug.fail(`Unsupported GeneratedIdentifierKind: ${Debug.formatEnum( - autoGenerate.flags & 7 /* KindMask */, - GeneratedIdentifierFlags, - /*isFlags*/ - true - )}.`); + return Debug.fail(`Unsupported GeneratedIdentifierKind: ${Debug.formatEnum(autoGenerate.flags & 7 /* KindMask */, GeneratedIdentifierFlags, /*isFlags*/ + true)}.`); } function pipelineEmitWithComments(hint, node) { const pipelinePhase = getNextPipelinePhase(2 /* Comments */, hint, node); @@ -117463,12 +104157,10 @@ ${lanes.join("\n")} const skipTrailingComments = end < 0 || (emitFlags & 2048 /* NoTrailingComments */) !== 0 || node.kind === 12 /* JsxText */; if ((pos > 0 || end > 0) && pos !== end) { if (!skipLeadingComments) { - emitLeadingComments( - pos, - /*isEmittedNode*/ - node.kind !== 359 /* NotEmittedStatement */ - ); + emitLeadingComments(pos, /*isEmittedNode*/ + node.kind !== 359 /* NotEmittedStatement */); } + if (!skipLeadingComments || pos >= 0 && (emitFlags & 1024 /* NoLeadingComments */) !== 0) { containerPos = pos; } @@ -117526,7 +104218,10 @@ ${lanes.join("\n")} } function emitBodyWithDetachedComments(node, detachedRange, emitCallback) { enterComment(); - const { pos, end } = detachedRange; + const { + pos, + end + } = detachedRange; const emitFlags = getEmitFlags(node); const skipLeadingComments = pos < 0 || (emitFlags & 1024 /* NoLeadingComments */) !== 0; const skipTrailingComments = commentsDisabled || end < 0 || (emitFlags & 2048 /* NoTrailingComments */) !== 0; @@ -117543,11 +104238,8 @@ ${lanes.join("\n")} } enterComment(); if (!skipTrailingComments) { - emitLeadingComments( - detachedRange.end, - /*isEmittedNode*/ - true - ); + emitLeadingComments(detachedRange.end, /*isEmittedNode*/ + true); if (hasWrittenComment && !writer.isAtStartOfLine()) { writer.writeLine(); } @@ -117601,8 +104293,7 @@ ${lanes.join("\n")} 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; @@ -117620,18 +104311,14 @@ ${lanes.join("\n")} if (commentsDisabled || pos === -1) { return; } - emitLeadingComments( - pos, - /*isEmittedNode*/ - true - ); + emitLeadingComments(pos, /*isEmittedNode*/ + true); } function emitTrailingComments(pos) { 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(" "); } @@ -117651,8 +104338,7 @@ ${lanes.join("\n")} exitComment(); } function emitTrailingCommentOfPositionNoNewline(commentPos, commentEnd, kind) { - if (!currentSourceFile) - return; + if (!currentSourceFile) return; emitPos(commentPos); writeCommentRange(currentSourceFile.text, getCurrentLineMap(), writer, commentPos, commentEnd, newLine); emitPos(commentEnd); @@ -117661,8 +104347,7 @@ ${lanes.join("\n")} } } function emitTrailingCommentOfPosition(commentPos, commentEnd, _kind, hasTrailingNewLine) { - if (!currentSourceFile) - return; + if (!currentSourceFile) return; emitPos(commentPos); writeCommentRange(currentSourceFile.text, getCurrentLineMap(), writer, commentPos, commentEnd, newLine); emitPos(commentEnd); @@ -117677,13 +104362,8 @@ ${lanes.join("\n")} if (hasDetachedComments(pos)) { forEachLeadingCommentWithoutDetachedComments(cb); } else { - forEachLeadingCommentRange( - currentSourceFile.text, - pos, - cb, - /*state*/ - pos - ); + forEachLeadingCommentRange(currentSourceFile.text, pos, cb, /*state*/ + pos); } } } @@ -117696,21 +104376,15 @@ ${lanes.join("\n")} 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(); } else { detachedCommentsInfo = void 0; } - forEachLeadingCommentRange( - currentSourceFile.text, - pos, - cb, - /*state*/ - pos - ); + forEachLeadingCommentRange(currentSourceFile.text, pos, cb, /*state*/ + pos); } function emitDetachedCommentsAndUpdateCommentsInfo(range) { const currentDetachedCommentInfo = currentSourceFile && emitDetachedComments(currentSourceFile.text, getCurrentLineMap(), writer, emitComment, range, newLine, commentsDisabled); @@ -117723,8 +104397,7 @@ ${lanes.join("\n")} } } 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); @@ -117751,14 +104424,7 @@ ${lanes.join("\n")} Debug.assertIsDefined(node.parent, "UnparsedNodes must have parent pointers"); const parsed = getParsedSourceMap(node.parent); if (parsed && sourceMapGenerator) { - sourceMapGenerator.appendSourceMap( - writer.getLine(), - writer.getColumn(), - parsed, - node.parent.sourceMapPath, - node.parent.getLineAndCharacterOfPosition(node.pos), - node.parent.getLineAndCharacterOfPosition(node.end) - ); + sourceMapGenerator.appendSourceMap(writer.getLine(), writer.getColumn(), parsed, node.parent.sourceMapPath, node.parent.getLineAndCharacterOfPosition(node.pos), node.parent.getLineAndCharacterOfPosition(node.end)); } } else { const source = sourceMapRange.source || sourceMapSource; @@ -117789,16 +104455,12 @@ ${lanes.join("\n")} if (sourceMapsDisabled || positionIsSynthesized(pos) || isJsonSourceMapSource(sourceMapSource)) { return; } - const { line: sourceLine, character: sourceCharacter } = getLineAndCharacterOfPosition(sourceMapSource, pos); - sourceMapGenerator.addMapping( - writer.getLine(), - writer.getColumn(), - sourceMapSourceIndex, - sourceLine, - sourceCharacter, - /*nameIndex*/ - void 0 - ); + const { + line: sourceLine, + character: sourceCharacter + } = getLineAndCharacterOfPosition(sourceMapSource, pos); + sourceMapGenerator.addMapping(writer.getLine(), writer.getColumn(), sourceMapSourceIndex, sourceLine, sourceCharacter, /*nameIndex*/ + void 0); } function emitSourcePos(source, pos) { if (source !== sourceMapSource) { @@ -117824,8 +104486,7 @@ ${lanes.join("\n")} 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); } @@ -117858,6 +104519,7 @@ ${lanes.join("\n")} return fileExtensionIs(sourceFile.fileName, ".json" /* Json */); } } + function createBracketsMap() { const brackets2 = []; brackets2[1024 /* Braces */] = ["{", "}"]; @@ -117888,6 +104550,7 @@ ${lanes.join("\n")} var init_emitter = __esm({ "src/compiler/emitter.ts"() { "use strict"; + init_ts2(); init_ts2(); init_ts_performance(); @@ -117903,7 +104566,7 @@ ${lanes.join("\n")} isTopLevelValueImportEqualsWithEntityName: notImplemented, getNodeCheckFlags: notImplemented, isDeclarationVisible: notImplemented, - isLateBound: (_node) => false, + isLateBound: _node => false, collectLinkedAliases: notImplemented, isImplementationOfOverload: notImplemented, isRequiredInitializedParameter: notImplemented, @@ -117937,10 +104600,18 @@ ${lanes.join("\n")} isImportRequiredByAugmentation: notImplemented, tryFindAmbientModule: notImplemented }; - createPrinterWithDefaults = /* @__PURE__ */ memoize(() => createPrinter({})); - createPrinterWithRemoveComments = /* @__PURE__ */ memoize(() => createPrinter({ removeComments: true })); - createPrinterWithRemoveCommentsNeverAsciiEscape = /* @__PURE__ */ memoize(() => createPrinter({ removeComments: true, neverAsciiEscape: true })); - createPrinterWithRemoveCommentsOmitTrailingSemicolon = /* @__PURE__ */ memoize(() => createPrinter({ removeComments: true, omitTrailingSemicolon: true })); + createPrinterWithDefaults = /* @__PURE__ */memoize(() => createPrinter({})); + createPrinterWithRemoveComments = /* @__PURE__ */memoize(() => createPrinter({ + removeComments: true + })); + createPrinterWithRemoveCommentsNeverAsciiEscape = /* @__PURE__ */memoize(() => createPrinter({ + removeComments: true, + neverAsciiEscape: true + })); + createPrinterWithRemoveCommentsOmitTrailingSemicolon = /* @__PURE__ */memoize(() => createPrinter({ + removeComments: true, + omitTrailingSemicolon: true + })); } }); @@ -117949,7 +104620,7 @@ ${lanes.join("\n")} if (!host.getDirectories || !host.readDirectory) { return void 0; } - const cachedReadDirectoryResult = /* @__PURE__ */ new Map(); + const cachedReadDirectoryResult = /* @__PURE__ */new Map(); const getCanonicalFileName = createGetCanonicalFileName(useCaseSensitiveFileNames2); return { useCaseSensitiveFileNames: useCaseSensitiveFileNames2, @@ -117989,15 +104660,10 @@ ${lanes.join("\n")} var _a; if (!host.realpath || ensureTrailingDirectorySeparator(toPath3(host.realpath(rootDir))) === rootDirPath) { const resultFromHost = { - files: map(host.readDirectory( - rootDir, - /*extensions*/ - void 0, - /*exclude*/ - void 0, - /*include*/ - ["*.*"] - ), getBaseNameOfFileName) || [], + files: map(host.readDirectory(rootDir, /*extensions*/ + void 0, /*exclude*/ + void 0, /*include*/ + ["*.*"]), getBaseNameOfFileName) || [], directories: host.getDirectories(rootDir) || [] }; cachedReadDirectoryResult.set(ensureTrailingDirectorySeparator(rootDirPath), resultFromHost); @@ -118030,12 +104696,8 @@ ${lanes.join("\n")} const path = toPath3(fileName); const result = getCachedFileSystemEntriesForBaseDir(path); if (result) { - updateFilesOfFileSystemEntry( - result, - getBaseNameOfFileName(fileName), - /*fileExists*/ - true - ); + updateFilesOfFileSystemEntry(result, getBaseNameOfFileName(fileName), /*fileExists*/ + true); } return host.writeFile(fileName, data, writeByteOrderMark); } @@ -118086,22 +104748,15 @@ ${lanes.join("\n")} 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, - /*extensions*/ - void 0, - /*exclude*/ - void 0, - /*include*/ - ["*.*"] - ), getBaseNameOfFileName) || emptyArray, + files: map(host.readDirectory(dir, /*extensions*/ + void 0, /*exclude*/ + void 0, /*include*/ + ["*.*"]), getBaseNameOfFileName) || emptyArray, directories: host.getDirectories(dir) || emptyArray }; - if (path === rootDirPath) - rootSymLinkResult = result; + if (path === rootDirPath) rootSymLinkResult = result; return result; } } @@ -118143,6 +104798,7 @@ ${lanes.join("\n")} updateFilesOfFileSystemEntry(parentResult, getBaseNameOfFileName(fileName), eventKind === 0 /* Created */); } } + function updateFilesOfFileSystemEntry(parentResult, baseName, fileExists2) { const canonicalizedFiles = parentResult.sortedAndCanonicalizedFiles; const canonicalizedBaseName = getCanonicalFileName(baseName); @@ -118154,7 +104810,7 @@ ${lanes.join("\n")} const sortedIndex = binarySearch(canonicalizedFiles, canonicalizedBaseName, identity, compareStringsCaseSensitive); if (sortedIndex >= 0) { canonicalizedFiles.splice(sortedIndex, 1); - const unsortedIndex = parentResult.files.findIndex((entry) => getCanonicalFileName(entry) === canonicalizedBaseName); + const unsortedIndex = parentResult.files.findIndex(entry => getCanonicalFileName(entry) === canonicalizedBaseName); parentResult.files.splice(unsortedIndex, 1); } } @@ -118178,12 +104834,11 @@ ${lanes.join("\n")} existing.projects.add(projectPath); } else { extendedConfigFilesMap.set(extendedConfigFilePath, { - projects: /* @__PURE__ */ new Set([projectPath]), + projects: /* @__PURE__ */new Set([projectPath]), 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); } @@ -118192,60 +104847,48 @@ ${lanes.join("\n")} }); } function clearSharedExtendedConfigFileWatcher(projectPath, extendedConfigFilesMap) { - extendedConfigFilesMap.forEach((watcher) => { - if (watcher.projects.delete(projectPath)) - watcher.close(); + extendedConfigFilesMap.forEach(watcher => { + if (watcher.projects.delete(projectPath)) watcher.close(); }); } function cleanExtendedConfigCache(extendedConfigCache, extendedConfigFilePath, toPath3) { - if (!extendedConfigCache.delete(extendedConfigFilePath)) - return; - extendedConfigCache.forEach(({ extendedResult }, key) => { + if (!extendedConfigCache.delete(extendedConfigFilePath)) return; + extendedConfigCache.forEach(({ + extendedResult + }, key) => { var _a; - if ((_a = extendedResult.extendedSourceFiles) == null ? void 0 : _a.some((extendedFile) => toPath3(extendedFile) === extendedConfigFilePath)) { + if ((_a = extendedResult.extendedSourceFiles) == null ? void 0 : _a.some(extendedFile => toPath3(extendedFile) === extendedConfigFilePath)) { cleanExtendedConfigCache(extendedConfigCache, key, toPath3); } }); } function updatePackageJsonWatch(lookups, packageJsonWatches, createPackageJsonWatch) { const newMap = new Map(lookups); - mutateMap( - packageJsonWatches, - newMap, - { - createNewValue: createPackageJsonWatch, - onDeleteValue: closeFileWatcher - } - ); + mutateMap(packageJsonWatches, newMap, { + createNewValue: createPackageJsonWatch, + onDeleteValue: closeFileWatcher + }); } function updateMissingFilePathsWatch(program, missingFileWatches, createMissingFileWatch) { const missingFilePaths = program.getMissingFilePaths(); const newMissingFilePathMap = arrayToMap(missingFilePaths, identity, returnTrue); - mutateMap( - missingFileWatches, - newMissingFilePathMap, - { - // Watch the missing files - createNewValue: createMissingFileWatch, - // Files that are no longer missing (e.g. because they are no longer required) - // should no longer be watched. - onDeleteValue: closeFileWatcher - } - ); + mutateMap(missingFileWatches, newMissingFilePathMap, { + // Watch the missing files + createNewValue: createMissingFileWatch, + // Files that are no longer missing (e.g. because they are no longer required) + // should no longer be watched. + onDeleteValue: closeFileWatcher + }); } function updateWatchingWildcardDirectories(existingWatchedForWildcards, wildcardDirectories, watchDirectory) { - mutateMap( - existingWatchedForWildcards, - wildcardDirectories, - { - // Create new watch and recursive info - createNewValue: createWildcardDirectoryWatcher, - // Close existing watch thats not needed any more - onDeleteValue: closeFileWatcherOf, - // Close existing watch that doesnt match in the flags - onExistingValue: updateWildcardDirectoryWatcher - } - ); + mutateMap(existingWatchedForWildcards, wildcardDirectories, { + // Create new watch and recursive info + createNewValue: createWildcardDirectoryWatcher, + // Close existing watch thats not needed any more + onDeleteValue: closeFileWatcherOf, + // Close existing watch that doesnt match in the flags + onExistingValue: updateWildcardDirectoryWatcher + }); function createWildcardDirectoryWatcher(directory, flags) { return { watcher: watchDirectory(directory, flags), @@ -118280,8 +104923,7 @@ ${lanes.join("\n")} 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; @@ -118290,13 +104932,10 @@ ${lanes.join("\n")} writeLog(`Project: ${configFileName} Detected excluded file: ${fileOrDirectory}`); return true; } - if (!program) - return false; - if (outFile(options) || options.outDir) - return false; + if (!program) return false; + if (outFile(options) || options.outDir) return false; if (isDeclarationFileName(fileOrDirectoryPath)) { - if (options.declarationDir) - return false; + if (options.declarationDir) return false; } else if (!fileExtensionIsOneOf(fileOrDirectoryPath, supportedJSExtensionsFlat)) { return false; } @@ -118309,11 +104948,10 @@ ${lanes.join("\n")} } return false; function hasSourceFile(file) { - return realProgram ? !!realProgram.getSourceFileByPath(file) : builderProgram ? builderProgram.getState().fileInfos.has(file) : !!find(program, (rootFile) => toPath3(rootFile) === file); + 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 */: @@ -118362,16 +105000,8 @@ ${lanes.join("\n")} function createExcludeHandlingAddWatch(key) { return (file, cb, flags, options, detailInfo1, detailInfo2) => { var _a; - return !matchesExclude(file, key === "watchFile" ? options == null ? void 0 : options.excludeFiles : options == null ? void 0 : options.excludeDirectories, useCaseSensitiveFileNames2(), ((_a = host.getCurrentDirectory) == null ? void 0 : _a.call(host)) || "") ? factory2[key].call( - /*thisArgs*/ - void 0, - file, - cb, - flags, - options, - detailInfo1, - detailInfo2 - ) : excludeWatcherFactory(file, flags, options, detailInfo1, detailInfo2); + return !matchesExclude(file, key === "watchFile" ? options == null ? void 0 : options.excludeFiles : options == null ? void 0 : options.excludeDirectories, useCaseSensitiveFileNames2(), ((_a = host.getCurrentDirectory) == null ? void 0 : _a.call(host)) || "") ? factory2[key].call( /*thisArgs*/ + void 0, file, cb, flags, options, detailInfo1, detailInfo2) : excludeWatcherFactory(file, flags, options, detailInfo1, detailInfo2); }; } function useCaseSensitiveFileNames2() { @@ -118412,27 +105042,16 @@ ${lanes.join("\n")} }; } function createTriggerLoggingAddWatch(key) { - return (file, cb, flags, options, detailInfo1, detailInfo2) => plainInvokeFactory[key].call( - /*thisArgs*/ - void 0, - file, - (...args) => { - const triggerredInfo = `${key === "watchFile" ? "FileWatcher" : "DirectoryWatcher"}:: Triggered with ${args[0]} ${args[1] !== void 0 ? args[1] : ""}:: ${getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo2)}`; - log(triggerredInfo); - const start = timestamp(); - cb.call( - /*thisArg*/ - void 0, - ...args - ); - const elapsed = timestamp() - start; - log(`Elapsed:: ${elapsed}ms ${triggerredInfo}`); - }, - flags, - options, - detailInfo1, - detailInfo2 - ); + return (file, cb, flags, options, detailInfo1, detailInfo2) => plainInvokeFactory[key].call( /*thisArgs*/ + void 0, file, (...args) => { + const triggerredInfo = `${key === "watchFile" ? "FileWatcher" : "DirectoryWatcher"}:: Triggered with ${args[0]} ${args[1] !== void 0 ? args[1] : ""}:: ${getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo2)}`; + log(triggerredInfo); + const start = timestamp(); + cb.call( /*thisArg*/ + void 0, ...args); + const elapsed = timestamp() - start; + log(`Elapsed:: ${elapsed}ms ${triggerredInfo}`); + }, flags, options, detailInfo1, detailInfo2); } function getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo3) { return `WatchInfo: ${file} ${flags} ${JSON.stringify(options)} ${getDetailWatchInfo3 ? getDetailWatchInfo3(detailInfo1, detailInfo2) : detailInfo2 === void 0 ? detailInfo1 : `${detailInfo1} ${detailInfo2}`}`; @@ -118444,6 +105063,7 @@ ${lanes.join("\n")} watchFile: fallbackPolling !== void 0 ? fallbackPolling : 1 /* PriorityPollingInterval */ }; } + function closeFileWatcherOf(objWithWatcher) { objWithWatcher.watcher.close(); } @@ -118451,14 +105071,15 @@ ${lanes.join("\n")} var init_watchUtilities = __esm({ "src/compiler/watchUtilities.ts"() { "use strict"; + init_ts2(); - ProgramUpdateLevel = /* @__PURE__ */ ((ProgramUpdateLevel2) => { + ProgramUpdateLevel = /* @__PURE__ */(ProgramUpdateLevel2 => { ProgramUpdateLevel2[ProgramUpdateLevel2["Update"] = 0] = "Update"; ProgramUpdateLevel2[ProgramUpdateLevel2["RootNamesAndUpdate"] = 1] = "RootNamesAndUpdate"; ProgramUpdateLevel2[ProgramUpdateLevel2["Full"] = 2] = "Full"; return ProgramUpdateLevel2; })(ProgramUpdateLevel || {}); - WatchLogLevel = /* @__PURE__ */ ((WatchLogLevel2) => { + WatchLogLevel = /* @__PURE__ */(WatchLogLevel2 => { WatchLogLevel2[WatchLogLevel2["None"] = 0] = "None"; WatchLogLevel2[WatchLogLevel2["TriggerOnly"] = 1] = "TriggerOnly"; WatchLogLevel2[WatchLogLevel2["Verbose"] = 2] = "Verbose"; @@ -118469,7 +105090,7 @@ ${lanes.join("\n")} // src/compiler/program.ts function findConfigFile(searchPath, fileExists, configName = "tsconfig.json") { - return forEachAncestorDirectory(searchPath, (ancestor) => { + return forEachAncestorDirectory(searchPath, ancestor => { const fileName = combinePaths(ancestor, configName); return fileExists(fileName) ? fileName : void 0; }); @@ -118481,7 +105102,7 @@ ${lanes.join("\n")} } function computeCommonSourceDirectoryOfFilenames(fileNames, currentDirectory, getCanonicalFileName) { let commonPathComponents; - const failed = forEach(fileNames, (sourceFile) => { + const failed = forEach(fileNames, sourceFile => { const sourcePathComponents = getNormalizedPathComponents(sourceFile, currentDirectory); sourcePathComponents.pop(); if (!commonPathComponents) { @@ -118534,14 +105155,7 @@ ${lanes.join("\n")} return (fileName, data, writeByteOrderMark, onError) => { try { mark("beforeIOWrite"); - writeFileEnsuringDirectories( - fileName, - data, - writeByteOrderMark, - actualWriteFile, - createDirectory, - directoryExists - ); + writeFileEnsuringDirectories(fileName, data, writeByteOrderMark, actualWriteFile, createDirectory, directoryExists); mark("afterIOWrite"); measure("I/O Write", "beforeIOWrite", "afterIOWrite"); } catch (e) { @@ -118552,7 +105166,7 @@ ${lanes.join("\n")} }; } function createCompilerHostWorker(options, setParentNodes, system = sys) { - const existingDirectories = /* @__PURE__ */ new Map(); + const existingDirectories = /* @__PURE__ */new Map(); const getCanonicalFileName = createGetCanonicalFileName(system.useCaseSensitiveFileNames); function directoryExists(directoryPath) { if (existingDirectories.has(directoryPath)) { @@ -118568,29 +105182,25 @@ ${lanes.join("\n")} return getDirectoryPath(normalizePath(system.getExecutingFilePath())); } const newLine = getNewLineCharacter(options); - const realpath = system.realpath && ((path) => system.realpath(path)); + const realpath = system.realpath && (path => system.realpath(path)); const compilerHost = { - getSourceFile: createGetSourceFile((fileName) => compilerHost.readFile(fileName), () => options, setParentNodes), + getSourceFile: createGetSourceFile(fileName => compilerHost.readFile(fileName), () => options, setParentNodes), getDefaultLibLocation, - getDefaultLibFileName: (options2) => combinePaths(getDefaultLibLocation(), getDefaultLibFileName(options2)), - writeFile: createWriteFileMeasuringIO( - (path, data, writeByteOrderMark) => system.writeFile(path, data, writeByteOrderMark), - (path) => (compilerHost.createDirectory || system.createDirectory)(path), - (path) => directoryExists(path) - ), + getDefaultLibFileName: options2 => combinePaths(getDefaultLibLocation(), getDefaultLibFileName(options2)), + writeFile: createWriteFileMeasuringIO((path, data, writeByteOrderMark) => system.writeFile(path, data, writeByteOrderMark), path => (compilerHost.createDirectory || system.createDirectory)(path), path => directoryExists(path)), getCurrentDirectory: memoize(() => system.getCurrentDirectory()), useCaseSensitiveFileNames: () => system.useCaseSensitiveFileNames, getCanonicalFileName, getNewLine: () => newLine, - fileExists: (fileName) => system.fileExists(fileName), - readFile: (fileName) => system.readFile(fileName), - trace: (s) => system.write(s + newLine), - directoryExists: (directoryName) => system.directoryExists(directoryName), - getEnvironmentVariable: (name) => system.getEnvironmentVariable ? system.getEnvironmentVariable(name) : "", - getDirectories: (path) => system.getDirectories(path), + fileExists: fileName => system.fileExists(fileName), + readFile: fileName => system.readFile(fileName), + trace: s => system.write(s + newLine), + directoryExists: directoryName => system.directoryExists(directoryName), + getEnvironmentVariable: name => system.getEnvironmentVariable ? system.getEnvironmentVariable(name) : "", + getDirectories: path => system.getDirectories(path), realpath, readDirectory: (path, extensions, include, exclude, depth) => system.readDirectory(path, extensions, include, exclude, depth), - createDirectory: (d) => system.createDirectory(d), + createDirectory: d => system.createDirectory(d), createHash: maybeBind(system, system.createHash) }; return compilerHost; @@ -118601,15 +105211,14 @@ ${lanes.join("\n")} const originalDirectoryExists = host.directoryExists; const originalCreateDirectory = host.createDirectory; const originalWriteFile = host.writeFile; - const readFileCache = /* @__PURE__ */ new Map(); - const fileExistsCache = /* @__PURE__ */ new Map(); - const directoryExistsCache = /* @__PURE__ */ new Map(); - const sourceFileCache = /* @__PURE__ */ new Map(); - const readFileWithCache = (fileName) => { + const readFileCache = /* @__PURE__ */new Map(); + const fileExistsCache = /* @__PURE__ */new Map(); + const directoryExistsCache = /* @__PURE__ */new Map(); + const sourceFileCache = /* @__PURE__ */new Map(); + 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) => { @@ -118617,11 +105226,10 @@ ${lanes.join("\n")} readFileCache.set(key, newValue !== void 0 ? newValue : false); return newValue; }; - host.readFile = (fileName) => { + 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); } @@ -118632,19 +105240,17 @@ ${lanes.join("\n")} 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)); + sourceFileCache.set(impliedNodeFormat, (forImpliedNodeFormat || /* @__PURE__ */new Map()).set(key, sourceFile)); } return sourceFile; } : void 0; - host.fileExists = (fileName) => { + 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; @@ -118656,9 +105262,9 @@ ${lanes.join("\n")} const value = readFileCache.get(key); if (value !== void 0 && value !== data) { readFileCache.delete(key); - sourceFileCache.forEach((map2) => map2.delete(key)); + sourceFileCache.forEach(map2 => map2.delete(key)); } else if (getSourceFileWithCache) { - sourceFileCache.forEach((map2) => { + sourceFileCache.forEach(map2 => { const sourceFile = map2.get(key); if (sourceFile && sourceFile.text !== data) { map2.delete(key); @@ -118669,17 +105275,16 @@ ${lanes.join("\n")} }; } if (originalDirectoryExists) { - host.directoryExists = (directory) => { + 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; }; if (originalCreateDirectory) { - host.createDirectory = (directory) => { + host.createDirectory = directory => { const key = toPath3(directory); directoryExistsCache.delete(key); originalCreateDirectory.call(host, directory); @@ -118718,9 +105323,12 @@ ${lanes.join("\n")} function formatDiagnostic(diagnostic, host) { const errorMessage = `${diagnosticCategoryName(diagnostic)} TS${diagnostic.code}: ${flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine())}${host.getNewLine()}`; if (diagnostic.file) { - const { line, character } = getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start); + const { + line, + character + } = getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start); const fileName = diagnostic.file.fileName; - const relativeFileName = convertToRelativePath(fileName, host.getCurrentDirectory(), (fileName2) => host.getCanonicalFileName(fileName2)); + const relativeFileName = convertToRelativePath(fileName, host.getCurrentDirectory(), fileName2 => host.getCanonicalFileName(fileName2)); return `${relativeFileName}(${line + 1},${character + 1}): ` + errorMessage; } return errorMessage; @@ -118737,12 +105345,19 @@ ${lanes.join("\n")} return "\x1B[94m" /* Blue */; } } + function formatColorAndReset(text, formatStyle) { return formatStyle + text + resetEscapeSequence; } function formatCodeSpan(file, start, length2, indent3, squiggleColor, host) { - const { line: firstLine, character: firstLineChar } = getLineAndCharacterOfPosition(file, start); - const { line: lastLine, character: lastLineChar } = getLineAndCharacterOfPosition(file, start + length2); + const { + line: firstLine, + character: firstLineChar + } = getLineAndCharacterOfPosition(file, start); + const { + line: lastLine, + character: lastLineChar + } = getLineAndCharacterOfPosition(file, start + length2); const lastLineInFile = getLineAndCharacterOfPosition(file, file.text.length).line; const hasMoreThanFiveLines = lastLine - firstLine >= 4; let gutterWidth = (lastLine + 1 + "").length; @@ -118779,8 +105394,11 @@ ${lanes.join("\n")} return context; } function formatLocation(file, start, host, color = formatColorAndReset) { - const { line: firstLine, character: firstLineChar } = getLineAndCharacterOfPosition(file, start); - const relativeFileName = host ? convertToRelativePath(file.fileName, host.getCurrentDirectory(), (fileName) => host.getCanonicalFileName(fileName)) : file.fileName; + const { + line: firstLine, + character: firstLineChar + } = getLineAndCharacterOfPosition(file, start); + const relativeFileName = host ? convertToRelativePath(file.fileName, host.getCurrentDirectory(), fileName => host.getCanonicalFileName(fileName)) : file.fileName; let output = ""; output += color(relativeFileName, "\x1B[96m" /* Cyan */); output += ":"; @@ -118793,7 +105411,10 @@ ${lanes.join("\n")} let output = ""; for (const diagnostic of diagnostics) { if (diagnostic.file) { - const { file, start } = diagnostic; + const { + file, + start + } = diagnostic; output += formatLocation(file, start, host); output += " - "; } @@ -118806,7 +105427,12 @@ ${lanes.join("\n")} } if (diagnostic.relatedInformation) { output += host.getNewLine(); - for (const { file, start, length: length2, messageText } of diagnostic.relatedInformation) { + for (const { + file, + start, + length: length2, + messageText + } of diagnostic.relatedInformation) { if (file) { output += host.getNewLine(); output += halfIndent + formatLocation(file, start, host); @@ -118875,57 +105501,42 @@ ${lanes.join("\n")} return override; } } - if (file.impliedNodeFormat === void 0) - return void 0; + if (file.impliedNodeFormat === void 0) return void 0; if (file.impliedNodeFormat !== 99 /* ESNext */) { return isImportCall(walkUpParenthesizedExpressions(usage.parent)) ? 99 /* ESNext */ : 1 /* CommonJS */; } + const exprParentParent = (_a = walkUpParenthesizedExpressions(usage.parent)) == null ? void 0 : _a.parent; return exprParentParent && isImportEqualsDeclaration(exprParentParent) ? 1 /* CommonJS */ : 99 /* ESNext */; } + 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, - node.token === 118 /* WithKeyword */ ? Diagnostics.Type_import_attributes_should_have_exactly_one_key_resolution_mode_with_value_import_or_require : Diagnostics.Type_import_assertions_should_have_exactly_one_key_resolution_mode_with_value_import_or_require - ); + grammarErrorOnNode == null ? void 0 : grammarErrorOnNode(node, node.token === 118 /* WithKeyword */ ? Diagnostics.Type_import_attributes_should_have_exactly_one_key_resolution_mode_with_value_import_or_require : Diagnostics.Type_import_assertions_should_have_exactly_one_key_resolution_mode_with_value_import_or_require); 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, - node.token === 118 /* WithKeyword */ ? Diagnostics.resolution_mode_is_the_only_valid_key_for_type_import_attributes : Diagnostics.resolution_mode_is_the_only_valid_key_for_type_import_assertions - ); + grammarErrorOnNode == null ? void 0 : grammarErrorOnNode(elem.name, node.token === 118 /* WithKeyword */ ? Diagnostics.resolution_mode_is_the_only_valid_key_for_type_import_attributes : Diagnostics.resolution_mode_is_the_only_valid_key_for_type_import_assertions); 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; } return elem.value.text === "import" ? 99 /* ESNext */ : 1 /* CommonJS */; } + function getModuleResolutionName(literal) { return literal.text; } function createModuleResolutionLoader(containingFile, redirectedReference, options, host, cache) { return { nameAndMode: moduleResolutionNameAndModeGetter, - resolve: (moduleName, resolutionMode) => resolveModuleName( - moduleName, - containingFile, - options, - host, - cache, - redirectedReference, - resolutionMode - ) + resolve: (moduleName, resolutionMode) => resolveModuleName(moduleName, containingFile, options, host, cache, redirectedReference, resolutionMode) }; } function getTypeReferenceResolutionName(entry) { @@ -118934,22 +105545,13 @@ ${lanes.join("\n")} function createTypeReferenceResolutionLoader(containingFile, redirectedReference, options, host, cache) { return { nameAndMode: typeReferenceResolutionNameAndModeGetter, - resolve: (typeRef, resoluionMode) => resolveTypeReferenceDirective( - typeRef, - containingFile, - options, - host, - redirectedReference, - cache, - resoluionMode - ) + resolve: (typeRef, resoluionMode) => resolveTypeReferenceDirective(typeRef, containingFile, options, host, redirectedReference, cache, resoluionMode) }; } 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 cache = /* @__PURE__ */new Map(); const loader = createLoader(containingFile, redirectedReference, options, host, resolutionCache); for (const entry of entries) { const name = loader.nameAndMode.getName(entry); @@ -118964,35 +105566,25 @@ ${lanes.join("\n")} return resolutions; } function forEachResolvedProjectReference(resolvedProjectReferences, cb) { - return forEachProjectReference( - /*projectReferences*/ - void 0, - resolvedProjectReferences, - (resolvedRef, parent2) => resolvedRef && cb(resolvedRef, parent2) - ); + return forEachProjectReference( /*projectReferences*/ + void 0, resolvedProjectReferences, (resolvedRef, parent2) => resolvedRef && cb(resolvedRef, parent2)); } function forEachProjectReference(projectReferences, resolvedProjectReferences, cbResolvedRef, cbRef) { let seenResolvedRefs; - return worker( - projectReferences, - resolvedProjectReferences, - /*parent*/ - void 0 - ); + return worker(projectReferences, resolvedProjectReferences, /*parent*/ + void 0); 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; - (seenResolvedRefs || (seenResolvedRefs = /* @__PURE__ */ new Set())).add(resolvedRef.sourceFile.path); + if (result || !resolvedRef) return result; + (seenResolvedRefs || (seenResolvedRefs = /* @__PURE__ */new Set())).add(resolvedRef.sourceFile.path); return worker(resolvedRef.commandLine.projectReferences, resolvedRef.references, resolvedRef); }); } @@ -119014,7 +105606,10 @@ ${lanes.join("\n")} function getLibFileNameFromLibReference(libReference) { const libName = toFileNameLowerCase(libReference.fileName); const libFileName = libMap.get(libName); - return { libName, libFileName }; + return { + libName, + libFileName + }; } function isReferencedFile(reason) { switch (reason == null ? void 0 : reason.kind) { @@ -119033,51 +105628,64 @@ ${lanes.join("\n")} function getReferencedFileLocation(program, ref) { var _a, _b, _c, _d; const file = Debug.checkDefined(program.getSourceFileByPath(ref.file)); - const { kind, index } = ref; + const { + kind, + index + } = ref; let pos, end, packageId, resolutionMode; switch (kind) { case 3 /* Import */: const importLiteral = getModuleNameStringLiteralAt(file, index); packageId = (_b = (_a = program.getResolvedModule(file, importLiteral.text, getModeForResolutionAtIndex(file, index))) == null ? void 0 : _a.resolvedModule) == null ? void 0 : _b.packageId; - if (importLiteral.pos === -1) - return { file, packageId, text: importLiteral.text }; + if (importLiteral.pos === -1) return { + file, + packageId, + text: importLiteral.text + }; pos = skipTrivia(file.text, importLiteral.pos); end = importLiteral.end; break; case 4 /* ReferenceFile */: - ({ pos, end } = file.referencedFiles[index]); + ({ + pos, + end + } = file.referencedFiles[index]); break; case 5 /* TypeReferenceDirective */: - ({ pos, end, resolutionMode } = file.typeReferenceDirectives[index]); + ({ + 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; break; case 7 /* LibReferenceDirective */: - ({ pos, end } = file.libReferenceDirectives[index]); + ({ + pos, + end + } = file.libReferenceDirectives[index]); break; default: return Debug.assertNever(kind); } - return { file, pos, end, packageId }; + 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 (program.getMissingFilePaths().some(fileExists)) - return false; + if (!arrayIsEqualTo(program.getProjectReferences(), projectReferences, projectReferenceUptoDate)) return false; + if (program.getSourceFiles().some(sourceFileNotUptoDate)) return false; + if (program.getMissingFilePaths().some(fileExists)) return false; const currentOptions = program.getCompilerOptions(); - if (!compareDataObjects(currentOptions, newOptions)) - return false; - if (program.resolvedLibReferences && forEachEntry(program.resolvedLibReferences, (_value, libFileName) => hasInvalidatedLibResolutions(libFileName))) - return false; - if (currentOptions.configFile && newOptions.configFile) - return currentOptions.configFile.text === newOptions.configFile.text; + 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); @@ -119090,16 +105698,12 @@ ${lanes.join("\n")} } 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])); } @@ -119129,12 +105733,15 @@ ${lanes.join("\n")} state.affectingLocations = packageJsonLocations; const packageJsonScope = getPackageScopeForPath(fileName, state); const impliedNodeFormat = (packageJsonScope == null ? void 0 : packageJsonScope.contents.packageJsonContent.type) === "module" ? 99 /* ESNext */ : 1 /* CommonJS */; - return { impliedNodeFormat, packageJsonLocations, packageJsonScope }; + return { + impliedNodeFormat, + packageJsonLocations, + packageJsonScope + }; } } 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) { @@ -119150,8 +105757,16 @@ ${lanes.join("\n")} function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _configFileParsingDiagnostics) { var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p; const createProgramOptions = isArray(rootNamesOrOptions) ? createCreateProgramOptions(rootNamesOrOptions, _options, _host, _oldProgram, _configFileParsingDiagnostics) : rootNamesOrOptions; - const { rootNames, options, configFileParsingDiagnostics, projectReferences, typeScriptVersion: typeScriptVersion3 } = createProgramOptions; - let { oldProgram } = createProgramOptions; + const { + rootNames, + options, + configFileParsingDiagnostics, + projectReferences, + typeScriptVersion: typeScriptVersion3 + } = createProgramOptions; + let { + oldProgram + } = createProgramOptions; const reportInvalidIgnoreDeprecations = memoize(() => createOptionValueDiagnostic("ignoreDeprecations", Diagnostics.Invalid_value_for_ignoreDeprecations)); let processingDefaultLibFiles; let processingOtherFiles; @@ -119160,7 +105775,7 @@ ${lanes.join("\n")} let commonSourceDirectory; let typeChecker; let classifiableNames; - const ambientModuleNameToUnmodifiedFileName = /* @__PURE__ */ new Map(); + const ambientModuleNameToUnmodifiedFileName = /* @__PURE__ */new Map(); let fileReasons = createMultiMap(); const cachedBindAndCheckDiagnosticsForFile = {}; const cachedDeclarationDiagnosticsForFile = {}; @@ -119177,15 +105792,13 @@ ${lanes.join("\n")} let packageMap; const maxNodeModuleJsDepth = typeof options.maxNodeModuleJsDepth === "number" ? options.maxNodeModuleJsDepth : 0; let currentNodeModulesDepth = 0; - const modulesWithElidedImports = /* @__PURE__ */ new Map(); - const sourceFilesFoundSearchingNodeModules = /* @__PURE__ */ new Map(); - (_a = tracing) == null ? void 0 : _a.push( - tracing.Phase.Program, - "createProgram", - { configFilePath: options.configFilePath, rootDir: options.rootDir }, - /*separateBeginAndEnd*/ - true - ); + const modulesWithElidedImports = /* @__PURE__ */new Map(); + const sourceFilesFoundSearchingNodeModules = /* @__PURE__ */new Map(); + (_a = tracing) == null ? void 0 : _a.push(tracing.Phase.Program, "createProgram", { + configFilePath: options.configFilePath, + rootDir: options.rootDir + }, /*separateBeginAndEnd*/ + true); mark("beforeProgram"); const host = createProgramOptions.host || createCompilerHost(options); const configParsingHost = parseConfigHostFromCompilerHostLike(host); @@ -119196,7 +105809,7 @@ ${lanes.join("\n")} const currentDirectory = host.getCurrentDirectory(); const supportedExtensions = getSupportedExtensions(options); const supportedExtensionsWithJsonIfResolveJsonModule = getSupportedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions); - const hasEmitBlockingDiagnostics = /* @__PURE__ */ new Map(); + const hasEmitBlockingDiagnostics = /* @__PURE__ */new Map(); let _compilerOptionsObjectLiteralSyntax; let moduleResolutionCache; let actualResolveModuleNamesWorker; @@ -119205,63 +105818,32 @@ ${lanes.join("\n")} actualResolveModuleNamesWorker = host.resolveModuleNameLiterals.bind(host); moduleResolutionCache = (_b = host.getModuleResolutionCache) == null ? void 0 : _b.call(host); } else if (host.resolveModuleNames) { - actualResolveModuleNamesWorker = (moduleNames, containingFile, redirectedReference, options2, containingSourceFile, reusedNames) => host.resolveModuleNames( - moduleNames.map(getModuleResolutionName), - containingFile, - reusedNames == null ? void 0 : reusedNames.map(getModuleResolutionName), - redirectedReference, - options2, - containingSourceFile - ).map( - (resolved) => resolved ? resolved.extension !== void 0 ? { resolvedModule: resolved } : ( - // An older host may have omitted extension, in which case we should infer it from the file extension of resolvedFileName. - { resolvedModule: { ...resolved, extension: extensionFromPath(resolved.resolvedFileName) } } - ) : emptyResolution - ); + actualResolveModuleNamesWorker = (moduleNames, containingFile, redirectedReference, options2, containingSourceFile, reusedNames) => host.resolveModuleNames(moduleNames.map(getModuleResolutionName), containingFile, reusedNames == null ? void 0 : reusedNames.map(getModuleResolutionName), redirectedReference, options2, containingSourceFile).map(resolved => resolved ? resolved.extension !== void 0 ? { + resolvedModule: resolved + } : + // An older host may have omitted extension, in which case we should infer it from the file extension of resolvedFileName. + { + resolvedModule: { + ...resolved, + extension: extensionFromPath(resolved.resolvedFileName) + } + } : emptyResolution); moduleResolutionCache = (_c = host.getModuleResolutionCache) == null ? void 0 : _c.call(host); } else { moduleResolutionCache = createModuleResolutionCache(currentDirectory, getCanonicalFileName, options); - actualResolveModuleNamesWorker = (moduleNames, containingFile, redirectedReference, options2, containingSourceFile) => loadWithModeAwareCache( - moduleNames, - containingFile, - redirectedReference, - options2, - containingSourceFile, - host, - moduleResolutionCache, - createModuleResolutionLoader - ); + actualResolveModuleNamesWorker = (moduleNames, containingFile, redirectedReference, options2, containingSourceFile) => loadWithModeAwareCache(moduleNames, containingFile, redirectedReference, options2, containingSourceFile, host, moduleResolutionCache, createModuleResolutionLoader); } let actualResolveTypeReferenceDirectiveNamesWorker; if (host.resolveTypeReferenceDirectiveReferences) { actualResolveTypeReferenceDirectiveNamesWorker = host.resolveTypeReferenceDirectiveReferences.bind(host); } else if (host.resolveTypeReferenceDirectives) { - actualResolveTypeReferenceDirectiveNamesWorker = (typeDirectiveNames, containingFile, redirectedReference, options2, containingSourceFile) => host.resolveTypeReferenceDirectives( - typeDirectiveNames.map(getTypeReferenceResolutionName), - containingFile, - redirectedReference, - options2, - containingSourceFile == null ? void 0 : containingSourceFile.impliedNodeFormat - ).map((resolvedTypeReferenceDirective) => ({ resolvedTypeReferenceDirective })); + actualResolveTypeReferenceDirectiveNamesWorker = (typeDirectiveNames, containingFile, redirectedReference, options2, containingSourceFile) => host.resolveTypeReferenceDirectives(typeDirectiveNames.map(getTypeReferenceResolutionName), containingFile, redirectedReference, options2, containingSourceFile == null ? void 0 : containingSourceFile.impliedNodeFormat).map(resolvedTypeReferenceDirective => ({ + resolvedTypeReferenceDirective + })); } else { - const typeReferenceDirectiveResolutionCache = createTypeReferenceDirectiveResolutionCache( - currentDirectory, - getCanonicalFileName, - /*options*/ - void 0, - moduleResolutionCache == null ? void 0 : moduleResolutionCache.getPackageJsonInfoCache(), - moduleResolutionCache == null ? void 0 : moduleResolutionCache.optionsToRedirectsKey - ); - actualResolveTypeReferenceDirectiveNamesWorker = (typeDirectiveNames, containingFile, redirectedReference, options2, containingSourceFile) => loadWithModeAwareCache( - typeDirectiveNames, - containingFile, - redirectedReference, - options2, - containingSourceFile, - host, - typeReferenceDirectiveResolutionCache, - createTypeReferenceResolutionLoader - ); + const typeReferenceDirectiveResolutionCache = createTypeReferenceDirectiveResolutionCache(currentDirectory, getCanonicalFileName, /*options*/ + void 0, moduleResolutionCache == null ? void 0 : moduleResolutionCache.getPackageJsonInfoCache(), moduleResolutionCache == null ? void 0 : moduleResolutionCache.optionsToRedirectsKey); + actualResolveTypeReferenceDirectiveNamesWorker = (typeDirectiveNames, containingFile, redirectedReference, options2, containingSourceFile) => loadWithModeAwareCache(typeDirectiveNames, containingFile, redirectedReference, options2, containingSourceFile, host, typeReferenceDirectiveResolutionCache, createTypeReferenceResolutionLoader); } const hasInvalidatedLibResolutions = host.hasInvalidatedLibResolutions || returnFalse; let actualResolveLibrary; @@ -119271,19 +105853,23 @@ ${lanes.join("\n")} const libraryResolutionCache = createModuleResolutionCache(currentDirectory, getCanonicalFileName, options, moduleResolutionCache == null ? void 0 : moduleResolutionCache.getPackageJsonInfoCache()); actualResolveLibrary = (libraryName, resolveFrom, options2) => resolveLibrary(libraryName, resolveFrom, options2, host, libraryResolutionCache); } - const packageIdToSourceFile = /* @__PURE__ */ new Map(); - let sourceFileToPackageName = /* @__PURE__ */ new Map(); + const packageIdToSourceFile = /* @__PURE__ */new Map(); + let sourceFileToPackageName = /* @__PURE__ */new Map(); let redirectTargetsMap = createMultiMap(); let usesUriStyleNodeCoreModules = false; - const filesByName = /* @__PURE__ */ new Map(); + const filesByName = /* @__PURE__ */new Map(); let missingFilePaths; - const filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? /* @__PURE__ */ new Map() : void 0; + const filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? /* @__PURE__ */new Map() : void 0; let resolvedProjectReferences; let projectReferenceRedirects; let mapFromFileToProjectReferenceRedirects; let mapFromToProjectReferenceRedirectSource; const useSourceOfProjectReferenceRedirect = !!((_d = host.useSourceOfProjectReferenceRedirect) == null ? void 0 : _d.call(host)) && !options.disableSourceOfProjectReferenceRedirect; - const { onProgramCreateComplete, fileExists, directoryExists } = updateHostForUseSourceOfProjectReferenceRedirect({ + const { + onProgramCreateComplete, + fileExists, + directoryExists + } = updateHostForUseSourceOfProjectReferenceRedirect({ compilerHost: host, getSymlinkCache, useSourceOfProjectReferenceRedirect, @@ -119293,7 +105879,9 @@ ${lanes.join("\n")} forEachResolvedProjectReference: forEachResolvedProjectReference2 }); const readFile = host.readFile.bind(host); - (_e = tracing) == null ? void 0 : _e.push(tracing.Phase.Program, "shouldProgramCreateNewSourceFiles", { hasOldProgram: !!oldProgram }); + (_e = tracing) == null ? void 0 : _e.push(tracing.Phase.Program, "shouldProgramCreateNewSourceFiles", { + hasOldProgram: !!oldProgram + }); const shouldCreateNewSourceFile = shouldProgramCreateNewSourceFiles(oldProgram, options); (_f = tracing) == null ? void 0 : _f.pop(); let structureIsReused; @@ -119301,6 +105889,7 @@ ${lanes.join("\n")} structureIsReused = tryReuseStructureFromOldProgram(); (_h = tracing) == null ? void 0 : _h.pop(); if (structureIsReused !== 2 /* Completely */) { + var _automaticTypeDirecti; processingDefaultLibFiles = []; processingOtherFiles = []; if (projectReferences) { @@ -119309,23 +105898,31 @@ ${lanes.join("\n")} } if (rootNames.length) { resolvedProjectReferences == null ? void 0 : resolvedProjectReferences.forEach((parsedRef, index) => { - if (!parsedRef) - return; + if (!parsedRef) return; const out = outFile(parsedRef.commandLine.options); if (useSourceOfProjectReferenceRedirect) { if (out || getEmitModuleKind(parsedRef.commandLine.options) === 0 /* None */) { for (const fileName of parsedRef.commandLine.fileNames) { - processProjectReferenceFile(fileName, { kind: 1 /* SourceFromProjectReference */, index }); + processProjectReferenceFile(fileName, { + kind: 1 /* SourceFromProjectReference */, + index + }); } } } else { if (out) { - processProjectReferenceFile(changeExtension(out, ".d.ts"), { kind: 2 /* OutputFromProjectReference */, index }); + processProjectReferenceFile(changeExtension(out, ".d.ts"), { + kind: 2 /* OutputFromProjectReference */, + index + }); } else if (getEmitModuleKind(parsedRef.commandLine.options) === 0 /* None */) { const getCommonSourceDirectory3 = memoize(() => getCommonSourceDirectoryOfConfig(parsedRef.commandLine, !host.useCaseSensitiveFileNames())); for (const fileName of parsedRef.commandLine.fileNames) { if (!isDeclarationFileName(fileName) && !fileExtensionIs(fileName, ".json" /* Json */)) { - processProjectReferenceFile(getOutputDeclarationFileName(fileName, parsedRef.commandLine, !host.useCaseSensitiveFileNames(), getCommonSourceDirectory3), { kind: 2 /* OutputFromProjectReference */, index }); + processProjectReferenceFile(getOutputDeclarationFileName(fileName, parsedRef.commandLine, !host.useCaseSensitiveFileNames(), getCommonSourceDirectory3), { + kind: 2 /* OutputFromProjectReference */, + index + }); } } } @@ -119333,65 +105930,53 @@ ${lanes.join("\n")} }); } } - (_i = tracing) == null ? void 0 : _i.push(tracing.Phase.Program, "processRootFiles", { count: rootNames.length }); - forEach(rootNames, (name, index) => processRootFile( - name, - /*isDefaultLib*/ - false, - /*ignoreNoDefaultLib*/ - false, - { kind: 0 /* RootFile */, index } - )); + (_i = tracing) == null ? void 0 : _i.push(tracing.Phase.Program, "processRootFiles", { + count: rootNames.length + }); + forEach(rootNames, (name, index) => processRootFile(name, /*isDefaultLib*/ + false, /*ignoreNoDefaultLib*/ + false, { + kind: 0 /* RootFile */, + index + })); (_j = tracing) == null ? void 0 : _j.pop(); - automaticTypeDirectiveNames ?? (automaticTypeDirectiveNames = rootNames.length ? getAutomaticTypeDirectiveNames(options, host) : emptyArray); + (_automaticTypeDirecti = automaticTypeDirectiveNames) !== null && _automaticTypeDirecti !== void 0 ? _automaticTypeDirecti : automaticTypeDirectiveNames = rootNames.length ? getAutomaticTypeDirectiveNames(options, host) : emptyArray; automaticTypeDirectiveResolutions = createModeAwareCache(); if (automaticTypeDirectiveNames.length) { - (_k = tracing) == null ? void 0 : _k.push(tracing.Phase.Program, "processTypeReferences", { count: automaticTypeDirectiveNames.length }); + (_k = tracing) == null ? void 0 : _k.push(tracing.Phase.Program, "processTypeReferences", { + count: automaticTypeDirectiveNames.length + }); const containingDirectory = options.configFilePath ? getDirectoryPath(options.configFilePath) : currentDirectory; const containingFilename = combinePaths(containingDirectory, inferredTypesContainingFile); const resolutions = resolveTypeReferenceDirectiveNamesReusingOldState(automaticTypeDirectiveNames, containingFilename); for (let i = 0; i < automaticTypeDirectiveNames.length; i++) { - automaticTypeDirectiveResolutions.set( - automaticTypeDirectiveNames[i], - /*mode*/ - void 0, - resolutions[i] - ); - processTypeReferenceDirective( - automaticTypeDirectiveNames[i], - /*mode*/ - void 0, - resolutions[i], - { - kind: 8 /* AutomaticTypeDirectiveFile */, - typeReference: automaticTypeDirectiveNames[i], - packageId: (_m = (_l = resolutions[i]) == null ? void 0 : _l.resolvedTypeReferenceDirective) == null ? void 0 : _m.packageId - } - ); + automaticTypeDirectiveResolutions.set(automaticTypeDirectiveNames[i], /*mode*/ + void 0, resolutions[i]); + processTypeReferenceDirective(automaticTypeDirectiveNames[i], /*mode*/ + void 0, resolutions[i], { + kind: 8 /* AutomaticTypeDirectiveFile */, + typeReference: automaticTypeDirectiveNames[i], + packageId: (_m = (_l = resolutions[i]) == null ? void 0 : _l.resolvedTypeReferenceDirective) == null ? void 0 : _m.packageId + }); } (_n = tracing) == null ? void 0 : _n.pop(); } if (rootNames.length && !skipDefaultLib) { const defaultLibraryFileName = getDefaultLibraryFileName(); if (!options.lib && defaultLibraryFileName) { - processRootFile( - defaultLibraryFileName, - /*isDefaultLib*/ - true, - /*ignoreNoDefaultLib*/ - false, - { kind: 6 /* LibFile */ } - ); + processRootFile(defaultLibraryFileName, /*isDefaultLib*/ + true, /*ignoreNoDefaultLib*/ + false, { + kind: 6 /* LibFile */ + }); } else { forEach(options.lib, (libFileName, index) => { - processRootFile( - pathForLibFile(libFileName), - /*isDefaultLib*/ - true, - /*ignoreNoDefaultLib*/ - false, - { kind: 6 /* LibFile */, index } - ); + processRootFile(pathForLibFile(libFileName), /*isDefaultLib*/ + true, /*ignoreNoDefaultLib*/ + false, { + kind: 6 /* LibFile */, + index + }); }); } } @@ -119405,36 +105990,29 @@ ${lanes.join("\n")} const oldSourceFiles = oldProgram.getSourceFiles(); for (const oldSourceFile of oldSourceFiles) { const newFile = getSourceFileByPath(oldSourceFile.resolvedPath); - if (shouldCreateNewSourceFile || !newFile || newFile.impliedNodeFormat !== oldSourceFile.impliedNodeFormat || // old file wasn't redirect but new file is + if (shouldCreateNewSourceFile || !newFile || newFile.impliedNodeFormat !== oldSourceFile.impliedNodeFormat || + // old file wasn't redirect but new file is oldSourceFile.resolvedPath === oldSourceFile.path && newFile.resolvedPath !== oldSourceFile.path) { host.onReleaseOldSourceFile(oldSourceFile, oldProgram.getCompilerOptions(), !!getSourceFileByPath(oldSourceFile.path)); } } if (!host.getParsedCommandLine) { - oldProgram.forEachResolvedProjectReference((resolvedProjectReference) => { + oldProgram.forEachResolvedProjectReference(resolvedProjectReference => { if (!getResolvedProjectReferenceByPath(resolvedProjectReference.sourceFile.path)) { - host.onReleaseOldSourceFile( - resolvedProjectReference.sourceFile, - oldProgram.getCompilerOptions(), - /*hasSourceFileByPath*/ - false - ); + host.onReleaseOldSourceFile(resolvedProjectReference.sourceFile, oldProgram.getCompilerOptions(), /*hasSourceFileByPath*/ + false); } }); } } if (oldProgram && host.onReleaseParsedCommandLine) { - forEachProjectReference( - oldProgram.getProjectReferences(), - oldProgram.getResolvedProjectReferences(), - (oldResolvedRef, parent2, index) => { - const oldReference = (parent2 == null ? void 0 : parent2.commandLine.projectReferences[index]) || oldProgram.getProjectReferences()[index]; - const oldRefPath = resolveProjectReferencePath(oldReference); - if (!(projectReferenceRedirects == null ? void 0 : projectReferenceRedirects.has(toPath3(oldRefPath)))) { - host.onReleaseParsedCommandLine(oldRefPath, oldResolvedRef, oldProgram.getCompilerOptions()); - } + forEachProjectReference(oldProgram.getProjectReferences(), oldProgram.getResolvedProjectReferences(), (oldResolvedRef, parent2, index) => { + const oldReference = (parent2 == null ? void 0 : parent2.commandLine.projectReferences[index]) || oldProgram.getProjectReferences()[index]; + const oldRefPath = resolveProjectReferencePath(oldReference); + if (!(projectReferenceRedirects == null ? void 0 : projectReferenceRedirects.has(toPath3(oldRefPath)))) { + host.onReleaseParsedCommandLine(oldRefPath, oldResolvedRef, oldProgram.getCompilerOptions()); } - ); + }); } oldProgram = void 0; resolvedLibProcessing = void 0; @@ -119513,15 +106091,19 @@ ${lanes.join("\n")} writeFile: writeFile2 }; onProgramCreateComplete(); - fileProcessingDiagnostics == null ? void 0 : fileProcessingDiagnostics.forEach((diagnostic) => { + 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)); + 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)); + return diagnostic.diagnostics.forEach(d => programDiagnostics.add(d)); default: Debug.assertNever(diagnostic); } @@ -119547,18 +106129,15 @@ ${lanes.join("\n")} } 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; - 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 (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)); }); return packageMap; } @@ -119569,33 +106148,31 @@ ${lanes.join("\n")} return !!getPackagesMap().get(packageName); } function addResolutionDiagnostics(resolution) { + var _fileProcessingDiagno; var _a2; - if (!((_a2 = resolution.resolutionDiagnostics) == null ? void 0 : _a2.length)) - return; - (fileProcessingDiagnostics ?? (fileProcessingDiagnostics = [])).push({ + if (!((_a2 = resolution.resolutionDiagnostics) == null ? void 0 : _a2.length)) return; + ((_fileProcessingDiagno = fileProcessingDiagnostics) !== null && _fileProcessingDiagno !== void 0 ? _fileProcessingDiagno : 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 }); + (_a2 = tracing) == null ? void 0 : _a2.push(tracing.Phase.Program, "resolveModuleNamesWorker", { + containingFileName + }); mark("beforeResolveModule"); const result = actualResolveModuleNamesWorker(moduleNames, containingFileName, redirectedReference, options, containingFile, reusedNames); mark("afterResolveModule"); @@ -119605,12 +106182,13 @@ ${lanes.join("\n")} } 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); - (_a2 = tracing) == null ? void 0 : _a2.push(tracing.Phase.Program, "resolveTypeReferenceDirectiveNamesWorker", { containingFileName }); + (_a2 = tracing) == null ? void 0 : _a2.push(tracing.Phase.Program, "resolveTypeReferenceDirectiveNamesWorker", { + containingFileName + }); mark("beforeResolveTypeReference"); const result = actualResolveTypeReferenceDirectiveNamesWorker(typeDirectiveNames, containingFileName, redirectedReference, options, containingSourceFile, reusedNames); mark("afterResolveTypeReference"); @@ -119620,26 +106198,20 @@ ${lanes.join("\n")} } 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; - return forEachResolvedProjectReference2((resolvedRef) => { + if (isString(source)) return getResolvedProjectReferenceToRedirect(source); + if (!source) return void 0; + return forEachResolvedProjectReference2(resolvedRef => { const out = outFile(resolvedRef.commandLine.options); - if (!out) - return void 0; + if (!out) return void 0; return toPath3(out) === filePath ? resolvedRef : void 0; }); } @@ -119647,19 +106219,13 @@ ${lanes.join("\n")} return compareValues(getDefaultLibFilePriority(a), getDefaultLibFilePriority(b)); } function getDefaultLibFilePriority(a) { - if (containsPath( - defaultLibraryPath, - a.fileName, - /*ignoreCase*/ - false - )) { + if (containsPath(defaultLibraryPath, a.fileName, /*ignoreCase*/ + 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; } @@ -119668,14 +106234,8 @@ ${lanes.join("\n")} } function getCommonSourceDirectory2() { if (commonSourceDirectory === void 0) { - const emittedFiles = filter(files, (file) => sourceFileMayBeEmitted(file, program)); - commonSourceDirectory = getCommonSourceDirectory( - options, - () => mapDefined(emittedFiles, (file) => file.isDeclarationFile ? void 0 : file.fileName), - currentDirectory, - getCanonicalFileName, - (commonSourceDirectory2) => checkSourceFilesBelongToPath(emittedFiles, commonSourceDirectory2) - ); + const emittedFiles = filter(files, file => sourceFileMayBeEmitted(file, program)); + commonSourceDirectory = getCommonSourceDirectory(options, () => mapDefined(emittedFiles, file => file.isDeclarationFile ? void 0 : file.fileName), currentDirectory, getCanonicalFileName, commonSourceDirectory2 => checkSourceFilesBelongToPath(emittedFiles, commonSourceDirectory2)); } return commonSourceDirectory; } @@ -119683,21 +106243,17 @@ ${lanes.join("\n")} var _a2; if (!classifiableNames) { getTypeChecker(); - classifiableNames = /* @__PURE__ */ new Set(); + classifiableNames = /* @__PURE__ */new Set(); for (const sourceFile of files) { - (_a2 = sourceFile.classifiableNames) == null ? void 0 : _a2.forEach((value) => classifiableNames.add(value)); + (_a2 = sourceFile.classifiableNames) == null ? void 0 : _a2.forEach(value => classifiableNames.add(value)); } } return classifiableNames; } function resolveModuleNamesReusingOldState(moduleNames, file) { if (structureIsReused === 0 /* Not */ && !file.ambientModuleNames.length) { - return resolveModuleNamesWorker( - moduleNames, - file, - /*reusedNames*/ - void 0 - ); + return resolveModuleNamesWorker(moduleNames, file, /*reusedNames*/ + void 0); } let unknownModuleNames; let result; @@ -119710,18 +106266,12 @@ ${lanes.join("\n")} const mode = getModeForUsageLocation(file, moduleName); const oldResolution = oldProgram == null ? void 0 : oldProgram.getResolvedModule(file, moduleName.text, mode); if (oldResolution == null ? void 0 : oldResolution.resolvedModule) { + var _result3, _reusedNames; if (isTraceEnabled(options, host)) { - trace( - host, - oldResolution.resolvedModule.packageId ? Diagnostics.Reusing_resolution_of_module_0_from_1_of_old_program_it_was_successfully_resolved_to_2_with_Package_ID_3 : Diagnostics.Reusing_resolution_of_module_0_from_1_of_old_program_it_was_successfully_resolved_to_2, - moduleName.text, - getNormalizedAbsolutePath(file.originalFileName, currentDirectory), - oldResolution.resolvedModule.resolvedFileName, - oldResolution.resolvedModule.packageId && packageIdToString(oldResolution.resolvedModule.packageId) - ); + trace(host, oldResolution.resolvedModule.packageId ? Diagnostics.Reusing_resolution_of_module_0_from_1_of_old_program_it_was_successfully_resolved_to_2_with_Package_ID_3 : Diagnostics.Reusing_resolution_of_module_0_from_1_of_old_program_it_was_successfully_resolved_to_2, moduleName.text, getNormalizedAbsolutePath(file.originalFileName, currentDirectory), oldResolution.resolvedModule.resolvedFileName, oldResolution.resolvedModule.packageId && packageIdToString(oldResolution.resolvedModule.packageId)); } - (result ?? (result = new Array(moduleNames.length)))[i] = oldResolution; - (reusedNames ?? (reusedNames = [])).push(moduleName); + ((_result3 = result) !== null && _result3 !== void 0 ? _result3 : result = new Array(moduleNames.length))[i] = oldResolution; + ((_reusedNames = reusedNames) !== null && _reusedNames !== void 0 ? _reusedNames : reusedNames = []).push(moduleName); continue; } } @@ -119737,7 +106287,8 @@ ${lanes.join("\n")} if (resolvesToAmbientModuleInNonModifiedFile) { (result || (result = new Array(moduleNames.length)))[i] = predictedToResolveToAmbientModuleMarker; } else { - (unknownModuleNames ?? (unknownModuleNames = [])).push(moduleName); + var _unknownModuleNames; + ((_unknownModuleNames = unknownModuleNames) !== null && _unknownModuleNames !== void 0 ? _unknownModuleNames : unknownModuleNames = []).push(moduleName); } } const resolutions = unknownModuleNames && unknownModuleNames.length ? resolveModuleNamesWorker(unknownModuleNames, file, reusedNames) : emptyArray; @@ -119774,12 +106325,8 @@ ${lanes.join("\n")} function resolveTypeReferenceDirectiveNamesReusingOldState(typeDirectiveNames, containingFile) { var _a2; if (structureIsReused === 0 /* Not */) { - return resolveTypeReferenceDirectiveNamesWorker( - typeDirectiveNames, - containingFile, - /*reusedNames*/ - void 0 - ); + return resolveTypeReferenceDirectiveNamesWorker(typeDirectiveNames, containingFile, /*reusedNames*/ + void 0); } let unknownTypeReferenceDirectiveNames; let result; @@ -119788,36 +106335,26 @@ ${lanes.join("\n")} const oldSourceFile = !isString(containingFile) ? oldProgram && oldProgram.getSourceFile(containingFile.fileName) : void 0; const canReuseResolutions = !isString(containingFile) ? containingFile === oldSourceFile && !hasInvalidatedResolutions(containingFile.path) : !hasInvalidatedResolutions(toPath3(containingFile)); for (let i = 0; i < typeDirectiveNames.length; i++) { + var _unknownTypeReference; const entry = typeDirectiveNames[i]; if (canReuseResolutions) { const typeDirectiveName = getTypeReferenceResolutionName(entry); const mode = getModeForFileReference(entry, containingSourceFile == null ? void 0 : containingSourceFile.impliedNodeFormat); const oldResolution = !isString(containingFile) ? oldProgram == null ? void 0 : oldProgram.getResolvedTypeReferenceDirective(containingFile, typeDirectiveName, mode) : (_a2 = oldProgram == null ? void 0 : oldProgram.getAutomaticTypeDirectiveResolutions()) == null ? void 0 : _a2.get(typeDirectiveName, mode); if (oldResolution == null ? void 0 : oldResolution.resolvedTypeReferenceDirective) { + var _result4, _reusedNames2; if (isTraceEnabled(options, host)) { - trace( - host, - oldResolution.resolvedTypeReferenceDirective.packageId ? Diagnostics.Reusing_resolution_of_type_reference_directive_0_from_1_of_old_program_it_was_successfully_resolved_to_2_with_Package_ID_3 : Diagnostics.Reusing_resolution_of_type_reference_directive_0_from_1_of_old_program_it_was_successfully_resolved_to_2, - typeDirectiveName, - !isString(containingFile) ? getNormalizedAbsolutePath(containingFile.originalFileName, currentDirectory) : containingFile, - oldResolution.resolvedTypeReferenceDirective.resolvedFileName, - oldResolution.resolvedTypeReferenceDirective.packageId && packageIdToString(oldResolution.resolvedTypeReferenceDirective.packageId) - ); + trace(host, oldResolution.resolvedTypeReferenceDirective.packageId ? Diagnostics.Reusing_resolution_of_type_reference_directive_0_from_1_of_old_program_it_was_successfully_resolved_to_2_with_Package_ID_3 : Diagnostics.Reusing_resolution_of_type_reference_directive_0_from_1_of_old_program_it_was_successfully_resolved_to_2, typeDirectiveName, !isString(containingFile) ? getNormalizedAbsolutePath(containingFile.originalFileName, currentDirectory) : containingFile, oldResolution.resolvedTypeReferenceDirective.resolvedFileName, oldResolution.resolvedTypeReferenceDirective.packageId && packageIdToString(oldResolution.resolvedTypeReferenceDirective.packageId)); } - (result ?? (result = new Array(typeDirectiveNames.length)))[i] = oldResolution; - (reusedNames ?? (reusedNames = [])).push(entry); + ((_result4 = result) !== null && _result4 !== void 0 ? _result4 : result = new Array(typeDirectiveNames.length))[i] = oldResolution; + ((_reusedNames2 = reusedNames) !== null && _reusedNames2 !== void 0 ? _reusedNames2 : reusedNames = []).push(entry); continue; } } - (unknownTypeReferenceDirectiveNames ?? (unknownTypeReferenceDirectiveNames = [])).push(entry); + ((_unknownTypeReference = unknownTypeReferenceDirectiveNames) !== null && _unknownTypeReference !== void 0 ? _unknownTypeReference : unknownTypeReferenceDirectiveNames = []).push(entry); } - if (!unknownTypeReferenceDirectiveNames) - return result || emptyArray; - const resolutions = resolveTypeReferenceDirectiveNamesWorker( - unknownTypeReferenceDirectiveNames, - containingFile, - reusedNames - ); + if (!unknownTypeReferenceDirectiveNames) return result || emptyArray; + const resolutions = resolveTypeReferenceDirectiveNamesWorker(unknownTypeReferenceDirectiveNames, containingFile, reusedNames); if (!result) { Debug.assert(resolutions.length === typeDirectiveNames.length); return resolutions; @@ -119833,75 +106370,65 @@ ${lanes.join("\n")} return result; } function canReuseProjectReferences() { - return !forEachProjectReference( - oldProgram.getProjectReferences(), - oldProgram.getResolvedProjectReferences(), - (oldResolvedRef, parent2, index) => { - const newRef = (parent2 ? parent2.commandLine.projectReferences : projectReferences)[index]; - const newResolvedRef = parseProjectReferenceConfigFile(newRef); - if (oldResolvedRef) { - return !newResolvedRef || newResolvedRef.sourceFile !== oldResolvedRef.sourceFile || !arrayIsEqualTo(oldResolvedRef.commandLine.fileNames, newResolvedRef.commandLine.fileNames); - } else { - return newResolvedRef !== void 0; - } - }, - (oldProjectReferences, parent2) => { - const newReferences = parent2 ? getResolvedProjectReferenceByPath(parent2.sourceFile.path).commandLine.projectReferences : projectReferences; - return !arrayIsEqualTo(oldProjectReferences, newReferences, projectReferenceIsEqualTo); + return !forEachProjectReference(oldProgram.getProjectReferences(), oldProgram.getResolvedProjectReferences(), (oldResolvedRef, parent2, index) => { + const newRef = (parent2 ? parent2.commandLine.projectReferences : projectReferences)[index]; + const newResolvedRef = parseProjectReferenceConfigFile(newRef); + if (oldResolvedRef) { + return !newResolvedRef || newResolvedRef.sourceFile !== oldResolvedRef.sourceFile || !arrayIsEqualTo(oldResolvedRef.commandLine.fileNames, newResolvedRef.commandLine.fileNames); + } else { + return newResolvedRef !== void 0; } - ); + }, (oldProjectReferences, parent2) => { + const newReferences = parent2 ? getResolvedProjectReferenceByPath(parent2.sourceFile.path).commandLine.projectReferences : projectReferences; + return !arrayIsEqualTo(oldProjectReferences, newReferences, projectReferenceIsEqualTo); + }); } function tryReuseStructureFromOldProgram() { var _a2; if (!oldProgram) { return 0 /* Not */; } + const oldOptions = oldProgram.getCompilerOptions(); if (changesAffectModuleResolution(oldOptions, options)) { return 0 /* Not */; } + const oldRootNames = oldProgram.getRootFileNames(); if (!arrayIsEqualTo(oldRootNames, rootNames)) { return 0 /* Not */; } + if (!canReuseProjectReferences()) { return 0 /* Not */; } + if (projectReferences) { resolvedProjectReferences = projectReferences.map(parseProjectReferenceConfigFile); } const newSourceFiles = []; const modifiedSourceFiles = []; structureIsReused = 2 /* Completely */; - if (oldProgram.getMissingFilePaths().some((missingFilePath) => host.fileExists(missingFilePath))) { + if (oldProgram.getMissingFilePaths().some(missingFilePath => host.fileExists(missingFilePath))) { return 0 /* Not */; } + const oldSourceFiles = oldProgram.getSourceFiles(); let SeenPackageName; - ((SeenPackageName2) => { + (SeenPackageName2 => { SeenPackageName2[SeenPackageName2["Exists"] = 0] = "Exists"; SeenPackageName2[SeenPackageName2["Modified"] = 1] = "Modified"; })(SeenPackageName || (SeenPackageName = {})); - const seenPackageNames = /* @__PURE__ */ new Map(); + const seenPackageNames = /* @__PURE__ */new Map(); for (const oldSourceFile of oldSourceFiles) { const sourceFileOptions = getCreateSourceFileOptions(oldSourceFile.fileName, moduleResolutionCache, host, options); - let newSourceFile = host.getSourceFileByPath ? host.getSourceFileByPath( - oldSourceFile.fileName, - oldSourceFile.resolvedPath, - sourceFileOptions, - /*onError*/ - void 0, - shouldCreateNewSourceFile - ) : host.getSourceFile( - oldSourceFile.fileName, - sourceFileOptions, - /*onError*/ - void 0, - shouldCreateNewSourceFile - ); + let newSourceFile = host.getSourceFileByPath ? host.getSourceFileByPath(oldSourceFile.fileName, oldSourceFile.resolvedPath, sourceFileOptions, /*onError*/ + void 0, shouldCreateNewSourceFile) : host.getSourceFile(oldSourceFile.fileName, sourceFileOptions, /*onError*/ + void 0, shouldCreateNewSourceFile); if (!newSourceFile) { return 0 /* Not */; } + newSourceFile.packageJsonLocations = ((_a2 = sourceFileOptions.packageJsonLocations) == null ? void 0 : _a2.length) ? sourceFileOptions.packageJsonLocations : void 0; newSourceFile.packageJsonScope = sourceFileOptions.packageJsonScope; Debug.assert(!newSourceFile.redirectInfo, "Host should not return a redirect source file from `getSourceFile`"); @@ -119910,12 +106437,14 @@ ${lanes.join("\n")} if (newSourceFile !== oldSourceFile.redirectInfo.unredirected) { return 0 /* Not */; } + fileChanged = false; newSourceFile = oldSourceFile; } else if (oldProgram.redirectTargetsMap.has(oldSourceFile.path)) { if (newSourceFile !== oldSourceFile) { return 0 /* Not */; } + fileChanged = false; } else { fileChanged = newSourceFile !== oldSourceFile; @@ -119931,6 +106460,7 @@ ${lanes.join("\n")} if (prevKind !== void 0 && newKind === 1 /* Modified */ || prevKind === 1 /* Modified */) { return 0 /* Not */; } + seenPackageNames.set(packageName, newKind); } if (fileChanged) { @@ -119954,6 +106484,7 @@ ${lanes.join("\n")} structureIsReused = 1 /* SafeModules */; } } + modifiedSourceFiles.push(newSourceFile); } else if (hasInvalidatedResolutions(oldSourceFile.path)) { structureIsReused = 1 /* SafeModules */; @@ -119969,50 +106500,37 @@ ${lanes.join("\n")} return structureIsReused; } for (const newSourceFile of modifiedSourceFiles) { + var _resolvedModulesProce, _resolvedTypeReferenc; const moduleNames = getModuleNames(newSourceFile); const resolutions = resolveModuleNamesReusingOldState(moduleNames, newSourceFile); - (resolvedModulesProcessing ?? (resolvedModulesProcessing = /* @__PURE__ */ new Map())).set(newSourceFile.path, resolutions); - const resolutionsChanged = hasChangesInResolutions( - moduleNames, - newSourceFile, - resolutions, - (name, mode) => oldProgram.getResolvedModule(newSourceFile, name, mode), - moduleResolutionIsEqualTo, - moduleResolutionNameAndModeGetter - ); - if (resolutionsChanged) - structureIsReused = 1 /* SafeModules */; + ((_resolvedModulesProce = resolvedModulesProcessing) !== null && _resolvedModulesProce !== void 0 ? _resolvedModulesProce : resolvedModulesProcessing = /* @__PURE__ */new Map()).set(newSourceFile.path, resolutions); + const resolutionsChanged = hasChangesInResolutions(moduleNames, newSourceFile, resolutions, (name, mode) => oldProgram.getResolvedModule(newSourceFile, name, mode), moduleResolutionIsEqualTo, moduleResolutionNameAndModeGetter); + if (resolutionsChanged) structureIsReused = 1 /* SafeModules */; const typesReferenceDirectives = newSourceFile.typeReferenceDirectives; const typeReferenceResolutions = resolveTypeReferenceDirectiveNamesReusingOldState(typesReferenceDirectives, newSourceFile); - (resolvedTypeReferenceDirectiveNamesProcessing ?? (resolvedTypeReferenceDirectiveNamesProcessing = /* @__PURE__ */ new Map())).set(newSourceFile.path, typeReferenceResolutions); - const typeReferenceResolutionsChanged = hasChangesInResolutions( - typesReferenceDirectives, - newSourceFile, - typeReferenceResolutions, - (name, mode) => oldProgram == null ? void 0 : oldProgram.getResolvedTypeReferenceDirective(newSourceFile, name, mode), - typeDirectiveIsEqualTo, - typeReferenceResolutionNameAndModeGetter - ); - if (typeReferenceResolutionsChanged) - structureIsReused = 1 /* SafeModules */; + ((_resolvedTypeReferenc = resolvedTypeReferenceDirectiveNamesProcessing) !== null && _resolvedTypeReferenc !== void 0 ? _resolvedTypeReferenc : resolvedTypeReferenceDirectiveNamesProcessing = /* @__PURE__ */new Map()).set(newSourceFile.path, typeReferenceResolutions); + const typeReferenceResolutionsChanged = hasChangesInResolutions(typesReferenceDirectives, newSourceFile, typeReferenceResolutions, (name, mode) => oldProgram == null ? void 0 : oldProgram.getResolvedTypeReferenceDirective(newSourceFile, name, mode), typeDirectiveIsEqualTo, typeReferenceResolutionNameAndModeGetter); + if (typeReferenceResolutionsChanged) structureIsReused = 1 /* SafeModules */; } + if (structureIsReused !== 2 /* Completely */) { return structureIsReused; } if (changesAffectingProgramStructure(oldOptions, options)) { return 1 /* SafeModules */; } + if (oldProgram.resolvedLibReferences && forEachEntry(oldProgram.resolvedLibReferences, (resolution, libFileName) => pathForLibFileWorker(libFileName).actual !== resolution.actual)) { return 1 /* SafeModules */; } + if (host.hasChangedAutomaticTypeDirectiveNames) { - if (host.hasChangedAutomaticTypeDirectiveNames()) - return 1 /* SafeModules */; + 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 */; } + missingFilePaths = oldProgram.getMissingFilePaths(); Debug.assert(newSourceFiles.length === oldProgram.getSourceFiles().length); for (const newSourceFile of newSourceFiles) { @@ -120047,6 +106565,7 @@ ${lanes.join("\n")} packageMap = oldProgram.getCurrentPackagesMap(); return 2 /* Completely */; } + function getEmitHost(writeFileCallback) { return { getPrependNodes, @@ -120065,17 +106584,15 @@ ${lanes.join("\n")} getSymlinkCache, writeFile: writeFileCallback || writeFile2, isEmitBlocked, - readFile: (f) => host.readFile(f), - fileExists: (f) => { + readFile: f => host.readFile(f), + fileExists: f => { const path = toPath3(f); - if (getSourceFileByPath(path)) - return true; - if (contains(missingFilePaths, path)) - return false; + if (getSourceFileByPath(path)) return true; + if (contains(missingFilePaths, path)) return false; return host.fileExists(f); }, useCaseSensitiveFileNames: () => host.useCaseSensitiveFileNames(), - getBuildInfo: (bundle) => { + getBuildInfo: bundle => { var _a2; return (_a2 = program.getBuildInfo) == null ? void 0 : _a2.call(program, bundle); }, @@ -120091,26 +106608,14 @@ ${lanes.join("\n")} function emitBuildInfo(writeFileCallback) { var _a2, _b2; Debug.assert(!outFile(options)); - (_a2 = tracing) == null ? void 0 : _a2.push( - tracing.Phase.Emit, - "emitBuildInfo", - {}, - /*separateBeginAndEnd*/ - true - ); + (_a2 = tracing) == null ? void 0 : _a2.push(tracing.Phase.Emit, "emitBuildInfo", {}, /*separateBeginAndEnd*/ + true); mark("beforeEmit"); - const emitResult = emitFiles( - notImplementedResolver, - getEmitHost(writeFileCallback), - /*targetSourceFile*/ - void 0, - /*transformers*/ - noTransformers, - /*emitOnly*/ - false, - /*onlyBuildInfo*/ - true - ); + const emitResult = emitFiles(notImplementedResolver, getEmitHost(writeFileCallback), /*targetSourceFile*/ + void 0, /*transformers*/ + noTransformers, /*emitOnly*/ + false, /*onlyBuildInfo*/ + true); mark("afterEmit"); measure("Emit", "beforeEmit", "afterEmit"); (_b2 = tracing) == null ? void 0 : _b2.pop(); @@ -120123,19 +106628,14 @@ ${lanes.join("\n")} return projectReferences; } function getPrependNodes() { - return createPrependNodes( - projectReferences, - (_ref, index) => { - var _a2; - return (_a2 = resolvedProjectReferences[index]) == null ? void 0 : _a2.commandLine; - }, - (fileName) => { - const path = toPath3(fileName); - const sourceFile = getSourceFileByPath(path); - return sourceFile ? sourceFile.text : filesByName.has(path) ? void 0 : host.readFile(path); - }, - host - ); + return createPrependNodes(projectReferences, (_ref, index) => { + var _a2; + return (_a2 = resolvedProjectReferences[index]) == null ? void 0 : _a2.commandLine; + }, fileName => { + const path = toPath3(fileName); + const sourceFile = getSourceFileByPath(path); + return sourceFile ? sourceFile.text : filesByName.has(path) ? void 0 : host.readFile(path); + }, host); } function isSourceFileFromExternalLibrary(file) { return !!sourceFilesFoundSearchingNodeModules.get(file.path); @@ -120154,7 +106654,7 @@ ${lanes.join("\n")} if (!options.lib) { return equalityComparer(file.fileName, getDefaultLibraryFileName()); } else { - return some(options.lib, (libFileName) => equalityComparer(file.fileName, resolvedLibReferences.get(libFileName).actual)); + return some(options.lib, libFileName => equalityComparer(file.fileName, resolvedLibReferences.get(libFileName).actual)); } } function getTypeChecker() { @@ -120162,13 +106662,10 @@ ${lanes.join("\n")} } function emit(sourceFile, writeFileCallback, cancellationToken, emitOnly, transformers, forceDtsEmit) { var _a2, _b2; - (_a2 = tracing) == null ? void 0 : _a2.push( - tracing.Phase.Emit, - "emit", - { path: sourceFile == null ? void 0 : sourceFile.path }, - /*separateBeginAndEnd*/ - true - ); + (_a2 = tracing) == null ? void 0 : _a2.push(tracing.Phase.Emit, "emit", { + path: sourceFile == null ? void 0 : sourceFile.path + }, /*separateBeginAndEnd*/ + true); const result = runWithCancellationToken(() => emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnly, transformers, forceDtsEmit)); (_b2 = tracing) == null ? void 0 : _b2.pop(); return result; @@ -120179,21 +106676,12 @@ ${lanes.join("\n")} 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(outFile(options) ? void 0 : sourceFile, cancellationToken); mark("beforeEmit"); - const emitResult = emitFiles( - emitResolver, - getEmitHost(writeFileCallback), - sourceFile, - getTransformers(options, customTransformers, emitOnly), - emitOnly, - /*onlyBuildInfo*/ - false, - forceDtsEmit - ); + const emitResult = emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile, getTransformers(options, customTransformers, emitOnly), emitOnly, /*onlyBuildInfo*/ + false, forceDtsEmit); mark("afterEmit"); measure("Emit", "beforeEmit", "afterEmit"); return emitResult; @@ -120208,7 +106696,7 @@ ${lanes.join("\n")} if (sourceFile) { return sortAndDeduplicateDiagnostics(getDiagnostics2(sourceFile, cancellationToken)); } - return sortAndDeduplicateDiagnostics(flatMap(program.getSourceFiles(), (sourceFile2) => { + return sortAndDeduplicateDiagnostics(flatMap(program.getSourceFiles(), sourceFile2 => { if (cancellationToken) { cancellationToken.throwIfCancellationRequested(); } @@ -120267,10 +106755,7 @@ ${lanes.join("\n")} } } function getSemanticDiagnosticsForFile(sourceFile, cancellationToken) { - return concatenate( - filterSemanticDiagnostics(getBindAndCheckDiagnosticsForFile(sourceFile, cancellationToken), options), - getProgramDiagnostics(sourceFile) - ); + return concatenate(filterSemanticDiagnostics(getBindAndCheckDiagnosticsForFile(sourceFile, cancellationToken), options), getProgramDiagnostics(sourceFile)); } function getBindAndCheckDiagnosticsForFile(sourceFile, cancellationToken) { return getAndCacheDiagnostics(sourceFile, cancellationToken, cachedBindAndCheckDiagnosticsForFile, getBindAndCheckDiagnosticsForFileNoCache); @@ -120290,8 +106775,8 @@ ${lanes.join("\n")} let bindDiagnostics = includeBindAndCheckDiagnostics ? sourceFile.bindDiagnostics : emptyArray; let checkDiagnostics = includeBindAndCheckDiagnostics ? typeChecker2.getDiagnostics(sourceFile, cancellationToken) : emptyArray; if (isPlainJs) { - bindDiagnostics = filter(bindDiagnostics, (d) => plainJSErrors.has(d.code)); - checkDiagnostics = filter(checkDiagnostics, (d) => plainJSErrors.has(d.code)); + 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); }); @@ -120302,7 +106787,10 @@ ${lanes.join("\n")} if (!includeBindAndCheckDiagnostics || !((_a2 = sourceFile.commentDirectives) == null ? void 0 : _a2.length)) { return flatDiagnostics; } - const { diagnostics, directives } = getDiagnosticsWithPrecedingDirectives(sourceFile, sourceFile.commentDirectives, flatDiagnostics); + const { + diagnostics, + directives + } = getDiagnosticsWithPrecedingDirectives(sourceFile, sourceFile.commentDirectives, flatDiagnostics); for (const errorExpectation of directives.getUnusedExpectations()) { diagnostics.push(createDiagnosticForRange(sourceFile, errorExpectation.range, Diagnostics.Unused_ts_expect_error_directive)); } @@ -120310,8 +106798,11 @@ ${lanes.join("\n")} } function getDiagnosticsWithPrecedingDirectives(sourceFile, commentDirectives, flatDiagnostics) { const directives = createCommentDirectivesMap(sourceFile, commentDirectives); - const diagnostics = flatDiagnostics.filter((diagnostic) => markPrecedingCommentDirectiveLine(diagnostic, directives) === -1); - return { diagnostics, directives }; + const diagnostics = flatDiagnostics.filter(diagnostic => markPrecedingCommentDirectiveLine(diagnostic, directives) === -1); + return { + diagnostics, + directives + }; } function getSuggestionDiagnostics(sourceFile, cancellationToken) { return runWithCancellationToken(() => { @@ -120319,7 +106810,10 @@ ${lanes.join("\n")} }); } function markPrecedingCommentDirectiveLine(diagnostic, directives) { - const { file, start } = diagnostic; + const { + file, + start + } = diagnostic; if (!file) { return -1; } @@ -120459,10 +106953,7 @@ ${lanes.join("\n")} } else if (exportIndex >= 0 && decoratorIndex < exportIndex) { const trailingDecoratorIndex = findIndex(parent2.modifiers, isDecorator, exportIndex); if (trailingDecoratorIndex >= 0) { - diagnostics.push(addRelatedInfo( - createDiagnosticForNode2(parent2.modifiers[trailingDecoratorIndex], Diagnostics.Decorators_may_not_appear_after_export_or_export_default_if_they_also_appear_before_export), - createDiagnosticForNode2(parent2.modifiers[decoratorIndex], Diagnostics.Decorator_used_before_export_here) - )); + diagnostics.push(addRelatedInfo(createDiagnosticForNode2(parent2.modifiers[trailingDecoratorIndex], Diagnostics.Decorators_may_not_appear_after_export_or_export_default_if_they_also_appear_before_export), createDiagnosticForNode2(parent2.modifiers[decoratorIndex], Diagnostics.Decorator_used_before_export_here))); } } } @@ -120543,6 +107034,7 @@ ${lanes.join("\n")} } } } + function createDiagnosticForNodeArray2(nodes, message, ...args) { const start = nodes.pos; return createFileDiagnostic(sourceFile, start, nodes.end - start, message, ...args); @@ -120569,7 +107061,7 @@ ${lanes.join("\n")} } const result = getDiagnostics2(sourceFile, cancellationToken); if (sourceFile) { - (cache.perFile || (cache.perFile = /* @__PURE__ */ new Map())).set(sourceFile.path, result); + (cache.perFile || (cache.perFile = /* @__PURE__ */new Map())).set(sourceFile.path, result); } else { cache.allDiagnostics = result; } @@ -120579,16 +107071,12 @@ ${lanes.join("\n")} return sourceFile.isDeclarationFile ? [] : getDeclarationDiagnosticsWorker(sourceFile, cancellationToken); } function getOptionsDiagnostics() { - return sortAndDeduplicateDiagnostics(concatenate( - programDiagnostics.getGlobalDiagnostics(), - getOptionsDiagnosticsOfConfigFile() - )); + return sortAndDeduplicateDiagnostics(concatenate(programDiagnostics.getGlobalDiagnostics(), getOptionsDiagnosticsOfConfigFile())); } function getOptionsDiagnosticsOfConfigFile() { - if (!options.configFile) - return emptyArray; + if (!options.configFile) return emptyArray; let diagnostics = programDiagnostics.getDiagnostics(options.configFile.fileName); - forEachResolvedProjectReference2((resolvedRef) => { + forEachResolvedProjectReference2(resolvedRef => { diagnostics = concatenate(diagnostics, programDiagnostics.getDiagnostics(resolvedRef.sourceFile.fileName)); }); return diagnostics; @@ -120600,14 +107088,8 @@ ${lanes.join("\n")} return configFileParsingDiagnostics || emptyArray; } function processRootFile(fileName, isDefaultLib, ignoreNoDefaultLib, reason) { - processSourceFile( - normalizePath(fileName), - isDefaultLib, - ignoreNoDefaultLib, - /*packageId*/ - void 0, - reason - ); + processSourceFile(normalizePath(fileName), isDefaultLib, ignoreNoDefaultLib, /*packageId*/ + void 0, reason); } function fileReferenceIsEqualTo(a, b) { return a.fileName === b.fileName; @@ -120617,15 +107099,10 @@ ${lanes.join("\n")} } function createSyntheticImport(text, file) { const externalHelpersModuleReference = factory.createStringLiteral(text); - const importDecl = factory.createImportDeclaration( - /*modifiers*/ - void 0, - /*importClause*/ - void 0, - externalHelpersModuleReference, - /*attributes*/ - void 0 - ); + const importDecl = factory.createImportDeclaration( /*modifiers*/ + void 0, /*importClause*/ + void 0, externalHelpersModuleReference, /*attributes*/ + void 0); addInternalEmitFlags(importDecl, 2 /* NeverApplyImportHelper */); setParent(externalHelpersModuleReference, importDecl); setParent(importDecl, file); @@ -120652,11 +107129,8 @@ ${lanes.join("\n")} } } for (const node of file.statements) { - collectModuleReferences( - node, - /*inAmbientModule*/ - false - ); + collectModuleReferences(node, /*inAmbientModule*/ + false); } const shouldProcessRequires = isJavaScriptFile && shouldResolveJsRequire(options); if (file.flags & 4194304 /* PossiblyContainsDynamicImport */ || shouldProcessRequires) { @@ -120670,11 +107144,8 @@ ${lanes.join("\n")} if (isAnyImportOrReExport(node)) { const moduleNameExpr = getExternalModuleName(node); if (moduleNameExpr && isStringLiteral(moduleNameExpr) && moduleNameExpr.text && (!inAmbientModule || !isExternalModuleNameRelative(moduleNameExpr.text))) { - setParentRecursive( - node, - /*incremental*/ - false - ); + setParentRecursive(node, /*incremental*/ + false); imports = append(imports, moduleNameExpr); if (!usesUriStyleNodeCoreModules && currentNodeModulesDepth === 0 && !file.isDeclarationFile) { usesUriStyleNodeCoreModules = startsWith(moduleNameExpr.text, "node:"); @@ -120693,11 +107164,8 @@ ${lanes.join("\n")} const body = node.body; if (body) { for (const statement of body.statements) { - collectModuleReferences( - statement, - /*inAmbientModule*/ - true - ); + collectModuleReferences(statement, /*inAmbientModule*/ + true); } } } @@ -120708,37 +107176,25 @@ ${lanes.join("\n")} const r = /import|require/g; while (r.exec(file2.text) !== null) { const node = getNodeAtPosition(file2, r.lastIndex); - if (shouldProcessRequires && isRequireCall( - node, - /*requireStringLiteralLikeArgument*/ - true - )) { - setParentRecursive( - node, - /*incremental*/ - false - ); + if (shouldProcessRequires && isRequireCall(node, /*requireStringLiteralLikeArgument*/ + true)) { + setParentRecursive(node, /*incremental*/ + false); imports = append(imports, node.arguments[0]); } else if (isImportCall(node) && node.arguments.length >= 1 && isStringLiteralLike(node.arguments[0])) { - setParentRecursive( - node, - /*incremental*/ - false - ); + setParentRecursive(node, /*incremental*/ + false); imports = append(imports, node.arguments[0]); } else if (isLiteralImportTypeNode(node)) { - setParentRecursive( - node, - /*incremental*/ - false - ); + setParentRecursive(node, /*incremental*/ + false); imports = append(imports, node.argument.literal); } } } function getNodeAtPosition(sourceFile, position) { let current = sourceFile; - const getContainingChild = (child) => { + const getContainingChild = child => { if (child.pos <= position && (position < child.end || position === child.end && child.kind === 1 /* EndOfFileToken */)) { return child; } @@ -120754,7 +107210,9 @@ ${lanes.join("\n")} } 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; } @@ -120764,7 +107222,7 @@ ${lanes.join("\n")} function getSourceFileFromReferenceWorker(fileName, getSourceFile2, fail, reason) { if (hasExtension(fileName)) { const canonicalFileName = host.getCanonicalFileName(fileName); - if (!options.allowNonTsExtensions && !forEach(flatten(supportedExtensionsWithJsonIfResolveJsonModule), (extension) => fileExtensionIs(canonicalFileName, extension))) { + if (!options.allowNonTsExtensions && !forEach(flatten(supportedExtensionsWithJsonIfResolveJsonModule), extension => fileExtensionIs(canonicalFileName, extension))) { if (fail) { if (hasJSFileExtension(canonicalFileName)) { fail(Diagnostics.File_0_is_a_JavaScript_file_Did_you_mean_to_enable_the_allowJs_option, fileName); @@ -120790,44 +107248,27 @@ ${lanes.join("\n")} 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("', '") + "'"); + 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("', '") + "'"); return sourceFileWithAddedExtension; } } function processSourceFile(fileName, isDefaultLib, ignoreNoDefaultLib, packageId, reason) { - getSourceFileFromReferenceWorker( - fileName, - (fileName2) => findSourceFile(fileName2, isDefaultLib, ignoreNoDefaultLib, reason, packageId), - // TODO: GH#18217 - (diagnostic, ...args) => addFilePreprocessingFileExplainingDiagnostic( - /*file*/ - void 0, - reason, - diagnostic, - args - ), - reason - ); + getSourceFileFromReferenceWorker(fileName, fileName2 => findSourceFile(fileName2, isDefaultLib, ignoreNoDefaultLib, reason, packageId), + // TODO: GH#18217 + (diagnostic, ...args) => addFilePreprocessingFileExplainingDiagnostic( /*file*/ + void 0, reason, diagnostic, args), reason); } function processProjectReferenceFile(fileName, reason) { - return processSourceFile( - fileName, - /*isDefaultLib*/ - false, - /*ignoreNoDefaultLib*/ - false, - /*packageId*/ - void 0, - reason - ); + return processSourceFile(fileName, /*isDefaultLib*/ + false, /*ignoreNoDefaultLib*/ + false, /*packageId*/ + void 0, reason); } function reportFileNamesDifferOnlyInCasingError(fileName, existingFile, reason) { const hasExistingReasonToReportErrorOn = !isReferencedFile(reason) && some(fileReasons.get(existingFile.path), isReferencedFile); @@ -120839,7 +107280,10 @@ ${lanes.join("\n")} } function createRedirectedSourceFile(redirectTarget, unredirected, fileName, path, resolvedPath, originalFileName, sourceFileOptions) { var _a2; - const redirect = parseNodeFactory.createRedirectedSourceFile({ redirectTarget, unredirected }); + const redirect = parseNodeFactory.createRedirectedSourceFile({ + redirectTarget, + unredirected + }); redirect.fileName = fileName; redirect.path = path; redirect.resolvedPath = resolvedPath; @@ -120864,7 +107308,17 @@ ${lanes.join("\n")} const result = getImpliedNodeFormatForFileWorker(getNormalizedAbsolutePath(fileName, currentDirectory), moduleResolutionCache2 == null ? void 0 : moduleResolutionCache2.getPackageJsonInfoCache(), host2, options2); const languageVersion = getEmitScriptTarget(options2); const setExternalModuleIndicator2 = getSetExternalModuleIndicator(options2); - return typeof result === "object" ? { ...result, languageVersion, setExternalModuleIndicator: setExternalModuleIndicator2, jsDocParsingMode: host2.jsDocParsingMode } : { languageVersion, impliedNodeFormat: result, setExternalModuleIndicator: setExternalModuleIndicator2, jsDocParsingMode: host2.jsDocParsingMode }; + return typeof result === "object" ? { + ...result, + languageVersion, + setExternalModuleIndicator: setExternalModuleIndicator2, + jsDocParsingMode: host2.jsDocParsingMode + } : { + languageVersion, + impliedNodeFormat: result, + setExternalModuleIndicator: setExternalModuleIndicator2, + jsDocParsingMode: host2.jsDocParsingMode + }; } function findSourceFileWorker(fileName, isDefaultLib, ignoreNoDefaultLib, reason, packageId) { var _a2; @@ -120873,18 +107327,12 @@ ${lanes.join("\n")} 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, - /*redirectedPath*/ - void 0 - ); + if (file2) addFileToFilesByName(file2, path, /*redirectedPath*/ + void 0); return file2; } } @@ -120936,18 +107384,8 @@ ${lanes.join("\n")} } } const sourceFileOptions = getCreateSourceFileOptions(fileName, moduleResolutionCache, host, options); - const file = host.getSourceFile( - fileName, - sourceFileOptions, - (hostErrorMessage) => addFilePreprocessingFileExplainingDiagnostic( - /*file*/ - void 0, - reason, - Diagnostics.Cannot_read_file_0_Colon_1, - [fileName, hostErrorMessage] - ), - shouldCreateNewSourceFile - ); + const file = host.getSourceFile(fileName, sourceFileOptions, hostErrorMessage => addFilePreprocessingFileExplainingDiagnostic( /*file*/ + void 0, reason, Diagnostics.Cannot_read_file_0_Colon_1, [fileName, hostErrorMessage]), shouldCreateNewSourceFile); if (packageId) { const packageIdKey = packageIdToString(packageId); const fileFromPackageId = packageIdToSourceFile.get(packageIdKey); @@ -121001,8 +107439,7 @@ ${lanes.join("\n")} return file; } function addFileIncludeReason(file, reason) { - if (file) - fileReasons.add(file.path, reason); + if (file) fileReasons.add(file.path, reason); } function addFileToFilesByName(file, path, redirectedPath) { if (redirectedPath) { @@ -121028,10 +107465,10 @@ ${lanes.join("\n")} } function getResolvedProjectReferenceToRedirect(fileName) { if (mapFromFileToProjectReferenceRedirects === void 0) { - mapFromFileToProjectReferenceRedirects = /* @__PURE__ */ new Map(); - forEachResolvedProjectReference2((referencedProject) => { + mapFromFileToProjectReferenceRedirects = /* @__PURE__ */new Map(); + forEachResolvedProjectReference2(referencedProject => { if (toPath3(options.configFilePath) !== referencedProject.sourceFile.path) { - referencedProject.commandLine.fileNames.forEach((f) => mapFromFileToProjectReferenceRedirects.set(toPath3(f), referencedProject.sourceFile.path)); + referencedProject.commandLine.fileNames.forEach(f => mapFromFileToProjectReferenceRedirects.set(toPath3(f), referencedProject.sourceFile.path)); } }); } @@ -121042,18 +107479,17 @@ ${lanes.join("\n")} 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) => { + mapFromToProjectReferenceRedirectSource = /* @__PURE__ */new Map(); + forEachResolvedProjectReference2(resolvedRef => { const out = outFile(resolvedRef.commandLine.options); if (out) { const outputDts = changeExtension(out, ".d.ts" /* Dts */); mapFromToProjectReferenceRedirectSource.set(toPath3(outputDts), true); } else { const getCommonSourceDirectory3 = memoize(() => getCommonSourceDirectoryOfConfig(resolvedRef.commandLine, !host.useCaseSensitiveFileNames())); - forEach(resolvedRef.commandLine.fileNames, (fileName) => { + forEach(resolvedRef.commandLine.fileNames, fileName => { if (!isDeclarationFileName(fileName) && !fileExtensionIs(fileName, ".json" /* Json */)) { const outputDts = getOutputDeclarationFileName(fileName, resolvedRef.commandLine, !host.useCaseSensitiveFileNames(), getCommonSourceDirectory3); mapFromToProjectReferenceRedirectSource.set(toPath3(outputDts), fileName); @@ -121075,36 +107511,43 @@ ${lanes.join("\n")} } function processReferencedFiles(file, isDefaultLib) { forEach(file.referencedFiles, (ref, index) => { - processSourceFile( - resolveTripleslashReference(ref.fileName, file.fileName), - isDefaultLib, - /*ignoreNoDefaultLib*/ - false, - /*packageId*/ - void 0, - { kind: 4 /* ReferenceFile */, file: file.path, index } - ); + processSourceFile(resolveTripleslashReference(ref.fileName, file.fileName), isDefaultLib, /*ignoreNoDefaultLib*/ + false, /*packageId*/ + void 0, { + kind: 4 /* ReferenceFile */, + file: file.path, + index + }); }); } function processTypeReferenceDirectives(file) { + var _resolvedTypeReferenc2; 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); + ((_resolvedTypeReferenc2 = resolvedTypeReferenceDirectiveNames) !== null && _resolvedTypeReferenc2 !== void 0 ? _resolvedTypeReferenc2 : 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); resolutionsInFile.set(fileName, getModeForFileReference(ref, file.impliedNodeFormat), resolvedTypeReferenceDirective); const mode = ref.resolutionMode || file.impliedNodeFormat; - processTypeReferenceDirective(fileName, mode, resolvedTypeReferenceDirective, { kind: 5 /* TypeReferenceDirective */, file: file.path, index }); + processTypeReferenceDirective(fileName, mode, resolvedTypeReferenceDirective, { + kind: 5 /* TypeReferenceDirective */, + file: file.path, + index + }); } } function processTypeReferenceDirective(typeReferenceDirective, mode, resolution, reason) { var _a2, _b2; - (_a2 = tracing) == null ? void 0 : _a2.push(tracing.Phase.Program, "processTypeReferenceDirective", { directive: typeReferenceDirective, hasResolved: !!resolution.resolvedTypeReferenceDirective, refKind: reason.kind, refPath: isReferencedFile(reason) ? reason.file : void 0 }); + (_a2 = tracing) == null ? void 0 : _a2.push(tracing.Phase.Program, "processTypeReferenceDirective", { + directive: typeReferenceDirective, + hasResolved: !!resolution.resolvedTypeReferenceDirective, + refKind: reason.kind, + refPath: isReferencedFile(reason) ? reason.file : void 0 + }); processTypeReferenceDirectiveWorker(typeReferenceDirective, mode, resolution, reason); (_b2 = tracing) == null ? void 0 : _b2.pop(); } @@ -121116,97 +107559,71 @@ ${lanes.join("\n")} return; } let saveResolution = true; - const { resolvedTypeReferenceDirective } = resolution; + const { + resolvedTypeReferenceDirective + } = resolution; if (resolvedTypeReferenceDirective) { - if (resolvedTypeReferenceDirective.isExternalLibraryImport) - currentNodeModulesDepth++; + if (resolvedTypeReferenceDirective.isExternalLibraryImport) currentNodeModulesDepth++; if (resolvedTypeReferenceDirective.primary) { - processSourceFile( - resolvedTypeReferenceDirective.resolvedFileName, - /*isDefaultLib*/ - false, - /*ignoreNoDefaultLib*/ - false, - resolvedTypeReferenceDirective.packageId, - reason - ); + 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] - ); + 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 - ); + processSourceFile(resolvedTypeReferenceDirective.resolvedFileName, /*isDefaultLib*/ + false, /*ignoreNoDefaultLib*/ + false, resolvedTypeReferenceDirective.packageId, reason); } } - if (resolvedTypeReferenceDirective.isExternalLibraryImport) - currentNodeModulesDepth--; + if (resolvedTypeReferenceDirective.isExternalLibraryImport) currentNodeModulesDepth--; } else { - addFilePreprocessingFileExplainingDiagnostic( - /*file*/ - void 0, - reason, - Diagnostics.Cannot_find_type_definition_file_for_0, - [typeReferenceDirective] - ); + addFilePreprocessingFileExplainingDiagnostic( /*file*/ + void 0, reason, Diagnostics.Cannot_find_type_definition_file_for_0, [typeReferenceDirective]); } if (saveResolution) { resolvedTypeReferenceDirectives.set(typeReferenceDirective, mode, resolution); } } function pathForLibFile(libFileName) { + var _resolvedLibReference; 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); + ((_resolvedLibReference = resolvedLibReferences) !== null && _resolvedLibReference !== void 0 ? _resolvedLibReference : resolvedLibReferences = /* @__PURE__ */new Map()).set(libFileName, result); return result.actual; } function pathForLibFileWorker(libFileName) { + var _resolvedLibProcessin2; 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) { + var _resolvedLibProcessin; if (oldResolution.resolution && isTraceEnabled(options, host)) { const libraryName2 = getLibraryNameFromLibFileName(libFileName); const resolveFrom2 = getInferredLibraryNameResolveFrom(options, currentDirectory, libFileName); - trace( - host, - oldResolution.resolution.resolvedModule ? oldResolution.resolution.resolvedModule.packageId ? Diagnostics.Reusing_resolution_of_module_0_from_1_of_old_program_it_was_successfully_resolved_to_2_with_Package_ID_3 : Diagnostics.Reusing_resolution_of_module_0_from_1_of_old_program_it_was_successfully_resolved_to_2 : Diagnostics.Reusing_resolution_of_module_0_from_1_of_old_program_it_was_not_resolved, - libraryName2, - getNormalizedAbsolutePath(resolveFrom2, currentDirectory), - (_b2 = oldResolution.resolution.resolvedModule) == null ? void 0 : _b2.resolvedFileName, - ((_c2 = oldResolution.resolution.resolvedModule) == null ? void 0 : _c2.packageId) && packageIdToString(oldResolution.resolution.resolvedModule.packageId) - ); + trace(host, oldResolution.resolution.resolvedModule ? oldResolution.resolution.resolvedModule.packageId ? Diagnostics.Reusing_resolution_of_module_0_from_1_of_old_program_it_was_successfully_resolved_to_2_with_Package_ID_3 : Diagnostics.Reusing_resolution_of_module_0_from_1_of_old_program_it_was_successfully_resolved_to_2 : Diagnostics.Reusing_resolution_of_module_0_from_1_of_old_program_it_was_not_resolved, libraryName2, getNormalizedAbsolutePath(resolveFrom2, currentDirectory), (_b2 = oldResolution.resolution.resolvedModule) == null ? void 0 : _b2.resolvedFileName, ((_c2 = oldResolution.resolution.resolvedModule) == null ? void 0 : _c2.packageId) && packageIdToString(oldResolution.resolution.resolvedModule.packageId)); } - (resolvedLibProcessing ?? (resolvedLibProcessing = /* @__PURE__ */ new Map())).set(libFileName, oldResolution); + ((_resolvedLibProcessin = resolvedLibProcessing) !== null && _resolvedLibProcessin !== void 0 ? _resolvedLibProcessin : resolvedLibProcessing = /* @__PURE__ */new Map()).set(libFileName, oldResolution); return oldResolution; } } const libraryName = getLibraryNameFromLibFileName(libFileName); const resolveFrom = getInferredLibraryNameResolveFrom(options, currentDirectory, libFileName); - (_d2 = tracing) == null ? void 0 : _d2.push(tracing.Phase.Program, "resolveLibrary", { resolveFrom }); + (_d2 = tracing) == null ? void 0 : _d2.push(tracing.Phase.Program, "resolveLibrary", { + resolveFrom + }); mark("beforeResolveLibrary"); const resolution = actualResolveLibrary(libraryName, resolveFrom, options, libFileName); mark("afterResolveLibrary"); @@ -121216,21 +107633,23 @@ ${lanes.join("\n")} resolution, actual: resolution.resolvedModule ? resolution.resolvedModule.resolvedFileName : combinePaths(defaultLibraryPath, libFileName) }; - (resolvedLibProcessing ?? (resolvedLibProcessing = /* @__PURE__ */ new Map())).set(libFileName, result); + ((_resolvedLibProcessin2 = resolvedLibProcessing) !== null && _resolvedLibProcessin2 !== void 0 ? _resolvedLibProcessin2 : resolvedLibProcessing = /* @__PURE__ */new Map()).set(libFileName, result); return result; } function processLibReferenceDirectives(file) { forEach(file.libReferenceDirectives, (libReference, index) => { - const { libName, libFileName } = getLibFileNameFromLibReference(libReference); + const { + libName, + libFileName + } = getLibFileNameFromLibReference(libReference); if (libFileName) { - processRootFile( - pathForLibFile(libFileName), - /*isDefaultLib*/ - true, - /*ignoreNoDefaultLib*/ - true, - { kind: 7 /* LibReferenceDirective */, file: file.path, index } - ); + processRootFile(pathForLibFile(libFileName), /*isDefaultLib*/ + true, /*ignoreNoDefaultLib*/ + true, { + kind: 7 /* LibReferenceDirective */, + file: file.path, + index + }); } else { const unqualifiedLibName = removeSuffix(removePrefix(libName, "lib."), ".d.ts"); const suggestion = getSpellingSuggestion(unqualifiedLibName, libs, identity); @@ -121238,7 +107657,11 @@ ${lanes.join("\n")} const args = suggestion ? [libName, suggestion] : [libName]; (fileProcessingDiagnostics || (fileProcessingDiagnostics = [])).push({ kind: 0 /* FilePreprocessingReferencedDiagnostic */, - reason: { kind: 7 /* LibReferenceDirective */, file: file.path, index }, + reason: { + kind: 7 /* LibReferenceDirective */, + file: file.path, + index + }, diagnostic, args }); @@ -121252,12 +107675,13 @@ ${lanes.join("\n")} var _a2; collectExternalModuleReferences(file); if (file.imports.length || file.moduleAugmentations.length) { + var _resolvedModules; const moduleNames = getModuleNames(file); const resolutions = (resolvedModulesProcessing == null ? void 0 : resolvedModulesProcessing.get(file.path)) || resolveModuleNamesReusingOldState(moduleNames, file); Debug.assert(resolutions.length === moduleNames.length); const optionsForFile = (useSourceOfProjectReferenceRedirect ? (_a2 = getRedirectReferenceForResolution(file)) == null ? void 0 : _a2.commandLine.options : void 0) || options; const resolutionsInFile = createModeAwareCache(); - (resolvedModules ?? (resolvedModules = /* @__PURE__ */ new Map())).set(file.path, resolutionsInFile); + ((_resolvedModules = resolvedModules) !== null && _resolvedModules !== void 0 ? _resolvedModules : resolvedModules = /* @__PURE__ */new Map()).set(file.path, resolutionsInFile); for (let index = 0; index < moduleNames.length; index++) { const resolution = resolutions[index].resolvedModule; const moduleName = moduleNames[index].text; @@ -121279,15 +107703,13 @@ ${lanes.join("\n")} if (elideImport) { modulesWithElidedImports.set(file.path, true); } else if (shouldAddFile) { - findSourceFile( - resolvedFileName, - /*isDefaultLib*/ - false, - /*ignoreNoDefaultLib*/ - false, - { kind: 3 /* Import */, file: file.path, index }, - resolution.packageId - ); + findSourceFile(resolvedFileName, /*isDefaultLib*/ + false, /*ignoreNoDefaultLib*/ + false, { + kind: 3 /* Import */, + file: file.path, + index + }, resolution.packageId); } if (isFromNodeModulesSearch) { currentNodeModulesDepth--; @@ -121302,11 +107724,7 @@ ${lanes.join("\n")} if (!sourceFile.isDeclarationFile) { const absoluteSourceFilePath = host.getCanonicalFileName(getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory)); if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) { - addProgramDiagnosticExplainingFile( - sourceFile, - Diagnostics.File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files, - [sourceFile.fileName, rootDirectory] - ); + addProgramDiagnosticExplainingFile(sourceFile, Diagnostics.File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files, [sourceFile.fileName, rootDirectory]); allFilesBelongToPath = false; } } @@ -121315,7 +107733,7 @@ ${lanes.join("\n")} } function parseProjectReferenceConfigFile(ref) { if (!projectReferenceRedirects) { - projectReferenceRedirects = /* @__PURE__ */ new Map(); + projectReferenceRedirects = /* @__PURE__ */new Map(); } const refPath = resolveProjectReferencePath(ref); const sourceFilePath = toPath3(refPath); @@ -121328,51 +107746,36 @@ ${lanes.join("\n")} if (host.getParsedCommandLine) { commandLine = host.getParsedCommandLine(refPath); if (!commandLine) { - addFileToFilesByName( - /*file*/ - void 0, - sourceFilePath, - /*redirectedPath*/ - void 0 - ); + addFileToFilesByName( /*file*/ + void 0, sourceFilePath, /*redirectedPath*/ + void 0); projectReferenceRedirects.set(sourceFilePath, false); return void 0; } sourceFile = Debug.checkDefined(commandLine.options.configFile); Debug.assert(!sourceFile.path || sourceFile.path === sourceFilePath); - addFileToFilesByName( - sourceFile, - sourceFilePath, - /*redirectedPath*/ - void 0 - ); + addFileToFilesByName(sourceFile, sourceFilePath, /*redirectedPath*/ + void 0); } else { const basePath = getNormalizedAbsolutePath(getDirectoryPath(refPath), currentDirectory); sourceFile = host.getSourceFile(refPath, 100 /* JSON */); - addFileToFilesByName( - sourceFile, - sourceFilePath, - /*redirectedPath*/ - void 0 - ); + addFileToFilesByName(sourceFile, sourceFilePath, /*redirectedPath*/ + void 0); if (sourceFile === void 0) { projectReferenceRedirects.set(sourceFilePath, false); return void 0; } - commandLine = parseJsonSourceFileConfigFileContent( - sourceFile, - configParsingHost, - basePath, - /*existingOptions*/ - void 0, - refPath - ); + commandLine = parseJsonSourceFileConfigFileContent(sourceFile, configParsingHost, basePath, /*existingOptions*/ + void 0, refPath); } sourceFile.fileName = refPath; sourceFile.path = sourceFilePath; sourceFile.resolvedPath = sourceFilePath; sourceFile.originalFileName = refPath; - const resolvedRef = { commandLine, sourceFile }; + const resolvedRef = { + commandLine, + sourceFile + }; projectReferenceRedirects.set(sourceFilePath, resolvedRef); if (commandLine.projectReferences) { resolvedRef.references = commandLine.projectReferences.map(parseProjectReferenceConfigFile); @@ -121424,11 +107827,7 @@ ${lanes.join("\n")} const rootPaths = new Set(rootNames.map(toPath3)); for (const file of files) { if (sourceFileMayBeEmitted(file, program) && !rootPaths.has(file.path)) { - addProgramDiagnosticExplainingFile( - 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 || ""] - ); + addProgramDiagnosticExplainingFile(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 || ""]); } } } @@ -121438,24 +107837,14 @@ ${lanes.join("\n")} continue; } if (!hasZeroOrOneAsteriskCharacter(key)) { - createDiagnosticForOptionPaths( - /*onKey*/ - true, - key, - Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, - key - ); + createDiagnosticForOptionPaths( /*onKey*/ + true, key, Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, key); } if (isArray(options.paths[key])) { const len = options.paths[key].length; if (len === 0) { - createDiagnosticForOptionPaths( - /*onKey*/ - false, - key, - Diagnostics.Substitutions_for_pattern_0_shouldn_t_be_an_empty_array, - key - ); + createDiagnosticForOptionPaths( /*onKey*/ + false, key, Diagnostics.Substitutions_for_pattern_0_shouldn_t_be_an_empty_array, key); } for (let i = 0; i < len; i++) { const subst = options.paths[key][i]; @@ -121472,13 +107861,8 @@ ${lanes.join("\n")} } } } else { - createDiagnosticForOptionPaths( - /*onKey*/ - false, - key, - Diagnostics.Substitutions_for_pattern_0_should_be_an_array, - key - ); + createDiagnosticForOptionPaths( /*onKey*/ + false, key, Diagnostics.Substitutions_for_pattern_0_should_be_an_array, key); } } } @@ -121514,7 +107898,7 @@ ${lanes.join("\n")} createDiagnosticForOptionName(Diagnostics.Option_0_cannot_be_specified_with_option_1, "noImplicitUseStrict", "alwaysStrict"); } const languageVersion = getEmitScriptTarget(options); - const firstNonAmbientExternalModuleSourceFile = find(files, (f) => isExternalModule(f) && !f.isDeclarationFile); + const firstNonAmbientExternalModuleSourceFile = find(files, f => isExternalModule(f) && !f.isDeclarationFile); if (options.isolatedModules || options.verbatimModuleSyntax) { if (options.module === 0 /* None */ && languageVersion < 2 /* ES2015 */ && options.isolatedModules) { createDiagnosticForOptionName(Diagnostics.Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher, "isolatedModules", "target"); @@ -121541,12 +107925,15 @@ ${lanes.join("\n")} createDiagnosticForOptionName(Diagnostics.Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_esNext, "resolveJsonModule", "module"); } } - if (options.outDir || // there is --outDir specified - options.rootDir || // there is --rootDir specified - options.sourceRoot || // there is --sourceRoot specified + if (options.outDir || + // there is --outDir specified + options.rootDir || + // there is --rootDir specified + options.sourceRoot || + // there is --sourceRoot specified options.mapRoot) { const dir = getCommonSourceDirectory2(); - if (options.outDir && dir === "" && files.some((file) => getRootLength(file.fileName) > 1)) { + if (options.outDir && dir === "" && files.some(file => getRootLength(file.fileName) > 1)) { createDiagnosticForOptionName(Diagnostics.Cannot_find_the_common_subdirectory_path_for_the_input_files, "outDir"); } } @@ -121632,17 +108019,17 @@ ${lanes.join("\n")} if (moduleResolution === 100 /* Bundler */ && !emitModuleKindIsNonNodeESM(moduleKind)) { createOptionValueDiagnostic("moduleResolution", Diagnostics.Option_0_can_only_be_used_when_module_is_set_to_es2015_or_later, "bundler"); } - if (ModuleKind[moduleKind] && (100 /* Node16 */ <= moduleKind && moduleKind <= 199 /* NodeNext */) && !(3 /* Node16 */ <= moduleResolution && moduleResolution <= 99 /* NodeNext */)) { + if (ModuleKind[moduleKind] && 100 /* Node16 */ <= moduleKind && moduleKind <= 199 /* NodeNext */ && !(3 /* Node16 */ <= moduleResolution && moduleResolution <= 99 /* NodeNext */)) { const moduleKindName = ModuleKind[moduleKind]; createOptionValueDiagnostic("moduleResolution", Diagnostics.Option_moduleResolution_must_be_set_to_0_or_left_unspecified_when_option_module_is_set_to_1, moduleKindName, moduleKindName); - } else if (ModuleResolutionKind[moduleResolution] && (3 /* Node16 */ <= moduleResolution && moduleResolution <= 99 /* NodeNext */) && !(100 /* Node16 */ <= moduleKind && moduleKind <= 199 /* NodeNext */)) { + } else if (ModuleResolutionKind[moduleResolution] && 3 /* Node16 */ <= moduleResolution && moduleResolution <= 99 /* NodeNext */ && !(100 /* Node16 */ <= moduleKind && moduleKind <= 199 /* NodeNext */)) { const moduleResolutionName = ModuleResolutionKind[moduleResolution]; createOptionValueDiagnostic("module", Diagnostics.Option_module_must_be_set_to_0_when_option_moduleResolution_is_set_to_1, moduleResolutionName, moduleResolutionName); } if (!options.noEmit && !options.suppressOutputPathCheck) { const emitHost = getEmitHost(); - const emitFilesSeen = /* @__PURE__ */ new Set(); - forEachEmittedFile(emitHost, (emitFileNames) => { + const emitFilesSeen = /* @__PURE__ */new Set(); + forEachEmittedFile(emitHost, emitFileNames => { if (!options.emitDeclarationOnly) { verifyEmitFilePath(emitFileNames.jsFilePath, emitFilesSeen); } @@ -121655,11 +108042,8 @@ ${lanes.join("\n")} if (filesByName.has(emitFilePath)) { let chain; if (!options.configFilePath) { - chain = chainDiagnosticMessages( - /*details*/ - void 0, - Diagnostics.Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig - ); + chain = chainDiagnosticMessages( /*details*/ + void 0, Diagnostics.Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig); } chain = chainDiagnosticMessages(chain, Diagnostics.Cannot_write_file_0_because_it_would_overwrite_input_file, emitFileName); blockEmittingOfFile(emitFileName, createCompilerDiagnosticFromMessageChain(chain)); @@ -121711,34 +108095,19 @@ ${lanes.join("\n")} function verifyDeprecatedCompilerOptions() { function createDiagnostic(name, value, useInstead, message, ...args) { if (useInstead) { - const details = chainDiagnosticMessages( - /*details*/ - void 0, - Diagnostics.Use_0_instead, - useInstead - ); + const details = chainDiagnosticMessages( /*details*/ + void 0, Diagnostics.Use_0_instead, useInstead); const chain = chainDiagnosticMessages(details, message, ...args); - createDiagnosticForOption( - /*onKey*/ - !value, - name, - /*option2*/ - void 0, - chain - ); + createDiagnosticForOption( /*onKey*/ + !value, name, /*option2*/ + void 0, chain); } else { - createDiagnosticForOption( - /*onKey*/ - !value, - name, - /*option2*/ - void 0, - message, - ...args - ); + createDiagnosticForOption( /*onKey*/ + !value, name, /*option2*/ + void 0, message, ...args); } } - checkDeprecations("5.0", "5.5", createDiagnostic, (createDeprecatedDiagnostic) => { + checkDeprecations("5.0", "5.5", createDiagnostic, createDeprecatedDiagnostic => { if (options.target === 0 /* ES3 */) { createDeprecatedDiagnostic("target", "ES3"); } @@ -121761,28 +108130,16 @@ ${lanes.join("\n")} createDeprecatedDiagnostic("charset"); } if (options.out) { - createDeprecatedDiagnostic( - "out", - /*value*/ - void 0, - "outFile" - ); + createDeprecatedDiagnostic("out", /*value*/ + void 0, "outFile"); } if (options.importsNotUsedAsValues) { - createDeprecatedDiagnostic( - "importsNotUsedAsValues", - /*value*/ - void 0, - "verbatimModuleSyntax" - ); + createDeprecatedDiagnostic("importsNotUsedAsValues", /*value*/ + void 0, "verbatimModuleSyntax"); } if (options.preserveValueImports) { - createDeprecatedDiagnostic( - "preserveValueImports", - /*value*/ - void 0, - "verbatimModuleSyntax" - ); + createDeprecatedDiagnostic("preserveValueImports", /*value*/ + void 0, "verbatimModuleSyntax"); } }); } @@ -121790,7 +108147,7 @@ ${lanes.join("\n")} function createDiagnostic(_name, _value, _useInstead, message, ...args) { createDiagnosticForReference(parentFile, index, message, ...args); } - checkDeprecations("5.0", "5.5", createDiagnostic, (createDeprecatedDiagnostic) => { + checkDeprecations("5.0", "5.5", createDiagnostic, createDeprecatedDiagnostic => { if (ref.prepend) { createDeprecatedDiagnostic("prepend"); } @@ -121801,16 +108158,13 @@ ${lanes.join("\n")} 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; + 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; const location = locationReason && getReferencedFileLocation(program, locationReason); const fileIncludeReasonDetails = fileIncludeReasons && chainDiagnosticMessages(fileIncludeReasons, Diagnostics.The_file_is_in_the_program_because_Colon); const redirectInfo = file && explainIfFileIsRedirectAndImpliedFormat(file); - const chain = chainDiagnosticMessages(redirectInfo ? fileIncludeReasonDetails ? [fileIncludeReasonDetails, ...redirectInfo] : redirectInfo : fileIncludeReasonDetails, diagnostic, ...args || emptyArray); + 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)); @@ -121819,8 +108173,7 @@ ${lanes.join("\n")} } else if (locationReason !== reason) { relatedInfo = append(relatedInfo, fileIncludeReasonToRelatedInformation(reason)); } - if (reason === fileProcessingReason) - fileProcessingReason = void 0; + if (reason === fileProcessingReason) fileProcessingReason = void 0; } } function addFilePreprocessingFileExplainingDiagnostic(file, fileProcessingReason, diagnostic, args) { @@ -121833,13 +108186,8 @@ ${lanes.join("\n")} }); } function addProgramDiagnosticExplainingFile(file, diagnostic, args) { - programDiagnostics.add(createDiagnosticExplainingFile( - file, - /*fileProcessingReason*/ - void 0, - diagnostic, - args - )); + programDiagnostics.add(createDiagnosticExplainingFile(file, /*fileProcessingReason*/ + void 0, diagnostic, args)); } function fileIncludeReasonToRelatedInformation(reason) { if (isReferencedFile(reason)) { @@ -121861,21 +108209,14 @@ ${lanes.join("\n")} default: Debug.assertNever(reason); } - return isReferenceFileLocation(referenceLocation) ? createFileDiagnostic( - referenceLocation.file, - referenceLocation.pos, - referenceLocation.end - referenceLocation.pos, - message2 - ) : void 0; + return isReferenceFileLocation(referenceLocation) ? createFileDiagnostic(referenceLocation.file, referenceLocation.pos, referenceLocation.end - referenceLocation.pos, 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) { @@ -121884,27 +108225,26 @@ ${lanes.join("\n")} 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; case 1 /* SourceFromProjectReference */: 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; - const { sourceFile, index } = referenceInfo; - const referencesSyntax = forEachTsConfigPropArray(sourceFile, "references", (property) => isArrayLiteralExpression(property.initializer) ? property.initializer : void 0); - return referencesSyntax && referencesSyntax.elements.length > index ? createDiagnosticForNodeInSourceFile( + 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; + const { sourceFile, - referencesSyntax.elements[index], - reason.kind === 2 /* OutputFromProjectReference */ ? Diagnostics.File_is_output_from_referenced_project_specified_here : Diagnostics.File_is_source_from_referenced_project_specified_here - ) : void 0; + index + } = referenceInfo; + const referencesSyntax = forEachTsConfigPropArray(sourceFile, "references", property => isArrayLiteralExpression(property.initializer) ? property.initializer : void 0); + return referencesSyntax && referencesSyntax.elements.length > index ? createDiagnosticForNodeInSourceFile(sourceFile, referencesSyntax.elements[index], reason.kind === 2 /* OutputFromProjectReference */ ? Diagnostics.File_is_output_from_referenced_project_specified_here : Diagnostics.File_is_source_from_referenced_project_specified_here) : void 0; case 8 /* AutomaticTypeDirectiveFile */: - if (!options.types) - return void 0; + if (!options.types) return void 0; configFileNode = getOptionsSyntaxByArrayElementValue("types", reason.typeReference); message = Diagnostics.File_is_entry_point_of_type_library_specified_here; break; @@ -121921,11 +108261,7 @@ ${lanes.join("\n")} default: Debug.assertNever(reason); } - return configFileNode && createDiagnosticForNodeInSourceFile( - options.configFile, - configFileNode, - message - ); + return configFileNode && createDiagnosticForNodeInSourceFile(options.configFile, configFileNode, message); } function verifyProjectReferences() { const buildInfoPath = !options.suppressOutputPathCheck ? getTsBuildInfoEmitOutputFilePath(options) : void 0; @@ -121941,10 +108277,8 @@ ${lanes.join("\n")} 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 (ref.prepend) { @@ -121965,9 +108299,9 @@ ${lanes.join("\n")} } function createDiagnosticForOptionPathKeyValue(key, valueIndex, message, ...args) { let needCompilerDiagnostic = true; - forEachOptionPathsSyntax((pathProp) => { + forEachOptionPathsSyntax(pathProp => { if (isObjectLiteralExpression(pathProp.initializer)) { - forEachPropertyAssignment(pathProp.initializer, key, (keyProps) => { + forEachPropertyAssignment(pathProp.initializer, key, keyProps => { const initializer = keyProps.initializer; if (isArrayLiteralExpression(initializer) && initializer.elements.length > valueIndex) { programDiagnostics.add(createDiagnosticForNodeInSourceFile(options.configFile, initializer.elements[valueIndex], message, ...args)); @@ -121982,16 +108316,9 @@ ${lanes.join("\n")} } function createDiagnosticForOptionPaths(onKey, key, message, ...args) { let needCompilerDiagnostic = true; - forEachOptionPathsSyntax((pathProp) => { - if (isObjectLiteralExpression(pathProp.initializer) && createOptionDiagnosticInObjectLiteralSyntax( - pathProp.initializer, - onKey, - key, - /*key2*/ - void 0, - message, - ...args - )) { + forEachOptionPathsSyntax(pathProp => { + if (isObjectLiteralExpression(pathProp.initializer) && createOptionDiagnosticInObjectLiteralSyntax(pathProp.initializer, onKey, key, /*key2*/ + void 0, message, ...args)) { needCompilerDiagnostic = false; } }); @@ -122006,37 +108333,23 @@ ${lanes.join("\n")} return forEachOptionsSyntaxByName("paths", callback); } function getOptionsSyntaxByValue(name, value) { - return forEachOptionsSyntaxByName(name, (property) => isStringLiteral(property.initializer) && property.initializer.text === value ? property.initializer : void 0); + return forEachOptionsSyntaxByName(name, property => isStringLiteral(property.initializer) && property.initializer.text === value ? property.initializer : void 0); } function getOptionsSyntaxByArrayElementValue(name, value) { const compilerOptionsObjectLiteralSyntax = getCompilerOptionsObjectLiteralSyntax(); return compilerOptionsObjectLiteralSyntax && getPropertyArrayElementValue(compilerOptionsObjectLiteralSyntax, name, value); } function createDiagnosticForOptionName(message, option1, option2, option3) { - createDiagnosticForOption( - /*onKey*/ - true, - option1, - option2, - message, - option1, - option2, - option3 - ); + createDiagnosticForOption( /*onKey*/ + true, option1, option2, message, option1, option2, option3); } function createOptionValueDiagnostic(option1, message, ...args) { - createDiagnosticForOption( - /*onKey*/ - false, - option1, - /*option2*/ - void 0, - message, - ...args - ); + createDiagnosticForOption( /*onKey*/ + false, option1, /*option2*/ + void 0, message, ...args); } function createDiagnosticForReference(sourceFile, index, message, ...args) { - const referencesSyntax = forEachTsConfigPropArray(sourceFile || options.configFile, "references", (property) => isArrayLiteralExpression(property.initializer) ? property.initializer : void 0); + const referencesSyntax = forEachTsConfigPropArray(sourceFile || options.configFile, "references", property => isArrayLiteralExpression(property.initializer) ? property.initializer : void 0); if (referencesSyntax && referencesSyntax.elements.length > index) { programDiagnostics.add(createDiagnosticForNodeInSourceFile(sourceFile || options.configFile, referencesSyntax.elements[index], message, ...args)); } else { @@ -122056,17 +108369,13 @@ ${lanes.join("\n")} } function getCompilerOptionsObjectLiteralSyntax() { if (_compilerOptionsObjectLiteralSyntax === void 0) { - _compilerOptionsObjectLiteralSyntax = forEachPropertyAssignment( - getTsConfigObjectLiteralExpression(options.configFile), - "compilerOptions", - (prop) => isObjectLiteralExpression(prop.initializer) ? prop.initializer : void 0 - ) || false; + _compilerOptionsObjectLiteralSyntax = forEachPropertyAssignment(getTsConfigObjectLiteralExpression(options.configFile), "compilerOptions", prop => isObjectLiteralExpression(prop.initializer) ? prop.initializer : void 0) || false; } return _compilerOptionsObjectLiteralSyntax || void 0; } function createOptionDiagnosticInObjectLiteralSyntax(objectLiteral, onKey, key1, key2, message, ...args) { let needsCompilerDiagnostic = false; - forEachPropertyAssignment(objectLiteral, key1, (prop) => { + forEachPropertyAssignment(objectLiteral, key1, prop => { if ("messageText" in message) { programDiagnostics.add(createDiagnosticForNodeFromMessageChain(options.configFile, onKey ? prop.name : prop.initializer, message)); } else { @@ -122079,17 +108388,9 @@ ${lanes.join("\n")} function createRedundantOptionDiagnostic(errorOnOption, redundantWithOption) { const compilerOptionsObjectLiteralSyntax = getCompilerOptionsObjectLiteralSyntax(); if (compilerOptionsObjectLiteralSyntax) { - createOptionDiagnosticInObjectLiteralSyntax( - compilerOptionsObjectLiteralSyntax, - /*onKey*/ - true, - errorOnOption, - /*key2*/ - void 0, - Diagnostics.Option_0_is_redundant_and_cannot_be_specified_with_option_1, - errorOnOption, - redundantWithOption - ); + createOptionDiagnosticInObjectLiteralSyntax(compilerOptionsObjectLiteralSyntax, /*onKey*/ + true, errorOnOption, /*key2*/ + void 0, Diagnostics.Option_0_is_redundant_and_cannot_be_specified_with_option_1, errorOnOption, redundantWithOption); } else { createDiagnosticForOptionName(Diagnostics.Option_0_is_redundant_and_cannot_be_specified_with_option_1, errorOnOption, redundantWithOption); } @@ -122110,6 +108411,7 @@ ${lanes.join("\n")} if (out) { return isSameFile(filePath, out) || isSameFile(filePath, removeFileExtension(out) + ".d.ts" /* Dts */); } + if (options.declarationDir && containsPath(options.declarationDir, filePath, currentDirectory, !host.useCaseSensitiveFileNames())) { return true; } @@ -122120,11 +108422,13 @@ ${lanes.join("\n")} const filePathWithoutExtension = removeFileExtension(filePath); return !!getSourceFileByPath(filePathWithoutExtension + ".ts" /* Ts */) || !!getSourceFileByPath(filePathWithoutExtension + ".tsx" /* Tsx */); } + return false; } function isSameFile(file1, file2) { return comparePaths(file1, file2, currentDirectory, !host.useCaseSensitiveFileNames()) === 0 /* EqualTo */; } + function getSymlinkCache() { if (host.getSymlinkCache) { return host.getSymlinkCache(); @@ -122144,21 +108448,22 @@ ${lanes.join("\n")} 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) { - directoryExists = host.compilerHost.directoryExists = (path) => { + directoryExists = host.compilerHost.directoryExists = path => { if (originalDirectoryExists.call(host.compilerHost, path)) { handleDirectoryCouldBeSymlink(path); return true; } - if (!host.getResolvedProjectReferences()) - return false; + if (!host.getResolvedProjectReferences()) return false; if (!setOfDeclarationDirectories) { - setOfDeclarationDirectories = /* @__PURE__ */ new Set(); - host.forEachResolvedProjectReference((ref) => { + setOfDeclarationDirectories = /* @__PURE__ */new Set(); + host.forEachResolvedProjectReference(ref => { const out = outFile(ref.commandLine.options); if (out) { setOfDeclarationDirectories.add(getDirectoryPath(host.toPath(out))); @@ -122170,40 +108475,35 @@ ${lanes.join("\n")} } }); } - return fileOrDirectoryExistsUsingSource( - path, - /*isFile*/ - false - ); + return fileOrDirectoryExistsUsingSource(path, /*isFile*/ + false); }; } if (originalGetDirectories) { - host.compilerHost.getDirectories = (path) => !host.getResolvedProjectReferences() || originalDirectoryExists && originalDirectoryExists.call(host.compilerHost, path) ? originalGetDirectories.call(host.compilerHost, path) : []; + host.compilerHost.getDirectories = path => !host.getResolvedProjectReferences() || originalDirectoryExists && originalDirectoryExists.call(host.compilerHost, path) ? originalGetDirectories.call(host.compilerHost, path) : []; } if (originalRealpath) { - host.compilerHost.realpath = (s) => { + host.compilerHost.realpath = s => { var _a; return ((_a = host.getSymlinkCache().getSymlinkedFiles()) == null ? void 0 : _a.get(host.toPath(s))) || originalRealpath.call(host.compilerHost, s); }; } - return { onProgramCreateComplete, fileExists, directoryExists }; + return { + onProgramCreateComplete, + fileExists, + directoryExists + }; function onProgramCreateComplete() { host.compilerHost.fileExists = originalFileExists; host.compilerHost.directoryExists = originalDirectoryExists; 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; - return fileOrDirectoryExistsUsingSource( - file, - /*isFile*/ - true - ); + if (originalFileExists.call(host.compilerHost, file)) return true; + if (!host.getResolvedProjectReferences()) return false; + if (!isDeclarationFileName(file)) return false; + return fileOrDirectoryExistsUsingSource(file, /*isFile*/ + true); } function fileExistsIfProjectReferenceDts(file) { const source = host.getSourceOfProjectReferenceRedirect(host.toPath(file)); @@ -122212,23 +108512,19 @@ ${lanes.join("\n")} function directoryExistsIfProjectReferenceDeclDir(dir) { const dirPath = host.toPath(dir); const dirPathWithTrailingDirectorySeparator = `${dirPath}${directorySeparator}`; - return forEachKey( - setOfDeclarationDirectories, - (declDirPath) => dirPath === declDirPath || // Any parent directory of declaration dir - startsWith(declDirPath, dirPathWithTrailingDirectorySeparator) || // Any directory inside declaration dir - startsWith(dirPath, `${declDirPath}/`) - ); + return forEachKey(setOfDeclarationDirectories, declDirPath => dirPath === declDirPath || + // Any parent directory of declaration dir + startsWith(declDirPath, dirPathWithTrailingDirectorySeparator) || + // Any directory inside declaration dir + startsWith(dirPath, `${declDirPath}/`)); } 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) { @@ -122242,35 +108538,24 @@ ${lanes.join("\n")} } function fileOrDirectoryExistsUsingSource(fileOrDirectory, isFile) { var _a; - const fileOrDirectoryExistsUsingSource2 = isFile ? (file) => fileExistsIfProjectReferenceDts(file) : (dir) => directoryExistsIfProjectReferenceDeclDir(dir); + 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; - return firstDefinedIterator( - symlinkedDirectories.entries(), - ([directoryPath, symlinkedDirectory]) => { - 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()); - symlinkCache.setSymlinkedFile( - fileOrDirectoryPath, - `${symlinkedDirectory.real}${absolutePath.replace(new RegExp(directoryPath, "i"), "")}` - ); - } - return result2; + 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; + const result2 = fileOrDirectoryExistsUsingSource2(fileOrDirectoryPath.replace(directoryPath, symlinkedDirectory.realPath)); + if (isFile && result2) { + const absolutePath = getNormalizedAbsolutePath(fileOrDirectory, host.compilerHost.getCurrentDirectory()); + symlinkCache.setSymlinkedFile(fileOrDirectoryPath, `${symlinkedDirectory.real}${absolutePath.replace(new RegExp(directoryPath, "i"), "")}`); } - ) || false; + return result2; + }) || false; } } function handleNoEmitOptions(program, sourceFile, writeFile2, cancellationToken) { @@ -122279,68 +108564,63 @@ ${lanes.join("\n")} program.getSemanticDiagnostics(sourceFile, cancellationToken); return sourceFile || outFile(options) ? emitSkippedWithNoDiagnostics : program.emitBuildInfo(writeFile2, cancellationToken); } - if (!options.noEmitOnError) - return void 0; - let diagnostics = [ - ...program.getOptionsDiagnostics(cancellationToken), - ...program.getSyntacticDiagnostics(sourceFile, cancellationToken), - ...program.getGlobalDiagnostics(cancellationToken), - ...program.getSemanticDiagnostics(sourceFile, cancellationToken) - ]; + if (!options.noEmitOnError) return void 0; + let diagnostics = [...program.getOptionsDiagnostics(cancellationToken), ...program.getSyntacticDiagnostics(sourceFile, cancellationToken), ...program.getGlobalDiagnostics(cancellationToken), ...program.getSemanticDiagnostics(sourceFile, cancellationToken)]; if (diagnostics.length === 0 && getEmitDeclarations(program.getCompilerOptions())) { - diagnostics = program.getDeclarationDiagnostics( - /*sourceFile*/ - void 0, - cancellationToken - ); + diagnostics = program.getDeclarationDiagnostics( /*sourceFile*/ + void 0, cancellationToken); } - if (!diagnostics.length) - return void 0; + if (!diagnostics.length) return void 0; let emittedFiles; if (!sourceFile && !outFile(options)) { 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 }; + return { + diagnostics, + sourceMaps: void 0, + emittedFiles, + emitSkipped: true + }; } function filterSemanticDiagnostics(diagnostic, option) { - return filter(diagnostic, (d) => !d.skippedOn || !option[d.skippedOn]); + return filter(diagnostic, d => !d.skippedOn || !option[d.skippedOn]); } function parseConfigHostFromCompilerHostLike(host, directoryStructureHost = host) { return { - fileExists: (f) => directoryStructureHost.fileExists(f), + fileExists: f => directoryStructureHost.fileExists(f), readDirectory(root, extensions, excludes, includes, depth) { Debug.assertIsDefined(directoryStructureHost.readDirectory, "'CompilerHost.readDirectory' must be implemented to correctly process 'projectReferences'"); return directoryStructureHost.readDirectory(root, extensions, excludes, includes, depth); }, - readFile: (f) => directoryStructureHost.readFile(f), + readFile: f => directoryStructureHost.readFile(f), directoryExists: maybeBind(directoryStructureHost, directoryStructureHost.directoryExists), getDirectories: maybeBind(directoryStructureHost, directoryStructureHost.getDirectories), realpath: maybeBind(directoryStructureHost, directoryStructureHost.realpath), useCaseSensitiveFileNames: host.useCaseSensitiveFileNames(), getCurrentDirectory: () => host.getCurrentDirectory(), onUnRecoverableConfigFileDiagnostic: host.onUnRecoverableConfigFileDiagnostic || returnUndefined, - trace: host.trace ? (s) => host.trace(s) : void 0 + trace: host.trace ? s => host.trace(s) : void 0 }; } function createPrependNodes(projectReferences, getCommandLine, readFile, host) { - if (!projectReferences) - return emptyArray; + if (!projectReferences) return emptyArray; let nodes; for (let i = 0; i < projectReferences.length; i++) { const ref = projectReferences[i]; const resolvedRefOpts = getCommandLine(ref, i); if (ref.prepend && resolvedRefOpts && resolvedRefOpts.options) { const out = outFile(resolvedRefOpts.options); - if (!out) - continue; - const { jsFilePath, sourceMapFilePath, declarationFilePath, declarationMapPath, buildInfoPath } = getOutputPathsForBundle( - resolvedRefOpts.options, - /*forceDtsPaths*/ - true - ); + if (!out) continue; + const { + jsFilePath, + sourceMapFilePath, + declarationFilePath, + declarationMapPath, + buildInfoPath + } = getOutputPathsForBundle(resolvedRefOpts.options, /*forceDtsPaths*/ + true); const node = createInputFilesWithFilePaths(readFile, jsFilePath, sourceMapFilePath, declarationFilePath, declarationMapPath, buildInfoPath, host, resolvedRefOpts.options); (nodes || (nodes = [])).push(node); } @@ -122350,7 +108630,11 @@ ${lanes.join("\n")} function resolveProjectReferencePath(ref) { return resolveConfigFileProjectName(ref.path); } - function getResolutionDiagnostic(options, { extension }, { isDeclarationFile }) { + function getResolutionDiagnostic(options, { + extension + }, { + isDeclarationFile + }) { switch (extension) { case ".ts" /* Ts */: case ".d.ts" /* Dts */: @@ -122385,8 +108669,11 @@ ${lanes.join("\n")} return isDeclarationFile || options.allowArbitraryExtensions ? void 0 : Diagnostics.Module_0_was_resolved_to_1_but_allowArbitraryExtensions_is_not_set; } } - function getModuleNames({ imports, moduleAugmentations }) { - const res = imports.map((i) => i); + function getModuleNames({ + imports, + moduleAugmentations + }) { + const res = imports.map(i => i); for (const aug of moduleAugmentations) { if (aug.kind === 11 /* StringLiteral */) { res.push(aug); @@ -122394,14 +108681,15 @@ ${lanes.join("\n")} } return res; } - function getModuleNameStringLiteralAt({ imports, moduleAugmentations }, index) { - if (index < imports.length) - return imports[index]; + function getModuleNameStringLiteralAt({ + imports, + moduleAugmentations + }, 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++; } } @@ -122411,9 +108699,10 @@ ${lanes.join("\n")} var init_program = __esm({ "src/compiler/program.ts"() { "use strict"; + init_ts2(); init_ts_performance(); - ForegroundColorEscapeSequences = /* @__PURE__ */ ((ForegroundColorEscapeSequences2) => { + ForegroundColorEscapeSequences = /* @__PURE__ */(ForegroundColorEscapeSequences2 => { ForegroundColorEscapeSequences2["Grey"] = "\x1B[90m"; ForegroundColorEscapeSequences2["Red"] = "\x1B[91m"; ForegroundColorEscapeSequences2["Yellow"] = "\x1B[93m"; @@ -122440,104 +108729,19 @@ ${lanes.join("\n")} getMode: (entry, file) => getModeForFileReference(entry, file == null ? void 0 : file.impliedNodeFormat) }; inferredTypesContainingFile = "__inferred type names__.ts"; - plainJSErrors = /* @__PURE__ */ new Set([ - // binder errors - Diagnostics.Cannot_redeclare_block_scoped_variable_0.code, - Diagnostics.A_module_cannot_have_multiple_default_exports.code, - Diagnostics.Another_export_default_is_here.code, - Diagnostics.The_first_export_default_is_here.code, - Diagnostics.Identifier_expected_0_is_a_reserved_word_at_the_top_level_of_a_module.code, - Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode.code, - Diagnostics.Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here.code, - Diagnostics.constructor_is_a_reserved_word.code, - Diagnostics.delete_cannot_be_called_on_an_identifier_in_strict_mode.code, - Diagnostics.Code_contained_in_a_class_is_evaluated_in_JavaScript_s_strict_mode_which_does_not_allow_this_use_of_0_For_more_information_see_https_Colon_Slash_Slashdeveloper_mozilla_org_Slashen_US_Slashdocs_SlashWeb_SlashJavaScript_SlashReference_SlashStrict_mode.code, - Diagnostics.Invalid_use_of_0_Modules_are_automatically_in_strict_mode.code, - Diagnostics.Invalid_use_of_0_in_strict_mode.code, - Diagnostics.A_label_is_not_allowed_here.code, - Diagnostics.with_statements_are_not_allowed_in_strict_mode.code, - // grammar errors - Diagnostics.A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement.code, - Diagnostics.A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement.code, - Diagnostics.A_class_declaration_without_the_default_modifier_must_have_a_name.code, - Diagnostics.A_class_member_cannot_have_the_0_keyword.code, - Diagnostics.A_comma_expression_is_not_allowed_in_a_computed_property_name.code, - Diagnostics.A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement.code, - Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement.code, - Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement.code, - Diagnostics.A_default_clause_cannot_appear_more_than_once_in_a_switch_statement.code, - Diagnostics.A_default_export_must_be_at_the_top_level_of_a_file_or_module_declaration.code, - Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context.code, - Diagnostics.A_destructuring_declaration_must_have_an_initializer.code, - Diagnostics.A_get_accessor_cannot_have_parameters.code, - Diagnostics.A_rest_element_cannot_contain_a_binding_pattern.code, - Diagnostics.A_rest_element_cannot_have_a_property_name.code, - Diagnostics.A_rest_element_cannot_have_an_initializer.code, - Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern.code, - Diagnostics.A_rest_parameter_cannot_have_an_initializer.code, - Diagnostics.A_rest_parameter_must_be_last_in_a_parameter_list.code, - Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma.code, - Diagnostics.A_return_statement_cannot_be_used_inside_a_class_static_block.code, - Diagnostics.A_set_accessor_cannot_have_rest_parameter.code, - Diagnostics.A_set_accessor_must_have_exactly_one_parameter.code, - Diagnostics.An_export_declaration_can_only_be_used_at_the_top_level_of_a_module.code, - Diagnostics.An_export_declaration_cannot_have_modifiers.code, - Diagnostics.An_import_declaration_can_only_be_used_at_the_top_level_of_a_module.code, - Diagnostics.An_import_declaration_cannot_have_modifiers.code, - Diagnostics.An_object_member_cannot_be_declared_optional.code, - Diagnostics.Argument_of_dynamic_import_cannot_be_spread_element.code, - Diagnostics.Cannot_assign_to_private_method_0_Private_methods_are_not_writable.code, - Diagnostics.Cannot_redeclare_identifier_0_in_catch_clause.code, - Diagnostics.Catch_clause_variable_cannot_have_an_initializer.code, - Diagnostics.Class_decorators_can_t_be_used_with_static_private_identifier_Consider_removing_the_experimental_decorator.code, - Diagnostics.Classes_can_only_extend_a_single_class.code, - Diagnostics.Classes_may_not_have_a_field_named_constructor.code, - Diagnostics.Did_you_mean_to_use_a_Colon_An_can_only_follow_a_property_name_when_the_containing_object_literal_is_part_of_a_destructuring_pattern.code, - Diagnostics.Duplicate_label_0.code, - Diagnostics.Dynamic_imports_can_only_accept_a_module_specifier_and_an_optional_set_of_attributes_as_arguments.code, - Diagnostics.for_await_loops_cannot_be_used_inside_a_class_static_block.code, - Diagnostics.JSX_attributes_must_only_be_assigned_a_non_empty_expression.code, - Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name.code, - Diagnostics.JSX_expressions_may_not_use_the_comma_operator_Did_you_mean_to_write_an_array.code, - Diagnostics.JSX_property_access_expressions_cannot_include_JSX_namespace_names.code, - Diagnostics.Jump_target_cannot_cross_function_boundary.code, - Diagnostics.Line_terminator_not_permitted_before_arrow.code, - Diagnostics.Modifiers_cannot_appear_here.code, - Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement.code, - Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement.code, - Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies.code, - Diagnostics.Private_identifiers_are_only_allowed_in_class_bodies_and_may_only_be_used_as_part_of_a_class_member_declaration_property_access_or_on_the_left_hand_side_of_an_in_expression.code, - Diagnostics.Property_0_is_not_accessible_outside_class_1_because_it_has_a_private_identifier.code, - Diagnostics.Tagged_template_expressions_are_not_permitted_in_an_optional_chain.code, - Diagnostics.The_left_hand_side_of_a_for_of_statement_may_not_be_async.code, - Diagnostics.The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer.code, - Diagnostics.The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer.code, - Diagnostics.Trailing_comma_not_allowed.code, - Diagnostics.Variable_declaration_list_cannot_be_empty.code, - Diagnostics._0_and_1_operations_cannot_be_mixed_without_parentheses.code, - Diagnostics._0_expected.code, - Diagnostics._0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2.code, - Diagnostics._0_list_cannot_be_empty.code, - Diagnostics._0_modifier_already_seen.code, - Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration.code, - Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element.code, - Diagnostics._0_modifier_cannot_appear_on_a_parameter.code, - Diagnostics._0_modifier_cannot_appear_on_class_elements_of_this_kind.code, - Diagnostics._0_modifier_cannot_be_used_here.code, - Diagnostics._0_modifier_must_precede_1_modifier.code, - Diagnostics._0_declarations_can_only_be_declared_inside_a_block.code, - Diagnostics._0_declarations_must_be_initialized.code, - Diagnostics.extends_clause_already_seen.code, - Diagnostics.let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations.code, - Diagnostics.Class_constructor_may_not_be_a_generator.code, - Diagnostics.Class_constructor_may_not_be_an_accessor.code, - Diagnostics.await_expressions_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules.code, - Diagnostics.await_using_statements_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules.code, - Diagnostics.Private_field_0_must_be_declared_in_an_enclosing_class.code, - // Type errors - Diagnostics.This_condition_will_always_return_0_since_JavaScript_compares_objects_by_reference_not_value.code - ]); - emitSkippedWithNoDiagnostics = { diagnostics: emptyArray, sourceMaps: void 0, emittedFiles: void 0, emitSkipped: true }; + plainJSErrors = /* @__PURE__ */new Set([ + // binder errors + Diagnostics.Cannot_redeclare_block_scoped_variable_0.code, Diagnostics.A_module_cannot_have_multiple_default_exports.code, Diagnostics.Another_export_default_is_here.code, Diagnostics.The_first_export_default_is_here.code, Diagnostics.Identifier_expected_0_is_a_reserved_word_at_the_top_level_of_a_module.code, Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode.code, Diagnostics.Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here.code, Diagnostics.constructor_is_a_reserved_word.code, Diagnostics.delete_cannot_be_called_on_an_identifier_in_strict_mode.code, Diagnostics.Code_contained_in_a_class_is_evaluated_in_JavaScript_s_strict_mode_which_does_not_allow_this_use_of_0_For_more_information_see_https_Colon_Slash_Slashdeveloper_mozilla_org_Slashen_US_Slashdocs_SlashWeb_SlashJavaScript_SlashReference_SlashStrict_mode.code, Diagnostics.Invalid_use_of_0_Modules_are_automatically_in_strict_mode.code, Diagnostics.Invalid_use_of_0_in_strict_mode.code, Diagnostics.A_label_is_not_allowed_here.code, Diagnostics.with_statements_are_not_allowed_in_strict_mode.code, + // grammar errors + Diagnostics.A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement.code, Diagnostics.A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement.code, Diagnostics.A_class_declaration_without_the_default_modifier_must_have_a_name.code, Diagnostics.A_class_member_cannot_have_the_0_keyword.code, Diagnostics.A_comma_expression_is_not_allowed_in_a_computed_property_name.code, Diagnostics.A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement.code, Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement.code, Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement.code, Diagnostics.A_default_clause_cannot_appear_more_than_once_in_a_switch_statement.code, Diagnostics.A_default_export_must_be_at_the_top_level_of_a_file_or_module_declaration.code, Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context.code, Diagnostics.A_destructuring_declaration_must_have_an_initializer.code, Diagnostics.A_get_accessor_cannot_have_parameters.code, Diagnostics.A_rest_element_cannot_contain_a_binding_pattern.code, Diagnostics.A_rest_element_cannot_have_a_property_name.code, Diagnostics.A_rest_element_cannot_have_an_initializer.code, Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern.code, Diagnostics.A_rest_parameter_cannot_have_an_initializer.code, Diagnostics.A_rest_parameter_must_be_last_in_a_parameter_list.code, Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma.code, Diagnostics.A_return_statement_cannot_be_used_inside_a_class_static_block.code, Diagnostics.A_set_accessor_cannot_have_rest_parameter.code, Diagnostics.A_set_accessor_must_have_exactly_one_parameter.code, Diagnostics.An_export_declaration_can_only_be_used_at_the_top_level_of_a_module.code, Diagnostics.An_export_declaration_cannot_have_modifiers.code, Diagnostics.An_import_declaration_can_only_be_used_at_the_top_level_of_a_module.code, Diagnostics.An_import_declaration_cannot_have_modifiers.code, Diagnostics.An_object_member_cannot_be_declared_optional.code, Diagnostics.Argument_of_dynamic_import_cannot_be_spread_element.code, Diagnostics.Cannot_assign_to_private_method_0_Private_methods_are_not_writable.code, Diagnostics.Cannot_redeclare_identifier_0_in_catch_clause.code, Diagnostics.Catch_clause_variable_cannot_have_an_initializer.code, Diagnostics.Class_decorators_can_t_be_used_with_static_private_identifier_Consider_removing_the_experimental_decorator.code, Diagnostics.Classes_can_only_extend_a_single_class.code, Diagnostics.Classes_may_not_have_a_field_named_constructor.code, Diagnostics.Did_you_mean_to_use_a_Colon_An_can_only_follow_a_property_name_when_the_containing_object_literal_is_part_of_a_destructuring_pattern.code, Diagnostics.Duplicate_label_0.code, Diagnostics.Dynamic_imports_can_only_accept_a_module_specifier_and_an_optional_set_of_attributes_as_arguments.code, Diagnostics.for_await_loops_cannot_be_used_inside_a_class_static_block.code, Diagnostics.JSX_attributes_must_only_be_assigned_a_non_empty_expression.code, Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name.code, Diagnostics.JSX_expressions_may_not_use_the_comma_operator_Did_you_mean_to_write_an_array.code, Diagnostics.JSX_property_access_expressions_cannot_include_JSX_namespace_names.code, Diagnostics.Jump_target_cannot_cross_function_boundary.code, Diagnostics.Line_terminator_not_permitted_before_arrow.code, Diagnostics.Modifiers_cannot_appear_here.code, Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement.code, Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement.code, Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies.code, Diagnostics.Private_identifiers_are_only_allowed_in_class_bodies_and_may_only_be_used_as_part_of_a_class_member_declaration_property_access_or_on_the_left_hand_side_of_an_in_expression.code, Diagnostics.Property_0_is_not_accessible_outside_class_1_because_it_has_a_private_identifier.code, Diagnostics.Tagged_template_expressions_are_not_permitted_in_an_optional_chain.code, Diagnostics.The_left_hand_side_of_a_for_of_statement_may_not_be_async.code, Diagnostics.The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer.code, Diagnostics.The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer.code, Diagnostics.Trailing_comma_not_allowed.code, Diagnostics.Variable_declaration_list_cannot_be_empty.code, Diagnostics._0_and_1_operations_cannot_be_mixed_without_parentheses.code, Diagnostics._0_expected.code, Diagnostics._0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2.code, Diagnostics._0_list_cannot_be_empty.code, Diagnostics._0_modifier_already_seen.code, Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration.code, Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element.code, Diagnostics._0_modifier_cannot_appear_on_a_parameter.code, Diagnostics._0_modifier_cannot_appear_on_class_elements_of_this_kind.code, Diagnostics._0_modifier_cannot_be_used_here.code, Diagnostics._0_modifier_must_precede_1_modifier.code, Diagnostics._0_declarations_can_only_be_declared_inside_a_block.code, Diagnostics._0_declarations_must_be_initialized.code, Diagnostics.extends_clause_already_seen.code, Diagnostics.let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations.code, Diagnostics.Class_constructor_may_not_be_a_generator.code, Diagnostics.Class_constructor_may_not_be_an_accessor.code, Diagnostics.await_expressions_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules.code, Diagnostics.await_using_statements_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules.code, Diagnostics.Private_field_0_must_be_declared_in_an_enclosing_class.code, + // Type errors + Diagnostics.This_condition_will_always_return_0_since_JavaScript_compares_objects_by_reference_not_value.code]); + emitSkippedWithNoDiagnostics = { + diagnostics: emptyArray, + sourceMaps: void 0, + emittedFiles: void 0, + emitSkipped: true + }; } }); @@ -122551,31 +108755,43 @@ ${lanes.join("\n")} // src/compiler/builderState.ts function getFileEmitOutput(program, sourceFile, emitOnlyDtsFiles, cancellationToken, customTransformers, forceDtsEmit) { const outputFiles = []; - const { emitSkipped, diagnostics } = program.emit(sourceFile, writeFile2, cancellationToken, emitOnlyDtsFiles, customTransformers, forceDtsEmit); - return { outputFiles, emitSkipped, diagnostics }; + const { + emitSkipped, + diagnostics + } = program.emit(sourceFile, writeFile2, cancellationToken, emitOnlyDtsFiles, customTransformers, forceDtsEmit); + return { + outputFiles, + emitSkipped, + diagnostics + }; function writeFile2(fileName, text, writeByteOrderMark) { - outputFiles.push({ name: fileName, writeByteOrderMark, text }); + outputFiles.push({ + name: fileName, + writeByteOrderMark, + text + }); } } var BuilderState; var init_builderState = __esm({ "src/compiler/builderState.ts"() { "use strict"; + init_ts2(); - ((BuilderState2) => { + (BuilderState2 => { function createManyToManyPathMap() { function create2(forward, reverse, deleted) { const map2 = { - getKeys: (v) => reverse.get(v), - getValues: (k) => forward.get(k), + getKeys: v => reverse.get(v), + getValues: k => forward.get(k), keys: () => forward.keys(), - deleteKey: (k) => { - (deleted || (deleted = /* @__PURE__ */ new Set())).add(k); + deleteKey: k => { + (deleted || (deleted = /* @__PURE__ */new Set())).add(k); const set = forward.get(k); if (!set) { return false; } - set.forEach((v) => deleteFromMultimap(reverse, v, k)); + set.forEach(v => deleteFromMultimap(reverse, v, k)); forward.delete(k); return true; }, @@ -122583,12 +108799,12 @@ ${lanes.join("\n")} deleted == null ? void 0 : deleted.delete(k); const existingVSet = forward.get(k); forward.set(k, vSet); - existingVSet == null ? void 0 : existingVSet.forEach((v) => { + existingVSet == null ? void 0 : existingVSet.forEach(v => { if (!vSet.has(v)) { deleteFromMultimap(reverse, v, k); } }); - vSet.forEach((v) => { + vSet.forEach(v => { if (!(existingVSet == null ? void 0 : existingVSet.has(v))) { addToMultimap(reverse, v, k); } @@ -122598,18 +108814,14 @@ ${lanes.join("\n")} }; return map2; } - return create2( - /* @__PURE__ */ new Map(), - /* @__PURE__ */ new Map(), - /*deleted*/ - void 0 - ); + return create2( /* @__PURE__ */new Map(), /* @__PURE__ */new Map(), /*deleted*/ + void 0); } BuilderState2.createManyToManyPathMap = createManyToManyPathMap; function addToMultimap(map2, k, v) { let set = map2.get(k); if (!set) { - set = /* @__PURE__ */ new Set(); + set = /* @__PURE__ */new Set(); map2.set(k, set); } set.add(v); @@ -122625,7 +108837,7 @@ ${lanes.join("\n")} return false; } function getReferencedFilesFromImportedModuleSymbol(symbol) { - return mapDefined(symbol.declarations, (declaration) => { + return mapDefined(symbol.declarations, declaration => { var _a; return (_a = getSourceFileOfNode(declaration)) == null ? void 0 : _a.resolvedPath; }); @@ -122653,7 +108865,9 @@ ${lanes.join("\n")} addReferencedFile(referencedPath); } } - program.forEachResolvedTypeReferenceDirective(({ resolvedTypeReferenceDirective }) => { + program.forEachResolvedTypeReferenceDirective(({ + resolvedTypeReferenceDirective + }) => { if (!resolvedTypeReferenceDirective) { return; } @@ -122664,11 +108878,9 @@ ${lanes.join("\n")} 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); } } @@ -122690,7 +108902,7 @@ ${lanes.join("\n")} } } function addReferencedFile(referencedPath) { - (referencedFiles || (referencedFiles = /* @__PURE__ */ new Set())).add(referencedPath); + (referencedFiles || (referencedFiles = /* @__PURE__ */new Set())).add(referencedPath); } } function canReuseOldState(newReferencedMap, oldState) { @@ -122699,7 +108911,7 @@ ${lanes.join("\n")} BuilderState2.canReuseOldState = canReuseOldState; function create(newProgram, oldState, disableUseFileVersionAsSignature) { var _a, _b, _c; - const fileInfos = /* @__PURE__ */ new Map(); + const fileInfos = /* @__PURE__ */new Map(); const options = newProgram.getCompilerOptions(); const isOutFile = outFile(options); const referencedMap = options.module !== 0 /* None */ && !isOutFile ? createManyToManyPathMap() : void 0; @@ -122746,13 +108958,7 @@ ${lanes.join("\n")} BuilderState2.releaseCache = releaseCache2; function getFilesAffectedBy(state, programOfThisState, path, cancellationToken, host) { var _a, _b; - const result = getFilesAffectedByWithOldState( - state, - programOfThisState, - path, - cancellationToken, - host - ); + const result = getFilesAffectedByWithOldState(state, programOfThisState, path, cancellationToken, host); (_a = state.oldSignatures) == null ? void 0 : _a.clear(); (_b = state.oldExportedModulesMap) == null ? void 0 : _b.clear(); return result; @@ -122771,39 +108977,22 @@ ${lanes.join("\n")} BuilderState2.getFilesAffectedByWithOldState = getFilesAffectedByWithOldState; function updateSignatureOfFile(state, signature, path) { state.fileInfos.get(path).signature = signature; - (state.hasCalledUpdateShapeSignature || (state.hasCalledUpdateShapeSignature = /* @__PURE__ */ new Set())).add(path); + (state.hasCalledUpdateShapeSignature || (state.hasCalledUpdateShapeSignature = /* @__PURE__ */new Set())).add(path); } BuilderState2.updateSignatureOfFile = updateSignatureOfFile; function computeDtsSignature(programOfThisState, sourceFile, cancellationToken, host, onNewSignature) { - programOfThisState.emit( - sourceFile, - (fileName, text, _writeByteOrderMark, _onError, sourceFiles, data) => { - Debug.assert(isDeclarationFileName(fileName), `File extension for signature expected to be dts: Got:: ${fileName}`); - onNewSignature( - computeSignatureWithDiagnostics( - programOfThisState, - sourceFile, - text, - host, - data - ), - sourceFiles - ); - }, - cancellationToken, - /*emitOnly*/ - true, - /*customTransformers*/ - void 0, - /*forceDtsEmit*/ - true - ); + programOfThisState.emit(sourceFile, (fileName, text, _writeByteOrderMark, _onError, sourceFiles, data) => { + Debug.assert(isDeclarationFileName(fileName), `File extension for signature expected to be dts: Got:: ${fileName}`); + onNewSignature(computeSignatureWithDiagnostics(programOfThisState, sourceFile, text, host, data), sourceFiles); + }, cancellationToken, /*emitOnly*/ + true, /*customTransformers*/ + void 0, /*forceDtsEmit*/ + true); } 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; @@ -122818,7 +109007,7 @@ ${lanes.join("\n")} if (latestSignature === void 0) { latestSignature = sourceFile.version; if (state.exportedModulesMap && latestSignature !== prevSignature) { - (state.oldExportedModulesMap || (state.oldExportedModulesMap = /* @__PURE__ */ new Map())).set(sourceFile.resolvedPath, state.exportedModulesMap.getValues(sourceFile.resolvedPath) || false); + (state.oldExportedModulesMap || (state.oldExportedModulesMap = /* @__PURE__ */new Map())).set(sourceFile.resolvedPath, state.exportedModulesMap.getValues(sourceFile.resolvedPath) || false); const references = state.referencedMap ? state.referencedMap.getValues(sourceFile.resolvedPath) : void 0; if (references) { state.exportedModulesMap.set(sourceFile.resolvedPath, references); @@ -122827,16 +109016,15 @@ ${lanes.join("\n")} } } } - (state.oldSignatures || (state.oldSignatures = /* @__PURE__ */ new Map())).set(sourceFile.resolvedPath, prevSignature || false); - (state.hasCalledUpdateShapeSignature || (state.hasCalledUpdateShapeSignature = /* @__PURE__ */ new Set())).add(sourceFile.resolvedPath); + (state.oldSignatures || (state.oldSignatures = /* @__PURE__ */new Map())).set(sourceFile.resolvedPath, prevSignature || false); + (state.hasCalledUpdateShapeSignature || (state.hasCalledUpdateShapeSignature = /* @__PURE__ */new Set())).add(sourceFile.resolvedPath); info.signature = latestSignature; return latestSignature !== prevSignature; } BuilderState2.updateShapeSignature = updateShapeSignature; function updateExportedModules(state, sourceFile, exportedModulesFromDeclarationEmit) { - if (!state.exportedModulesMap) - return; - (state.oldExportedModulesMap || (state.oldExportedModulesMap = /* @__PURE__ */ new Map())).set(sourceFile.resolvedPath, state.exportedModulesMap.getValues(sourceFile.resolvedPath) || false); + if (!state.exportedModulesMap) return; + (state.oldExportedModulesMap || (state.oldExportedModulesMap = /* @__PURE__ */new Map())).set(sourceFile.resolvedPath, state.exportedModulesMap.getValues(sourceFile.resolvedPath) || false); const exportedModules = getExportedModules(exportedModulesFromDeclarationEmit); if (exportedModules) { state.exportedModulesMap.set(sourceFile.resolvedPath, exportedModules); @@ -122847,11 +109035,10 @@ ${lanes.join("\n")} BuilderState2.updateExportedModules = updateExportedModules; function getExportedModules(exportedModulesFromDeclarationEmit) { let exportedModules; - exportedModulesFromDeclarationEmit == null ? void 0 : exportedModulesFromDeclarationEmit.forEach( - (symbol) => getReferencedFilesFromImportedModuleSymbol(symbol).forEach( - (path) => (exportedModules ?? (exportedModules = /* @__PURE__ */ new Set())).add(path) - ) - ); + exportedModulesFromDeclarationEmit == null ? void 0 : exportedModulesFromDeclarationEmit.forEach(symbol => getReferencedFilesFromImportedModuleSymbol(symbol).forEach(path => { + var _exportedModules; + return ((_exportedModules = exportedModules) !== null && _exportedModules !== void 0 ? _exportedModules : exportedModules = /* @__PURE__ */new Set()).add(path); + })); return exportedModules; } BuilderState2.getExportedModules = getExportedModules; @@ -122863,7 +109050,7 @@ ${lanes.join("\n")} if (!state.referencedMap || isFileAffectingGlobalScope(sourceFile)) { return getAllFileNames(state, programOfThisState); } - const seenMap = /* @__PURE__ */ new Set(); + const seenMap = /* @__PURE__ */new Set(); const queue = [sourceFile.resolvedPath]; while (queue.length) { const path = queue.pop(); @@ -122877,16 +109064,17 @@ ${lanes.join("\n")} } } } - return arrayFrom(mapDefinedIterator(seenMap.keys(), (path) => { + return arrayFrom(mapDefinedIterator(seenMap.keys(), path => { + var _ref40; var _a; - return ((_a = programOfThisState.getSourceFileByPath(path)) == null ? void 0 : _a.fileName) ?? path; + return (_ref40 = (_a = programOfThisState.getSourceFileByPath(path)) == null ? void 0 : _a.fileName) !== null && _ref40 !== void 0 ? _ref40 : path; })); } BuilderState2.getAllDependencies = getAllDependencies; function getAllFileNames(state, programOfThisState) { if (!state.allFileNames) { const sourceFiles = programOfThisState.getSourceFiles(); - state.allFileNames = sourceFiles === emptyArray ? emptyArray : sourceFiles.map((file) => file.fileName); + state.allFileNames = sourceFiles === emptyArray ? emptyArray : sourceFiles.map(file => file.fileName); } return state.allFileNames; } @@ -122904,7 +109092,7 @@ ${lanes.join("\n")} return true; } function containsGlobalScopeAugmentation(sourceFile) { - return some(sourceFile.moduleAugmentations, (augmentation) => isGlobalScopeAugmentation(augmentation.parent)); + return some(sourceFile.moduleAugmentations, augmentation => isGlobalScopeAugmentation(augmentation.parent)); } function isFileAffectingGlobalScope(sourceFile) { return containsGlobalScopeAugmentation(sourceFile) || !isExternalOrCommonJsModule(sourceFile) && !isJsonSourceFile(sourceFile) && !containsOnlyAmbientModules(sourceFile); @@ -122914,8 +109102,7 @@ ${lanes.join("\n")} return state.allFilesExcludingDefaultLibraryFile; } let result; - if (firstSourceFile) - addSourceFile(firstSourceFile); + if (firstSourceFile) addSourceFile(firstSourceFile); for (const sourceFile of programOfThisState.getSourceFiles()) { if (sourceFile !== firstSourceFile) { addSourceFile(sourceFile); @@ -122945,7 +109132,7 @@ ${lanes.join("\n")} if (compilerOptions && (getIsolatedModules(compilerOptions) || outFile(compilerOptions))) { return [sourceFileWithUpdatedShape]; } - const seenFileNamesMap = /* @__PURE__ */ new Map(); + const seenFileNamesMap = /* @__PURE__ */new Map(); seenFileNamesMap.set(sourceFileWithUpdatedShape.resolvedPath, sourceFileWithUpdatedShape); const queue = getReferencedByPaths(state, sourceFileWithUpdatedShape.resolvedPath); while (queue.length > 0) { @@ -122958,7 +109145,7 @@ ${lanes.join("\n")} } } } - return arrayFrom(mapDefinedIterator(seenFileNamesMap.values(), (value) => value)); + return arrayFrom(mapDefinedIterator(seenFileNamesMap.values(), value => value)); } })(BuilderState || (BuilderState = {})); } @@ -122967,64 +109154,51 @@ ${lanes.join("\n")} // 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) { - return map1 === map2 || map1 !== void 0 && map2 !== void 0 && map1.size === map2.size && !forEachKey(map1, (key) => !map2.has(key)); + return map1 === map2 || map1 !== void 0 && map2 !== void 0 && map1.size === map2.size && !forEachKey(map1, key => !map2.has(key)); } function createBuilderProgramState(newProgram, oldState) { var _a, _b; - const state = BuilderState.create( - newProgram, - oldState, - /*disableUseFileVersionAsSignature*/ - false - ); + const state = BuilderState.create(newProgram, oldState, /*disableUseFileVersionAsSignature*/ + false); state.program = newProgram; const compilerOptions = newProgram.getCompilerOptions(); state.compilerOptions = compilerOptions; const outFilePath = outFile(compilerOptions); if (!outFilePath) { - state.semanticDiagnosticsPerFile = /* @__PURE__ */ new Map(); + state.semanticDiagnosticsPerFile = /* @__PURE__ */new Map(); } else if (compilerOptions.composite && (oldState == null ? void 0 : oldState.outSignature) && outFilePath === outFile(oldState == null ? void 0 : oldState.compilerOptions)) { state.outSignature = oldState.outSignature && getEmitSignatureFromOldSignature(compilerOptions, oldState.compilerOptions, oldState.outSignature); } - state.changedFilesSet = /* @__PURE__ */ new Set(); + state.changedFilesSet = /* @__PURE__ */new Set(); state.latestChangedDtsFile = compilerOptions.composite ? oldState == null ? void 0 : oldState.latestChangedDtsFile : void 0; const useOldState = BuilderState.canReuseOldState(state.referencedMap, oldState); const oldCompilerOptions = useOldState ? oldState.compilerOptions : void 0; const canCopySemanticDiagnostics = useOldState && oldState.semanticDiagnosticsPerFile && !!state.semanticDiagnosticsPerFile && !compilerOptionsAffectSemanticDiagnostics(compilerOptions, oldCompilerOptions); const canCopyEmitSignatures = compilerOptions.composite && (oldState == null ? void 0 : oldState.emitSignatures) && !outFilePath && !compilerOptionsAffectDeclarationPath(compilerOptions, oldState.compilerOptions); if (useOldState) { - (_a = oldState.changedFilesSet) == null ? void 0 : _a.forEach((value) => state.changedFilesSet.add(value)); + (_a = oldState.changedFilesSet) == null ? void 0 : _a.forEach(value => state.changedFilesSet.add(value)); if (!outFilePath && ((_b = oldState.affectedFilesPendingEmit) == null ? void 0 : _b.size)) { state.affectedFilesPendingEmit = new Map(oldState.affectedFilesPendingEmit); - state.seenAffectedFiles = /* @__PURE__ */ new Set(); + state.seenAffectedFiles = /* @__PURE__ */new Set(); } state.programEmitPending = oldState.programEmitPending; } else { @@ -123037,27 +109211,27 @@ ${lanes.join("\n")} state.fileInfos.forEach((info, sourceFilePath) => { let oldInfo; let newReferences; - if (!useOldState || // File wasn't present in old state - !(oldInfo = oldState.fileInfos.get(sourceFilePath)) || // versions dont match - oldInfo.version !== info.version || // Implied formats dont match - oldInfo.impliedFormat !== info.impliedFormat || // Referenced files changed - !hasSameKeys(newReferences = referencedMap && referencedMap.getValues(sourceFilePath), oldReferencedMap && oldReferencedMap.getValues(sourceFilePath)) || // Referenced file was deleted in the new program - newReferences && forEachKey(newReferences, (path) => !state.fileInfos.has(path) && oldState.fileInfos.has(path))) { + if (!useOldState || + // File wasn't present in old state + !(oldInfo = oldState.fileInfos.get(sourceFilePath)) || + // versions dont match + oldInfo.version !== info.version || + // Implied formats dont match + oldInfo.impliedFormat !== info.impliedFormat || + // Referenced files changed + !hasSameKeys(newReferences = referencedMap && referencedMap.getValues(sourceFilePath), oldReferencedMap && oldReferencedMap.getValues(sourceFilePath)) || + // Referenced file was deleted in the new program + newReferences && forEachKey(newReferences, path => !state.fileInfos.has(path) && oldState.fileInfos.has(path))) { addFileToChangeSet(state, sourceFilePath); } else if (canCopySemanticDiagnostics) { const sourceFile = newProgram.getSourceFileByPath(sourceFilePath); - 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) - ); + state.semanticDiagnosticsPerFile.set(sourceFilePath, oldState.hasReusableDiagnostic ? convertToDiagnostics(diagnostics, newProgram) : repopulateDiagnostics(diagnostics, newProgram)); if (!state.semanticDiagnosticsFromOldState) { - state.semanticDiagnosticsFromOldState = /* @__PURE__ */ new Set(); + state.semanticDiagnosticsFromOldState = /* @__PURE__ */new Set(); } state.semanticDiagnosticsFromOldState.add(sourceFilePath); } @@ -123065,39 +109239,30 @@ ${lanes.join("\n")} if (canCopyEmitSignatures) { const oldEmitSignature = oldState.emitSignatures.get(sourceFilePath); if (oldEmitSignature) { - (state.emitSignatures ?? (state.emitSignatures = /* @__PURE__ */ new Map())).set(sourceFilePath, getEmitSignatureFromOldSignature(compilerOptions, oldState.compilerOptions, oldEmitSignature)); + var _state$emitSignatures; + ((_state$emitSignatures = state.emitSignatures) !== null && _state$emitSignatures !== void 0 ? _state$emitSignatures : state.emitSignatures = /* @__PURE__ */new Map()).set(sourceFilePath, getEmitSignatureFromOldSignature(compilerOptions, oldState.compilerOptions, oldEmitSignature)); } } }); 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; })) { - BuilderState.getAllFilesExcludingDefaultLibraryFile( - state, - newProgram, - /*firstSourceFile*/ - void 0 - ).forEach((file) => addFileToChangeSet(state, file.resolvedPath)); + BuilderState.getAllFilesExcludingDefaultLibraryFile(state, newProgram, /*firstSourceFile*/ + void 0).forEach(file => addFileToChangeSet(state, file.resolvedPath)); } else if (oldCompilerOptions) { const pendingEmitKind = compilerOptionsAffectEmit(compilerOptions, oldCompilerOptions) ? getBuilderFileEmit(compilerOptions) : getPendingEmitKind(compilerOptions, oldCompilerOptions); if (pendingEmitKind !== 0 /* None */) { if (!outFilePath) { - newProgram.getSourceFiles().forEach((f) => { + newProgram.getSourceFiles().forEach(f => { if (!state.changedFilesSet.has(f.resolvedPath)) { - addToAffectedFilesPendingEmit( - state, - f.resolvedPath, - pendingEmitKind - ); + addToAffectedFilesPendingEmit(state, f.resolvedPath, pendingEmitKind); } }); Debug.assert(!state.seenAffectedFiles || !state.seenAffectedFiles.size); - state.seenAffectedFiles = state.seenAffectedFiles || /* @__PURE__ */ new Set(); + state.seenAffectedFiles = state.seenAffectedFiles || /* @__PURE__ */new Set(); state.buildInfoEmitPending = true; } else { state.programEmitPending = state.programEmitPending ? state.programEmitPending | pendingEmitKind : pendingEmitKind; @@ -123105,10 +109270,8 @@ ${lanes.join("\n")} } } if (outFilePath && !state.changedFilesSet.size) { - if (useOldState) - state.bundle = oldState.bundle; - if (some(newProgram.getProjectReferences(), (ref) => !!ref.prepend)) - state.programEmitPending = getBuilderFileEmit(compilerOptions); + if (useOldState) state.bundle = oldState.bundle; + if (some(newProgram.getProjectReferences(), ref => !!ref.prepend)) state.programEmitPending = getBuilderFileEmit(compilerOptions); } return state; } @@ -123118,25 +109281,24 @@ ${lanes.join("\n")} state.programEmitPending = void 0; } function getEmitSignatureFromOldSignature(options, oldOptions, oldEmitSignature) { - return !!options.declarationMap === !!oldOptions.declarationMap ? ( - // Use same format of signature - oldEmitSignature - ) : ( - // Convert to different format - isString(oldEmitSignature) ? [oldEmitSignature] : oldEmitSignature[0] - ); + return !!options.declarationMap === !!oldOptions.declarationMap ? + // Use same format of signature + oldEmitSignature : + // Convert to different format + isString(oldEmitSignature) ? [oldEmitSignature] : oldEmitSignature[0]; } function repopulateDiagnostics(diagnostics, newProgram) { - if (!diagnostics.length) - return diagnostics; - return sameMap(diagnostics, (diag2) => { - if (isString(diag2.messageText)) - return diag2; - const repopulatedChain = convertOrRepopulateDiagnosticMessageChain(diag2.messageText, diag2.file, newProgram, (chain) => { + if (!diagnostics.length) return diagnostics; + return sameMap(diagnostics, diag2 => { + if (isString(diag2.messageText)) return diag2; + const repopulatedChain = convertOrRepopulateDiagnosticMessageChain(diag2.messageText, diag2.file, newProgram, chain => { var _a; return (_a = chain.repopulateInfo) == null ? void 0 : _a.call(chain); }); - return repopulatedChain === diag2.messageText ? diag2 : { ...diag2, messageText: repopulatedChain }; + return repopulatedChain === diag2.messageText ? diag2 : { + ...diag2, + messageText: repopulatedChain + }; }); } function convertOrRepopulateDiagnosticMessageChain(chain, sourceFile, newProgram, repopulateInfo) { @@ -123148,37 +109310,44 @@ ${lanes.join("\n")} }; } const next = convertOrRepopulateDiagnosticMessageChainArray(chain.next, sourceFile, newProgram, repopulateInfo); - return next === chain.next ? chain : { ...chain, next }; + return next === chain.next ? chain : { + ...chain, + next + }; } function convertOrRepopulateDiagnosticMessageChainArray(array, sourceFile, newProgram, repopulateInfo) { - return sameMap(array, (chain) => convertOrRepopulateDiagnosticMessageChain(chain, sourceFile, newProgram, repopulateInfo)); + return sameMap(array, chain => convertOrRepopulateDiagnosticMessageChain(chain, sourceFile, newProgram, repopulateInfo)); } function convertToDiagnostics(diagnostics, newProgram) { - if (!diagnostics.length) - return emptyArray; + if (!diagnostics.length) return emptyArray; let buildInfoDirectory; - return diagnostics.map((diagnostic) => { + return diagnostics.map(diagnostic => { const result = convertToDiagnosticRelatedInformation(diagnostic, 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; + const { + relatedInformation + } = diagnostic; + result.relatedInformation = relatedInformation ? relatedInformation.length ? relatedInformation.map(r => convertToDiagnosticRelatedInformation(r, newProgram, toPathInBuildInfoDirectory)) : [] : void 0; return result; }); function toPathInBuildInfoDirectory(path) { - buildInfoDirectory ?? (buildInfoDirectory = getDirectoryPath(getNormalizedAbsolutePath(getTsBuildInfoEmitOutputFilePath(newProgram.getCompilerOptions()), newProgram.getCurrentDirectory()))); + var _buildInfoDirectory; + (_buildInfoDirectory = buildInfoDirectory) !== null && _buildInfoDirectory !== void 0 ? _buildInfoDirectory : buildInfoDirectory = getDirectoryPath(getNormalizedAbsolutePath(getTsBuildInfoEmitOutputFilePath(newProgram.getCompilerOptions()), newProgram.getCurrentDirectory())); return toPath(path, buildInfoDirectory, newProgram.getCanonicalFileName); } } function convertToDiagnosticRelatedInformation(diagnostic, newProgram, toPath3) { - const { file } = diagnostic; + const { + file + } = diagnostic; const sourceFile = file ? newProgram.getSourceFileByPath(toPath3(file)) : void 0; return { ...diagnostic, file: sourceFile, - messageText: isString(diagnostic.messageText) ? diagnostic.messageText : convertOrRepopulateDiagnosticMessageChain(diagnostic.messageText, sourceFile, newProgram, (chain) => chain.info) + messageText: isString(diagnostic.messageText) ? diagnostic.messageText : convertOrRepopulateDiagnosticMessageChain(diagnostic.messageText, sourceFile, newProgram, chain => chain.info) }; } function releaseCache(state) { @@ -123207,8 +109376,7 @@ ${lanes.join("\n")} state.outSignature = savedEmitState.outSignature; state.latestChangedDtsFile = savedEmitState.latestChangedDtsFile; state.hasChangedEmitSignature = savedEmitState.hasChangedEmitSignature; - 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)); @@ -123216,7 +109384,9 @@ ${lanes.join("\n")} function getNextAffectedFile(state, cancellationToken, host) { var _a, _b; while (true) { - const { affectedFiles } = state; + const { + affectedFiles + } = state; if (affectedFiles) { const seenAffectedFiles = state.seenAffectedFiles; let affectedFilesIndex = state.affectedFilesIndex; @@ -123225,12 +109395,7 @@ ${lanes.join("\n")} if (!seenAffectedFiles.has(affectedFile.resolvedPath)) { state.affectedFilesIndex = affectedFilesIndex; addToAffectedFilesPendingEmit(state, affectedFile.resolvedPath, getBuilderFileEmit(state.compilerOptions)); - handleDtsMayChangeOfAffectedFile( - state, - affectedFile, - cancellationToken, - host - ); + handleDtsMayChangeOfAffectedFile(state, affectedFile, cancellationToken, host); return affectedFile; } affectedFilesIndex++; @@ -123251,37 +109416,24 @@ ${lanes.join("\n")} Debug.assert(!state.semanticDiagnosticsPerFile); return program; } - state.affectedFiles = BuilderState.getFilesAffectedByWithOldState( - state, - program, - nextKey.value, - cancellationToken, - host - ); + state.affectedFiles = BuilderState.getFilesAffectedByWithOldState(state, program, nextKey.value, 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); @@ -123291,10 +109443,11 @@ ${lanes.join("\n")} } 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 removeDiagnosticsOfLibraryFiles(state) { @@ -123302,30 +109455,18 @@ ${lanes.join("\n")} state.cleanedDiagnosticsOfLibFiles = true; const program = Debug.checkDefined(state.program); const options = program.getCompilerOptions(); - forEach(program.getSourceFiles(), (f) => program.isSourceFileDefaultLibrary(f) && !skipTypeChecking(f, options, program) && removeSemanticDiagnosticsOf(state, f.resolvedPath)); + forEach(program.getSourceFiles(), f => program.isSourceFileDefaultLibrary(f) && !skipTypeChecking(f, options, program) && removeSemanticDiagnosticsOf(state, f.resolvedPath)); } } function handleDtsMayChangeOfAffectedFile(state, affectedFile, cancellationToken, host) { removeSemanticDiagnosticsOf(state, affectedFile.resolvedPath); if (state.allFilesExcludingDefaultLibraryFile === state.affectedFiles) { removeDiagnosticsOfLibraryFiles(state); - BuilderState.updateShapeSignature( - state, - Debug.checkDefined(state.program), - affectedFile, - cancellationToken, - host - ); + BuilderState.updateShapeSignature(state, Debug.checkDefined(state.program), affectedFile, cancellationToken, host); return; } - if (state.compilerOptions.assumeChangesOnlyAffectDirectDependencies) - return; - handleDtsMayChangeOfReferencingExportOfAffectedFile( - state, - affectedFile, - cancellationToken, - host - ); + if (state.compilerOptions.assumeChangesOnlyAffectDirectDependencies) return; + handleDtsMayChangeOfReferencingExportOfAffectedFile(state, affectedFile, cancellationToken, host); } function handleDtsMayChangeOf(state, path, cancellationToken, host) { removeSemanticDiagnosticsOf(state, path); @@ -123333,21 +109474,15 @@ ${lanes.join("\n")} const program = Debug.checkDefined(state.program); const sourceFile = program.getSourceFileByPath(path); if (sourceFile) { - BuilderState.updateShapeSignature( - state, - program, - sourceFile, - cancellationToken, - host, - /*useFileVersionAsSignature*/ - true - ); + BuilderState.updateShapeSignature(state, program, sourceFile, cancellationToken, host, /*useFileVersionAsSignature*/ + true); if (getEmitDeclarations(state.compilerOptions)) { addToAffectedFilesPendingEmit(state, path, state.compilerOptions.declarationMap ? 24 /* AllDts */ : 8 /* Dts */); } } } } + function removeSemanticDiagnosticsOf(state, path) { if (!state.semanticDiagnosticsFromOldState) { return true; @@ -123363,40 +109498,25 @@ ${lanes.join("\n")} } function handleDtsMayChangeOfGlobalScope(state, filePath, cancellationToken, host) { var _a; - if (!((_a = state.fileInfos.get(filePath)) == null ? void 0 : _a.affectsGlobalScope)) - return false; - BuilderState.getAllFilesExcludingDefaultLibraryFile( - state, - state.program, - /*firstSourceFile*/ - void 0 - ).forEach( - (file) => handleDtsMayChangeOf( - state, - file.resolvedPath, - cancellationToken, - host - ) - ); + if (!((_a = state.fileInfos.get(filePath)) == null ? void 0 : _a.affectsGlobalScope)) return false; + BuilderState.getAllFilesExcludingDefaultLibraryFile(state, state.program, /*firstSourceFile*/ + void 0).forEach(file => handleDtsMayChangeOf(state, file.resolvedPath, cancellationToken, host)); removeDiagnosticsOfLibraryFiles(state); return true; } function handleDtsMayChangeOfReferencingExportOfAffectedFile(state, affectedFile, cancellationToken, host) { var _a; - if (!state.exportedModulesMap || !state.changedFilesSet.has(affectedFile.resolvedPath)) - return; - if (!isChangedSignature(state, affectedFile.resolvedPath)) - return; + if (!state.exportedModulesMap || !state.changedFilesSet.has(affectedFile.resolvedPath)) return; + if (!isChangedSignature(state, affectedFile.resolvedPath)) return; if (getIsolatedModules(state.compilerOptions)) { - const seenFileNamesMap = /* @__PURE__ */ new Map(); + const seenFileNamesMap = /* @__PURE__ */new Map(); seenFileNamesMap.set(affectedFile.resolvedPath, true); const queue = BuilderState.getReferencedByPaths(state, affectedFile.resolvedPath); while (queue.length > 0) { const currentPath = queue.pop(); if (!seenFileNamesMap.has(currentPath)) { seenFileNamesMap.set(currentPath, true); - if (handleDtsMayChangeOfGlobalScope(state, currentPath, cancellationToken, host)) - return; + if (handleDtsMayChangeOfGlobalScope(state, currentPath, cancellationToken, host)) return; handleDtsMayChangeOf(state, currentPath, cancellationToken, host); if (isChangedSignature(state, currentPath)) { const currentSourceFile = Debug.checkDefined(state.program).getSourceFileByPath(currentPath); @@ -123405,53 +109525,28 @@ ${lanes.join("\n")} } } } - const seenFileAndExportsOfFile = /* @__PURE__ */ new Set(); - (_a = state.exportedModulesMap.getKeys(affectedFile.resolvedPath)) == null ? void 0 : _a.forEach((exportedFromPath) => { - if (handleDtsMayChangeOfGlobalScope(state, exportedFromPath, cancellationToken, host)) - return true; + const seenFileAndExportsOfFile = /* @__PURE__ */new Set(); + (_a = state.exportedModulesMap.getKeys(affectedFile.resolvedPath)) == null ? void 0 : _a.forEach(exportedFromPath => { + if (handleDtsMayChangeOfGlobalScope(state, exportedFromPath, cancellationToken, host)) return true; const references = state.referencedMap.getKeys(exportedFromPath); - return references && forEachKey(references, (filePath) => handleDtsMayChangeOfFileAndExportsOfFile( - state, - filePath, - seenFileAndExportsOfFile, - cancellationToken, - host - )); + return references && forEachKey(references, filePath => handleDtsMayChangeOfFileAndExportsOfFile(state, filePath, seenFileAndExportsOfFile, cancellationToken, host)); }); } function handleDtsMayChangeOfFileAndExportsOfFile(state, filePath, seenFileAndExportsOfFile, cancellationToken, host) { var _a, _b; - if (!tryAddToSet(seenFileAndExportsOfFile, filePath)) - return void 0; - if (handleDtsMayChangeOfGlobalScope(state, filePath, cancellationToken, host)) - return true; + if (!tryAddToSet(seenFileAndExportsOfFile, filePath)) return void 0; + if (handleDtsMayChangeOfGlobalScope(state, filePath, cancellationToken, host)) return true; handleDtsMayChangeOf(state, filePath, cancellationToken, host); - (_a = state.exportedModulesMap.getKeys(filePath)) == null ? void 0 : _a.forEach( - (exportedFromPath) => handleDtsMayChangeOfFileAndExportsOfFile( - state, - exportedFromPath, - seenFileAndExportsOfFile, - cancellationToken, - host - ) - ); - (_b = state.referencedMap.getKeys(filePath)) == null ? void 0 : _b.forEach( - (referencingFilePath) => !seenFileAndExportsOfFile.has(referencingFilePath) && // Not already removed diagnostic file - handleDtsMayChangeOf( - // Dont add to seen since this is not yet done with the export removal - state, - referencingFilePath, - cancellationToken, - host - ) - ); + (_a = state.exportedModulesMap.getKeys(filePath)) == null ? void 0 : _a.forEach(exportedFromPath => handleDtsMayChangeOfFileAndExportsOfFile(state, exportedFromPath, seenFileAndExportsOfFile, cancellationToken, host)); + (_b = state.referencedMap.getKeys(filePath)) == null ? void 0 : _b.forEach(referencingFilePath => !seenFileAndExportsOfFile.has(referencingFilePath) && + // Not already removed diagnostic file + handleDtsMayChangeOf( + // Dont add to seen since this is not yet done with the export removal + state, referencingFilePath, cancellationToken, host)); return void 0; } function getSemanticDiagnosticsOfFile(state, sourceFile, cancellationToken) { - return concatenate( - getBinderAndCheckerDiagnosticsOfFile(state, sourceFile, cancellationToken), - Debug.checkDefined(state.program).getProgramDiagnostics(sourceFile) - ); + return concatenate(getBinderAndCheckerDiagnosticsOfFile(state, sourceFile, cancellationToken), Debug.checkDefined(state.program).getProgramDiagnostics(sourceFile)); } function getBinderAndCheckerDiagnosticsOfFile(state, sourceFile, cancellationToken) { const path = sourceFile.resolvedPath; @@ -123476,13 +109571,18 @@ ${lanes.join("\n")} 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 fileNameToFileId = /* @__PURE__ */new Map(); const root = []; if (outFile(state.compilerOptions)) { const fileInfos2 = arrayFrom(state.fileInfos.entries(), ([key, value]) => { const fileId = toFileId(key); tryAddRoot(key, fileId); - return value.impliedFormat ? { version: value.version, impliedFormat: value.impliedFormat, signature: void 0, affectsGlobalScope: void 0 } : value.version; + return value.impliedFormat ? { + version: value.version, + impliedFormat: value.impliedFormat, + signature: void 0, + affectsGlobalScope: void 0 + } : value.version; }); const program2 = { fileNames, @@ -123491,16 +109591,20 @@ ${lanes.join("\n")} options: convertToProgramBuildInfoCompilerOptions(state.compilerOptions), outSignature: state.outSignature, latestChangedDtsFile, - pendingEmit: !state.programEmitPending ? void 0 : ( - // Pending is undefined or None is encoded as undefined - state.programEmitPending === getBuilderFileEmit(state.compilerOptions) ? false : ( - // Pending emit is same as deteremined by compilerOptions - state.programEmitPending - ) - ) + pendingEmit: !state.programEmitPending ? void 0 : + // Pending is undefined or None is encoded as undefined + state.programEmitPending === getBuilderFileEmit(state.compilerOptions) ? false : + // Pending emit is same as deteremined by compilerOptions + state.programEmitPending // Actual value }; - const { js, dts, commonSourceDirectory, sourceFiles } = bundle; + + const { + js, + dts, + commonSourceDirectory, + sourceFiles + } = bundle; state.bundle = bundle = { commonSourceDirectory, sourceFiles, @@ -123524,52 +109628,53 @@ ${lanes.join("\n")} if (!isJsonSourceFile(file) && sourceFileMayBeEmitted(file, state.program)) { const emitSignature = (_b2 = state.emitSignatures) == null ? void 0 : _b2.get(key); if (emitSignature !== actualSignature) { - (emitSignatures || (emitSignatures = [])).push( - 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 - [fileId, !isString(emitSignature) && emitSignature[0] === actualSignature ? emptyArray : emitSignature] - ) - ); + (emitSignatures || (emitSignatures = [])).push(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 + [fileId, !isString(emitSignature) && emitSignature[0] === actualSignature ? emptyArray : emitSignature]); } } } - return value.version === actualSignature ? value.affectsGlobalScope || value.impliedFormat ? ( - // If file version is same as signature, dont serialize signature - { version: value.version, signature: void 0, affectsGlobalScope: value.affectsGlobalScope, impliedFormat: value.impliedFormat } - ) : ( - // If file info only contains version and signature and both are same we can just write string - value.version - ) : actualSignature !== void 0 ? ( - // If signature is not same as version, encode signature in the fileInfo - oldSignature === void 0 ? ( - // If we havent computed signature, use fileInfo as is - value - ) : ( - // Serialize fileInfo with new updated signature - { version: value.version, signature: actualSignature, affectsGlobalScope: value.affectsGlobalScope, impliedFormat: value.impliedFormat } - ) - ) : ( - // Signature of the FileInfo is undefined, serialize it as false - { version: value.version, signature: false, affectsGlobalScope: value.affectsGlobalScope, impliedFormat: value.impliedFormat } - ); + return value.version === actualSignature ? value.affectsGlobalScope || value.impliedFormat ? + // If file version is same as signature, dont serialize signature + { + version: value.version, + signature: void 0, + affectsGlobalScope: value.affectsGlobalScope, + impliedFormat: value.impliedFormat + } : + // If file info only contains version and signature and both are same we can just write string + value.version : actualSignature !== void 0 ? + // If signature is not same as version, encode signature in the fileInfo + oldSignature === void 0 ? + // If we havent computed signature, use fileInfo as is + value : + // Serialize fileInfo with new updated signature + { + version: value.version, + signature: actualSignature, + affectsGlobalScope: value.affectsGlobalScope, + impliedFormat: value.impliedFormat + } : + // Signature of the FileInfo is undefined, serialize it as false + { + version: value.version, + signature: false, + affectsGlobalScope: value.affectsGlobalScope, + impliedFormat: value.impliedFormat + }; }); let referencedMap; if (state.referencedMap) { - referencedMap = arrayFrom(state.referencedMap.keys()).sort(compareStringsCaseSensitive).map((key) => [ - toFileId(key), - toFileIdListId(state.referencedMap.getValues(key)) - ]); + referencedMap = arrayFrom(state.referencedMap.keys()).sort(compareStringsCaseSensitive).map(key => [toFileId(key), toFileIdListId(state.referencedMap.getValues(key))]); } let exportedModulesMap; if (state.exportedModulesMap) { - exportedModulesMap = mapDefined(arrayFrom(state.exportedModulesMap.keys()).sort(compareStringsCaseSensitive), (key) => { + exportedModulesMap = mapDefined(arrayFrom(state.exportedModulesMap.keys()).sort(compareStringsCaseSensitive), key => { var _a2; const oldValue = (_a2 = state.oldExportedModulesMap) == null ? void 0 : _a2.get(key); - if (oldValue === void 0) - return [toFileId(key), toFileIdListId(state.exportedModulesMap.getValues(key))]; - if (oldValue) - return [toFileId(key), toFileIdListId(oldValue)]; + if (oldValue === void 0) return [toFileId(key), toFileIdListId(state.exportedModulesMap.getValues(key))]; + if (oldValue) return [toFileId(key), toFileIdListId(oldValue)]; return void 0; }); } @@ -123577,37 +109682,30 @@ ${lanes.join("\n")} if (state.semanticDiagnosticsPerFile) { for (const key of arrayFrom(state.semanticDiagnosticsPerFile.keys()).sort(compareStringsCaseSensitive)) { const value = state.semanticDiagnosticsPerFile.get(key); - (semanticDiagnosticsPerFile || (semanticDiagnosticsPerFile = [])).push( - value.length ? [ - toFileId(key), - convertToReusableDiagnostics(value, relativeToBuildInfo) - ] : toFileId(key) - ); + (semanticDiagnosticsPerFile || (semanticDiagnosticsPerFile = [])).push(value.length ? [toFileId(key), convertToReusableDiagnostics(value, relativeToBuildInfo)] : toFileId(key)); } } let affectedFilesPendingEmit; if ((_c = state.affectedFilesPendingEmit) == null ? void 0 : _c.size) { const fullEmitForOptions = getBuilderFileEmit(state.compilerOptions); - const seenFiles = /* @__PURE__ */ new Set(); + 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; - const fileId = toFileId(path), pendingEmit = state.affectedFilesPendingEmit.get(path); - (affectedFilesPendingEmit || (affectedFilesPendingEmit = [])).push( - pendingEmit === fullEmitForOptions ? fileId : ( - // Pending full emit per options - pendingEmit === 8 /* Dts */ ? [fileId] : ( - // Pending on Dts only - [fileId, pendingEmit] - ) - ) - // Anything else + if (!file || !sourceFileMayBeEmitted(file, state.program)) continue; + const fileId = toFileId(path), + pendingEmit = state.affectedFilesPendingEmit.get(path); + (affectedFilesPendingEmit || (affectedFilesPendingEmit = [])).push(pendingEmit === fullEmitForOptions ? fileId : + // Pending full emit per options + pendingEmit === 8 /* Dts */ ? [fileId] : + // Pending on Dts only + [fileId, pendingEmit] + // Anything else ); } } } + let changeFileSet; if (state.changedFilesSet.size) { for (const path of arrayFrom(state.changedFilesSet.keys()).sort(compareStringsCaseSensitive)) { @@ -123649,39 +109747,32 @@ ${lanes.join("\n")} 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); + (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 convertToProgramBuildInfoCompilerOptions(options) { let result; - const { optionsNameMap } = getOptionsNameMap(); + const { + optionsNameMap + } = getOptionsNameMap(); for (const name of getOwnKeys(options).sort(compareStringsCaseSensitive)) { const optionInfo = optionsNameMap.get(name.toLowerCase()); if (optionInfo == null ? void 0 : optionInfo.affectsBuildInfo) { - (result || (result = {}))[name] = convertToReusableCompilerOptionValue( - optionInfo, - options[name], - relativeToBuildInfoEnsuringAbsolutePath - ); + (result || (result = {}))[name] = convertToReusableCompilerOptionValue(optionInfo, options[name], relativeToBuildInfoEnsuringAbsolutePath); } } return result; @@ -123703,19 +109794,23 @@ ${lanes.join("\n")} } function convertToReusableDiagnostics(diagnostics, relativeToBuildInfo) { Debug.assert(!!diagnostics.length); - return diagnostics.map((diagnostic) => { + return diagnostics.map(diagnostic => { const result = convertToReusableDiagnosticRelatedInformation(diagnostic, relativeToBuildInfo); 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, relativeToBuildInfo)) : [] : void 0; + const { + relatedInformation + } = diagnostic; + result.relatedInformation = relatedInformation ? relatedInformation.length ? relatedInformation.map(r => convertToReusableDiagnosticRelatedInformation(r, relativeToBuildInfo)) : [] : void 0; return result; }); } function convertToReusableDiagnosticRelatedInformation(diagnostic, relativeToBuildInfo) { - const { file } = diagnostic; + const { + file + } = diagnostic; return { ...diagnostic, file: file ? relativeToBuildInfo(file.resolvedPath) : void 0, @@ -123730,15 +109825,16 @@ ${lanes.join("\n")} }; } const next = convertToReusableDiagnosticMessageChainArray(chain.next); - return next === chain.next ? chain : { ...chain, next }; + 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++) { @@ -123774,38 +109870,44 @@ ${lanes.join("\n")} oldProgram = oldProgramOrHost; configFileParsingDiagnostics = configFileParsingDiagnosticsOrOldProgram; } - return { host, newProgram, oldProgram, configFileParsingDiagnostics: configFileParsingDiagnostics || emptyArray }; + return { + host, + newProgram, + oldProgram, + configFileParsingDiagnostics: configFileParsingDiagnostics || emptyArray + }; } function getTextHandlingSourceMapForSignature(text, data) { return (data == null ? void 0 : data.sourceMapUrlPos) !== void 0 ? text.substring(0, data.sourceMapUrlPos) : text; } function computeSignatureWithDiagnostics(program, sourceFile, text, host, data) { + var _host$createHash; var _a; text = getTextHandlingSourceMapForSignature(text, data); let sourceFileDirectory; if ((_a = data == null ? void 0 : data.diagnostics) == null ? void 0 : _a.length) { - text += data.diagnostics.map((diagnostic) => `${locationInfo(diagnostic)}${DiagnosticCategory[diagnostic.category]}${diagnostic.code}: ${flattenDiagnosticMessageText2(diagnostic.messageText)}`).join("\n"); + text += data.diagnostics.map(diagnostic => `${locationInfo(diagnostic)}${DiagnosticCategory[diagnostic.category]}${diagnostic.code}: ${flattenDiagnosticMessageText2(diagnostic.messageText)}`).join("\n"); } - return (host.createHash ?? generateDjb2Hash)(text); + return ((_host$createHash = host.createHash) !== null && _host$createHash !== void 0 ? _host$createHash : generateDjb2Hash)(text); function flattenDiagnosticMessageText2(diagnostic) { return isString(diagnostic) ? diagnostic : diagnostic === void 0 ? "" : !diagnostic.next ? diagnostic.messageText : diagnostic.messageText + diagnostic.next.map(flattenDiagnosticMessageText2).join("\n"); } function locationInfo(diagnostic) { - 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, - program.getCanonicalFileName - ))}(${diagnostic.start},${diagnostic.length})`; + 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, program.getCanonicalFileName))}(${diagnostic.start},${diagnostic.length})`; } } function computeSignature(text, host, data) { - return (host.createHash ?? generateDjb2Hash)(getTextHandlingSourceMapForSignature(text, data)); + var _host$createHash2; + return ((_host$createHash2 = host.createHash) !== null && _host$createHash2 !== void 0 ? _host$createHash2 : generateDjb2Hash)(getTextHandlingSourceMapForSignature(text, data)); } - function createBuilderProgram(kind, { newProgram, host, oldProgram, configFileParsingDiagnostics }) { + function createBuilderProgram(kind, { + newProgram, + host, + oldProgram, + configFileParsingDiagnostics + }) { let oldState = oldProgram && oldProgram.getState(); if (oldState && newProgram === oldState.program && configFileParsingDiagnostics === newProgram.getConfigFileParsingDiagnostics()) { newProgram = void 0; @@ -123813,7 +109915,7 @@ ${lanes.join("\n")} return oldProgram; } const state = createBuilderProgramState(newProgram, oldState); - newProgram.getBuildInfo = (bundle) => getBuildInfo2(state, bundle); + newProgram.getBuildInfo = bundle => getBuildInfo2(state, bundle); newProgram = void 0; oldProgram = void 0; oldState = void 0; @@ -123821,9 +109923,9 @@ ${lanes.join("\n")} const builderProgram = createRedirectedBuilderProgram(getState, configFileParsingDiagnostics); builderProgram.getState = getState; builderProgram.saveEmitState = () => backupBuilderProgramEmitState(state); - builderProgram.restoreEmitState = (saved) => restoreBuilderProgramEmitState(state, saved); + builderProgram.restoreEmitState = saved => restoreBuilderProgramEmitState(state, saved); builderProgram.hasChangedEmitSignature = () => !!state.hasChangedEmitSignature; - builderProgram.getAllDependencies = (sourceFile) => BuilderState.getAllDependencies(state, Debug.checkDefined(state.program), sourceFile); + builderProgram.getAllDependencies = sourceFile => BuilderState.getAllDependencies(state, Debug.checkDefined(state.program), sourceFile); builderProgram.getSemanticDiagnostics = getSemanticDiagnostics; builderProgram.emit = emit; builderProgram.releaseProgram = () => releaseCache(state); @@ -123854,62 +109956,55 @@ ${lanes.join("\n")} if (!outFile(state.compilerOptions)) { const pendingAffectedFile = getNextAffectedFilePendingEmit(state, emitOnlyDtsFiles); if (!pendingAffectedFile) { - 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; - return { result: result2, affected: affected2 }; + return { + result: result2, + affected: affected2 + }; } - ({ affectedFile: affected, emitKind } = pendingAffectedFile); + ({ + 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; } - const result = state.program.emit( - affected === state.program ? void 0 : affected, - getWriteFileCallback(writeFile2, customTransformers), - cancellationToken, - emitOnly, - customTransformers - ); + const result = state.program.emit(affected === state.program ? void 0 : affected, getWriteFileCallback(writeFile2, customTransformers), cancellationToken, emitOnly, customTransformers); if (affected !== state.program) { + var _state$seenEmittedFil, _state$affectedFilesP; 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); + ((_state$seenEmittedFil = state.seenEmittedFiles) !== null && _state$seenEmittedFil !== void 0 ? _state$seenEmittedFil : 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 (pendingKind) ((_state$affectedFilesP = state.affectedFilesPendingEmit) !== null && _state$affectedFilesP !== void 0 ? _state$affectedFilesP : state.affectedFilesPendingEmit = /* @__PURE__ */new Map()).set(affectedSourceFile.resolvedPath, pendingKind);else (_c = state.affectedFilesPendingEmit) == null ? void 0 : _c.delete(affectedSourceFile.resolvedPath); } else { state.changedFilesSet.clear(); } - return { result, affected }; + 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, _d; if (isDeclarationFileName(fileName)) { @@ -123920,24 +110015,16 @@ ${lanes.join("\n")} const file = sourceFiles[0]; const info = state.fileInfos.get(file.resolvedPath); if (info.signature === file.version) { - const signature = computeSignatureWithDiagnostics( - state.program, - file, - text, - host, - data - ); - if (!((_a = data == null ? void 0 : data.diagnostics) == null ? void 0 : _a.length)) - emitSignature = signature; + const signature = computeSignatureWithDiagnostics(state.program, file, text, host, data); + if (!((_a = data == null ? void 0 : data.diagnostics) == null ? void 0 : _a.length)) emitSignature = signature; if (signature !== file.version) { - if (host.storeFilesChangingSignatureDuringEmit) - (state.filesChangingSignature ?? (state.filesChangingSignature = /* @__PURE__ */ new Set())).add(file.resolvedPath); - if (state.exportedModulesMap) - BuilderState.updateExportedModules(state, file, file.exportedModulesFromDeclarationEmit); + var _state$filesChangingS; + if (host.storeFilesChangingSignatureDuringEmit) ((_state$filesChangingS = state.filesChangingSignature) !== null && _state$filesChangingS !== void 0 ? _state$filesChangingS : state.filesChangingSignature = /* @__PURE__ */new Set()).add(file.resolvedPath); + if (state.exportedModulesMap) BuilderState.updateExportedModules(state, file, file.exportedModulesFromDeclarationEmit); if (state.affectedFiles) { + var _state$oldSignatures; 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) !== null && _state$oldSignatures !== void 0 ? _state$oldSignatures : state.oldSignatures = /* @__PURE__ */new Map()).set(file.resolvedPath, info.signature || false); info.signature = signature; } else { info.signature = signature; @@ -123947,39 +110034,28 @@ ${lanes.join("\n")} } } if (state.compilerOptions.composite) { + var _state$emitSignatures2; const filePath = sourceFiles[0].resolvedPath; emitSignature = handleNewSignature((_d = state.emitSignatures) == null ? void 0 : _d.get(filePath), emitSignature); - if (!emitSignature) - return; - (state.emitSignatures ?? (state.emitSignatures = /* @__PURE__ */ new Map())).set(filePath, emitSignature); + if (!emitSignature) return; + ((_state$emitSignatures2 = state.emitSignatures) !== null && _state$emitSignatures2 !== void 0 ? _state$emitSignatures2 : state.emitSignatures = /* @__PURE__ */new Map()).set(filePath, emitSignature); } } else if (state.compilerOptions.composite) { - const newSignature = handleNewSignature( - state.outSignature, - /*newSignature*/ - void 0 - ); - if (!newSignature) - return; + const newSignature = handleNewSignature(state.outSignature, /*newSignature*/ + void 0); + 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) { + var _newSignature; const oldSignature = !oldSignatureFormat || isString(oldSignatureFormat) ? oldSignatureFormat : oldSignatureFormat[0]; - newSignature ?? (newSignature = computeSignature(text, host, data)); + (_newSignature = newSignature) !== null && _newSignature !== void 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; @@ -123993,8 +110069,7 @@ ${lanes.join("\n")} 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 = []; @@ -124018,21 +110093,13 @@ ${lanes.join("\n")} clearAffectedFilesPendingEmit(state, emitOnlyDtsFiles); } } - return Debug.checkDefined(state.program).emit( - targetSourceFile, - getWriteFileCallback(writeFile2, customTransformers), - cancellationToken, - emitOnlyDtsFiles, - customTransformers - ); + return Debug.checkDefined(state.program).emit(targetSourceFile, getWriteFileCallback(writeFile2, customTransformers), cancellationToken, emitOnlyDtsFiles, customTransformers); } function getSemanticDiagnosticsOfNextAffectedFile(cancellationToken, ignoreSourceFile) { while (true) { const affected = getNextAffectedFile(state, cancellationToken, host); let result; - if (!affected) - return void 0; - else if (affected !== state.program) { + if (!affected) return void 0;else if (affected !== state.program) { const affectedSourceFile = affected; if (!ignoreSourceFile || !ignoreSourceFile(affectedSourceFile)) { result = getSemanticDiagnosticsOfFile(state, affectedSourceFile, cancellationToken); @@ -124040,18 +110107,17 @@ ${lanes.join("\n")} state.seenAffectedFiles.add(affectedSourceFile.resolvedPath); state.affectedFilesIndex++; state.buildInfoEmitPending = true; - if (!result) - continue; + if (!result) continue; } else { - result = state.program.getSemanticDiagnostics( - /*sourceFile*/ - void 0, - cancellationToken - ); + result = state.program.getSemanticDiagnostics( /*sourceFile*/ + void 0, cancellationToken); state.changedFilesSet.clear(); state.programEmitPending = getBuilderFileEmit(state.compilerOptions); } - return { result, affected }; + return { + result, + affected + }; } } function getSemanticDiagnostics(sourceFile, cancellationToken) { @@ -124064,8 +110130,7 @@ ${lanes.join("\n")} if (sourceFile) { return getSemanticDiagnosticsOfFile(state, sourceFile, cancellationToken); } - while (getSemanticDiagnosticsOfNextAffectedFile(cancellationToken)) { - } + while (getSemanticDiagnosticsOfNextAffectedFile(cancellationToken)) {} let diagnostics; for (const sourceFile2 of Debug.checkDefined(state.program).getSourceFiles()) { diagnostics = addRange(diagnostics, getSemanticDiagnosticsOfFile(state, sourceFile2, cancellationToken)); @@ -124074,16 +110139,28 @@ ${lanes.join("\n")} } } function addToAffectedFilesPendingEmit(state, affectedFilePendingEmit, kind) { + var _state$affectedFilesP2; var _a; const existingKind = ((_a = state.affectedFilesPendingEmit) == null ? void 0 : _a.get(affectedFilePendingEmit)) || 0 /* None */; - (state.affectedFilesPendingEmit ?? (state.affectedFilesPendingEmit = /* @__PURE__ */ new Map())).set(affectedFilePendingEmit, existingKind | kind); + ((_state$affectedFilesP2 = state.affectedFilesPendingEmit) !== null && _state$affectedFilesP2 !== void 0 ? _state$affectedFilesP2 : state.affectedFilesPendingEmit = /* @__PURE__ */new Map()).set(affectedFilePendingEmit, existingKind | kind); } function toBuilderStateFileInfoForMultiEmit(fileInfo) { - return isString(fileInfo) ? { version: fileInfo, signature: fileInfo, affectsGlobalScope: void 0, impliedFormat: void 0 } : isString(fileInfo.signature) ? fileInfo : { version: fileInfo.version, signature: fileInfo.signature === false ? void 0 : fileInfo.version, affectsGlobalScope: fileInfo.affectsGlobalScope, impliedFormat: fileInfo.impliedFormat }; + return isString(fileInfo) ? { + version: fileInfo, + signature: fileInfo, + affectsGlobalScope: void 0, + impliedFormat: void 0 + } : isString(fileInfo.signature) ? fileInfo : { + version: fileInfo.version, + signature: fileInfo.signature === false ? void 0 : fileInfo.version, + affectsGlobalScope: fileInfo.affectsGlobalScope, + impliedFormat: fileInfo.impliedFormat + }; } function toBuilderFileEmit(value, fullEmitForOptions) { return isNumber(value) ? fullEmitForOptions : value[1] || 8 /* Dts */; } + function toProgramEmitPending(value, options) { return !value ? getBuilderFileEmit(options || {}) : value; } @@ -124097,10 +110174,15 @@ ${lanes.join("\n")} let filePathsSetList; const latestChangedDtsFile = program.latestChangedDtsFile ? toAbsolutePath(program.latestChangedDtsFile) : void 0; if (isProgramBundleEmitBuildInfo(program)) { - const fileInfos = /* @__PURE__ */ new Map(); + const fileInfos = /* @__PURE__ */new Map(); program.fileInfos.forEach((fileInfo, index) => { const path = toFilePath(index + 1); - fileInfos.set(path, isString(fileInfo) ? { version: fileInfo, signature: void 0, affectsGlobalScope: void 0, impliedFormat: void 0 } : fileInfo); + fileInfos.set(path, isString(fileInfo) ? { + version: fileInfo, + signature: void 0, + affectsGlobalScope: void 0, + impliedFormat: void 0 + } : fileInfo); }); state = { fileInfos, @@ -124111,28 +110193,21 @@ ${lanes.join("\n")} bundle: buildInfo.bundle }; } else { - filePathsSetList = (_b = program.fileIdsList) == null ? void 0 : _b.map((fileIds) => new Set(fileIds.map(toFilePath))); - const fileInfos = /* @__PURE__ */ new Map(); - const emitSignatures = ((_c = program.options) == null ? void 0 : _c.composite) && !outFile(program.options) ? /* @__PURE__ */ new Map() : void 0; + filePathsSetList = (_b = program.fileIdsList) == null ? void 0 : _b.map(fileIds => new Set(fileIds.map(toFilePath))); + const fileInfos = /* @__PURE__ */new Map(); + const emitSignatures = ((_c = program.options) == null ? void 0 : _c.composite) && !outFile(program.options) ? /* @__PURE__ */new Map() : void 0; program.fileInfos.forEach((fileInfo, index) => { 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)); - else { + (_d = program.emitSignatures) == null ? void 0 : _d.forEach(value => { + if (isNumber(value)) emitSignatures.delete(toFilePath(value));else { const key = toFilePath(value[0]); - emitSignatures.set( - key, - !isString(value[1]) && !value[1].length ? ( - // File signature is emit signature but differs in map - [emitSignatures.get(key)] - ) : value[1] - ); + emitSignatures.set(key, !isString(value[1]) && !value[1].length ? + // File signature is emit signature but differs in map + [emitSignatures.get(key)] : value[1]); } }); const fullEmitForOptions = program.affectedFilesPendingEmit ? getBuilderFileEmit(program.options || {}) : void 0; @@ -124141,9 +110216,9 @@ ${lanes.join("\n")} compilerOptions: program.options ? convertToOptionsWithAbsolutePaths(program.options, toAbsolutePath) : {}, referencedMap: toManyToManyPathMap(program.referencedMap), exportedModulesMap: toManyToManyPathMap(program.exportedModulesMap), - semanticDiagnosticsPerFile: program.semanticDiagnosticsPerFile && arrayToMap(program.semanticDiagnosticsPerFile, (value) => toFilePath(isNumber(value) ? value : value[0]), (value) => isNumber(value) ? emptyArray : value[1]), + semanticDiagnosticsPerFile: program.semanticDiagnosticsPerFile && arrayToMap(program.semanticDiagnosticsPerFile, value => toFilePath(isNumber(value) ? value : value[0]), value => isNumber(value) ? emptyArray : value[1]), hasReusableDiagnostic: true, - affectedFilesPendingEmit: program.affectedFilesPendingEmit && arrayToMap(program.affectedFilesPendingEmit, (value) => toFilePath(isNumber(value) ? value : value[0]), (value) => toBuilderFileEmit(value, fullEmitForOptions)), + affectedFilesPendingEmit: program.affectedFilesPendingEmit && arrayToMap(program.affectedFilesPendingEmit, value => toFilePath(isNumber(value) ? value : value[0]), value => toBuilderFileEmit(value, fullEmitForOptions)), changedFilesSet: new Set(map(program.changeFileSet, toFilePath)), latestChangedDtsFile, emitSignatures: (emitSignatures == null ? void 0 : emitSignatures.size) ? emitSignatures : void 0 @@ -124198,7 +110273,7 @@ ${lanes.join("\n")} function getBuildInfoFileVersionMap(program, buildInfoPath, host) { const buildInfoDirectory = getDirectoryPath(getNormalizedAbsolutePath(buildInfoPath, host.getCurrentDirectory())); const getCanonicalFileName = createGetCanonicalFileName(host.useCaseSensitiveFileNames()); - const fileInfos = /* @__PURE__ */ new Map(); + const fileInfos = /* @__PURE__ */new Map(); let rootIndex = 0; const roots = []; program.fileInfos.forEach((fileInfo, index) => { @@ -124211,8 +110286,7 @@ ${lanes.join("\n")} if (isArray(current)) { if (current[0] <= fileId && fileId <= current[1]) { roots.push(path); - if (current[1] === fileId) - rootIndex++; + if (current[1] === fileId) rootIndex++; } } else if (current === fileId) { roots.push(path); @@ -124220,7 +110294,10 @@ ${lanes.join("\n")} } } }); - return { fileInfos, roots }; + return { + fileInfos, + roots + }; } function createRedirectedBuilderProgram(getState, configFileParsingDiagnostics) { return { @@ -124231,10 +110308,10 @@ ${lanes.join("\n")} getProgramOrUndefined: () => getState().program, releaseProgram: () => getState().program = void 0, getCompilerOptions: () => getState().compilerOptions, - getSourceFile: (fileName) => getProgram().getSourceFile(fileName), + getSourceFile: fileName => getProgram().getSourceFile(fileName), getSourceFiles: () => getProgram().getSourceFiles(), - getOptionsDiagnostics: (cancellationToken) => getProgram().getOptionsDiagnostics(cancellationToken), - getGlobalDiagnostics: (cancellationToken) => getProgram().getGlobalDiagnostics(cancellationToken), + getOptionsDiagnostics: cancellationToken => getProgram().getOptionsDiagnostics(cancellationToken), + getGlobalDiagnostics: cancellationToken => getProgram().getGlobalDiagnostics(cancellationToken), getConfigFileParsingDiagnostics: () => configFileParsingDiagnostics, getSyntacticDiagnostics: (sourceFile, cancellationToken) => getProgram().getSyntacticDiagnostics(sourceFile, cancellationToken), getDeclarationDiagnostics: (sourceFile, cancellationToken) => getProgram().getDeclarationDiagnostics(sourceFile, cancellationToken), @@ -124253,8 +110330,9 @@ ${lanes.join("\n")} var init_builder = __esm({ "src/compiler/builder.ts"() { "use strict"; + init_ts2(); - BuilderFileEmit = /* @__PURE__ */ ((BuilderFileEmit2) => { + BuilderFileEmit = /* @__PURE__ */(BuilderFileEmit2 => { BuilderFileEmit2[BuilderFileEmit2["None"] = 0] = "None"; BuilderFileEmit2[BuilderFileEmit2["Js"] = 1] = "Js"; BuilderFileEmit2[BuilderFileEmit2["JsMap"] = 2] = "JsMap"; @@ -124266,7 +110344,7 @@ ${lanes.join("\n")} BuilderFileEmit2[BuilderFileEmit2["All"] = 31] = "All"; return BuilderFileEmit2; })(BuilderFileEmit || {}); - BuilderProgramKind = /* @__PURE__ */ ((BuilderProgramKind2) => { + BuilderProgramKind = /* @__PURE__ */(BuilderProgramKind2 => { BuilderProgramKind2[BuilderProgramKind2["SemanticDiagnosticsBuilderProgram"] = 0] = "SemanticDiagnosticsBuilderProgram"; BuilderProgramKind2[BuilderProgramKind2["EmitAndSemanticDiagnosticsBuilderProgram"] = 1] = "EmitAndSemanticDiagnosticsBuilderProgram"; return BuilderProgramKind2; @@ -124282,12 +110360,19 @@ ${lanes.join("\n")} return createBuilderProgram(1 /* EmitAndSemanticDiagnosticsBuilderProgram */, getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences)); } function createAbstractBuilder(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { - const { newProgram, configFileParsingDiagnostics: newConfigFileParsingDiagnostics } = getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences); - return createRedirectedBuilderProgram(() => ({ program: newProgram, compilerOptions: newProgram.getCompilerOptions() }), newConfigFileParsingDiagnostics); + const { + newProgram, + configFileParsingDiagnostics: newConfigFileParsingDiagnostics + } = getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences); + return createRedirectedBuilderProgram(() => ({ + program: newProgram, + compilerOptions: newProgram.getCompilerOptions() + }), newConfigFileParsingDiagnostics); } var init_builderPublic = __esm({ "src/compiler/builderPublic.ts"() { "use strict"; + init_ts2(); } }); @@ -124297,17 +110382,16 @@ ${lanes.join("\n")} if (endsWith(path, "/node_modules/.staging")) { return removeSuffix(path, "/.staging"); } - return some(ignoredPaths, (searchPath) => path.includes(searchPath)) ? void 0 : 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 + 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; } @@ -124320,10 +110404,8 @@ ${lanes.join("\n")} 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; } @@ -124331,11 +110413,9 @@ ${lanes.join("\n")} 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; } @@ -124350,11 +110430,9 @@ ${lanes.join("\n")} 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; if (isInDirectoryPath(rootPathComponents, failedLookupPathComponents)) { if (failedLookupPathComponents.length > rootPathComponents.length + 1) { return getDirectoryOfFailedLookupWatch(failedLookupComponents, failedLookupPathComponents, Math.max(rootPathComponents.length + 1, perceivedOsRootLength + 1)); @@ -124366,14 +110444,7 @@ ${lanes.join("\n")} }; } } - return getDirectoryToWatchFromFailedLookupLocationDirectory( - failedLookupComponents, - failedLookupPathComponents, - failedLookupPathComponents.length - 1, - perceivedOsRootLength, - nodeModulesIndex, - rootPathComponents - ); + return getDirectoryToWatchFromFailedLookupLocationDirectory(failedLookupComponents, failedLookupPathComponents, failedLookupPathComponents.length - 1, perceivedOsRootLength, nodeModulesIndex, rootPathComponents); } function getDirectoryToWatchFromFailedLookupLocationDirectory(dirComponents, dirPathComponents, dirPathComponentsLength, perceivedOsRootLength, nodeModulesIndex, rootPathComponents) { if (nodeModulesIndex !== -1) { @@ -124403,14 +110474,7 @@ ${lanes.join("\n")} return rootPath; } typeRoot = isRootedDiskPath(typeRoot) ? normalizePath(typeRoot) : getNormalizedAbsolutePath(typeRoot, getCurrentDirectory()); - const toWatch = getDirectoryToWatchFromFailedLookupLocationDirectory( - getPathComponents(typeRoot), - typeRootPathComponents, - typeRootPathComponents.length, - perceivedOsRootLengthForWatching(typeRootPathComponents, typeRootPathComponents.length), - typeRootPathComponents.indexOf("node_modules"), - rootPathComponents - ); + const toWatch = getDirectoryToWatchFromFailedLookupLocationDirectory(getPathComponents(typeRoot), typeRootPathComponents, typeRootPathComponents.length, perceivedOsRootLengthForWatching(typeRootPathComponents, typeRootPathComponents.length), typeRootPathComponents.indexOf("node_modules"), rootPathComponents); return toWatch && filterCustomPath(toWatch.dirPath) ? toWatch.dirPath : void 0; } function getRootDirectoryOfResolutionCache(rootDirForResolution, getCurrentDirectory) { @@ -124427,15 +110491,7 @@ ${lanes.join("\n")} function createModuleResolutionLoaderUsingGlobalCache(containingFile, redirectedReference, options, resolutionHost, moduleResolutionCache) { return { nameAndMode: moduleResolutionNameAndModeGetter, - resolve: (moduleName, resoluionMode) => resolveModuleNameUsingGlobalCache( - resolutionHost, - moduleResolutionCache, - moduleName, - containingFile, - options, - redirectedReference, - resoluionMode - ) + resolve: (moduleName, resoluionMode) => resolveModuleNameUsingGlobalCache(resolutionHost, moduleResolutionCache, moduleName, containingFile, options, redirectedReference, resoluionMode) }; } function resolveModuleNameUsingGlobalCache(resolutionHost, moduleResolutionCache, moduleName, containingFile, compilerOptions, redirectedReference, mode) { @@ -124446,14 +110502,12 @@ ${lanes.join("\n")} } const globalCache = resolutionHost.getGlobalCache(); if (globalCache !== void 0 && !isExternalModuleNameRelative(moduleName) && !(primaryResult.resolvedModule && extensionIsTS(primaryResult.resolvedModule.extension))) { - const { resolvedModule, failedLookupLocations, affectingLocations, resolutionDiagnostics } = loadModuleFromGlobalCache( - Debug.checkDefined(resolutionHost.globalCacheResolutionModuleName)(moduleName), - resolutionHost.projectName, - compilerOptions, - host, - globalCache, - moduleResolutionCache - ); + const { + resolvedModule, + failedLookupLocations, + affectingLocations, + resolutionDiagnostics + } = loadModuleFromGlobalCache(Debug.checkDefined(resolutionHost.globalCacheResolutionModuleName)(moduleName), resolutionHost.projectName, compilerOptions, host, globalCache, moduleResolutionCache); if (resolvedModule) { primaryResult.resolvedModule = resolvedModule; primaryResult.failedLookupLocations = updateResolutionField(primaryResult.failedLookupLocations, failedLookupLocations); @@ -124469,10 +110523,10 @@ ${lanes.join("\n")} let filesWithInvalidatedResolutions; let filesWithInvalidatedNonRelativeUnresolvedImports; const nonRelativeExternalModuleResolutions = createMultiMap(); - const resolutionsWithFailedLookups = /* @__PURE__ */ new Set(); - const resolutionsWithOnlyAffectingLocations = /* @__PURE__ */ new Set(); - const resolvedFileToResolution = /* @__PURE__ */ new Map(); - const impliedFormatPackageJsons = /* @__PURE__ */ new Map(); + const resolutionsWithFailedLookups = /* @__PURE__ */new Set(); + const resolutionsWithOnlyAffectingLocations = /* @__PURE__ */new Set(); + const resolvedFileToResolution = /* @__PURE__ */new Map(); + const impliedFormatPackageJsons = /* @__PURE__ */new Map(); let hasChangedAutomaticTypeDirectiveNames = false; let affectingPathChecksForFile; let affectingPathChecks; @@ -124482,33 +110536,18 @@ ${lanes.join("\n")} let allModuleAndTypeResolutionsAreInvalidated = false; const getCurrentDirectory = memoize(() => resolutionHost.getCurrentDirectory()); const cachedDirectoryStructureHost = resolutionHost.getCachedDirectoryStructureHost(); - const resolvedModuleNames = /* @__PURE__ */ new Map(); - const moduleResolutionCache = createModuleResolutionCache( - getCurrentDirectory(), - resolutionHost.getCanonicalFileName, - resolutionHost.getCompilationSettings() - ); - const resolvedTypeReferenceDirectives = /* @__PURE__ */ new Map(); - const typeReferenceDirectiveResolutionCache = createTypeReferenceDirectiveResolutionCache( - getCurrentDirectory(), - resolutionHost.getCanonicalFileName, - resolutionHost.getCompilationSettings(), - moduleResolutionCache.getPackageJsonInfoCache(), - moduleResolutionCache.optionsToRedirectsKey - ); - const resolvedLibraries = /* @__PURE__ */ new Map(); - const libraryResolutionCache = createModuleResolutionCache( - getCurrentDirectory(), - resolutionHost.getCanonicalFileName, - getOptionsForLibraryResolution(resolutionHost.getCompilationSettings()), - moduleResolutionCache.getPackageJsonInfoCache() - ); - const directoryWatchesOfFailedLookups = /* @__PURE__ */ new Map(); - const fileWatchesOfAffectingLocations = /* @__PURE__ */ new Map(); + const resolvedModuleNames = /* @__PURE__ */new Map(); + const moduleResolutionCache = createModuleResolutionCache(getCurrentDirectory(), resolutionHost.getCanonicalFileName, resolutionHost.getCompilationSettings()); + const resolvedTypeReferenceDirectives = /* @__PURE__ */new Map(); + const typeReferenceDirectiveResolutionCache = createTypeReferenceDirectiveResolutionCache(getCurrentDirectory(), resolutionHost.getCanonicalFileName, resolutionHost.getCompilationSettings(), moduleResolutionCache.getPackageJsonInfoCache(), moduleResolutionCache.optionsToRedirectsKey); + const resolvedLibraries = /* @__PURE__ */new Map(); + const libraryResolutionCache = createModuleResolutionCache(getCurrentDirectory(), resolutionHost.getCanonicalFileName, getOptionsForLibraryResolution(resolutionHost.getCompilationSettings()), moduleResolutionCache.getPackageJsonInfoCache()); + const directoryWatchesOfFailedLookups = /* @__PURE__ */new Map(); + const fileWatchesOfAffectingLocations = /* @__PURE__ */new Map(); const rootDir = getRootDirectoryOfResolutionCache(rootDirForResolution, getCurrentDirectory); const rootPath = resolutionHost.toPath(rootDir); const rootPathComponents = getPathComponents(rootPath); - const typeRootsWatches = /* @__PURE__ */ new Map(); + const typeRootsWatches = /* @__PURE__ */new Map(); return { rootDirForResolution, resolvedModuleNames, @@ -124602,8 +110641,8 @@ ${lanes.join("\n")} const collected = filesWithInvalidatedResolutions; filesWithInvalidatedResolutions = void 0; return { - hasInvalidatedResolutions: (path) => customHasInvalidatedResolutions(path) || allModuleAndTypeResolutionsAreInvalidated || !!(collected == null ? void 0 : collected.has(path)) || isFileWithInvalidatedNonRelativeUnresolvedImports(path), - hasInvalidatedLibResolutions: (libFileName) => { + hasInvalidatedResolutions: path => customHasInvalidatedResolutions(path) || allModuleAndTypeResolutionsAreInvalidated || !!(collected == null ? void 0 : collected.has(path)) || isFileWithInvalidatedNonRelativeUnresolvedImports(path), + hasInvalidatedLibResolutions: libFileName => { var _a; return customHasInvalidatedLibResolutions(libFileName) || !!((_a = resolvedLibraries == null ? void 0 : resolvedLibraries.get(libFileName)) == null ? void 0 : _a.isInvalidated); } @@ -124624,11 +110663,7 @@ ${lanes.join("\n")} resolvedLibraries.forEach((resolution, libFileName) => { var _a; if (!((_a = newProgram == null ? void 0 : newProgram.resolvedLibReferences) == null ? void 0 : _a.has(libFileName))) { - stopWatchFailedLookupLocationOfResolution( - resolution, - resolutionHost.toPath(getInferredLibraryNameResolveFrom(resolutionHost.getCompilationSettings(), getCurrentDirectory(), libFileName)), - getResolvedModule - ); + stopWatchFailedLookupLocationOfResolution(resolution, resolutionHost.toPath(getInferredLibraryNameResolveFrom(resolutionHost.getCompilationSettings(), getCurrentDirectory(), libFileName)), getResolvedModule); resolvedLibraries.delete(libFileName); } }); @@ -124640,30 +110675,25 @@ ${lanes.join("\n")} nonRelativeExternalModuleResolutions.clear(); if (newProgram !== oldProgram) { cleanupLibResolutionWatching(newProgram); - newProgram == null ? void 0 : newProgram.getSourceFiles().forEach((newFile) => { + newProgram == null ? void 0 : newProgram.getSourceFiles().forEach(newFile => { + var _ref41, _impliedFormatPackage; var _a; - const expected = isExternalOrCommonJsModule(newFile) ? ((_a = newFile.packageJsonLocations) == null ? void 0 : _a.length) ?? 0 : 0; - const existing = impliedFormatPackageJsons.get(newFile.path) ?? emptyArray; + const expected = isExternalOrCommonJsModule(newFile) ? (_ref41 = (_a = newFile.packageJsonLocations) == null ? void 0 : _a.length) !== null && _ref41 !== void 0 ? _ref41 : 0 : 0; + const existing = (_impliedFormatPackage = impliedFormatPackageJsons.get(newFile.path)) !== null && _impliedFormatPackage !== void 0 ? _impliedFormatPackage : emptyArray; for (let i = existing.length; i < expected; i++) { - createFileWatcherOfAffectingLocation( - newFile.packageJsonLocations[i], - /*forResolution*/ - false - ); + createFileWatcherOfAffectingLocation(newFile.packageJsonLocations[i], /*forResolution*/ + false); } if (existing.length > expected) { for (let i = expected; i < existing.length; i++) { fileWatchesOfAffectingLocations.get(existing[i]).files--; } } - if (expected) - impliedFormatPackageJsons.set(newFile.path, newFile.packageJsonLocations); - else - impliedFormatPackageJsons.delete(newFile.path); + if (expected) impliedFormatPackageJsons.set(newFile.path, newFile.packageJsonLocations);else impliedFormatPackageJsons.delete(newFile.path); }); impliedFormatPackageJsons.forEach((existing, path) => { if (!(newProgram == null ? void 0 : newProgram.getSourceFileByPath(path))) { - existing.forEach((location) => fileWatchesOfAffectingLocations.get(location).files--); + existing.forEach(location => fileWatchesOfAffectingLocations.get(location).files--); impliedFormatPackageJsons.delete(path); } }); @@ -124715,7 +110745,8 @@ ${lanes.join("\n")} const name = loader.nameAndMode.getName(entry); const mode = loader.nameAndMode.getMode(entry, containingSourceFile); let resolution = resolutionsInFile.get(name, mode); - if (!seenNamesInFile.has(name, mode) && (allModuleAndTypeResolutionsAreInvalidated || unmatchedRedirects || !resolution || resolution.isInvalidated || // If the name is unresolved import that was invalidated, recalculate + if (!seenNamesInFile.has(name, mode) && (allModuleAndTypeResolutionsAreInvalidated || unmatchedRedirects || !resolution || resolution.isInvalidated || + // If the name is unresolved import that was invalidated, recalculate hasInvalidatedNonRelativeUnresolvedImport && !isExternalModuleNameRelative(name) && shouldRetryResolution(resolution))) { const existingResolution = resolution; resolution = loader.resolve(name, mode); @@ -124737,27 +110768,14 @@ ${lanes.join("\n")} const host = getModuleResolutionHost(resolutionHost); if (isTraceEnabled(options, host) && !seenNamesInFile.has(name, mode)) { const resolved = getResolutionWithResolvedFileName(resolution); - trace( - host, - perFileCache === resolvedModuleNames ? (resolved == null ? void 0 : resolved.resolvedFileName) ? resolved.packageId ? Diagnostics.Reusing_resolution_of_module_0_from_1_of_old_program_it_was_successfully_resolved_to_2_with_Package_ID_3 : Diagnostics.Reusing_resolution_of_module_0_from_1_of_old_program_it_was_successfully_resolved_to_2 : Diagnostics.Reusing_resolution_of_module_0_from_1_of_old_program_it_was_not_resolved : (resolved == null ? void 0 : resolved.resolvedFileName) ? resolved.packageId ? Diagnostics.Reusing_resolution_of_type_reference_directive_0_from_1_of_old_program_it_was_successfully_resolved_to_2_with_Package_ID_3 : Diagnostics.Reusing_resolution_of_type_reference_directive_0_from_1_of_old_program_it_was_successfully_resolved_to_2 : Diagnostics.Reusing_resolution_of_type_reference_directive_0_from_1_of_old_program_it_was_not_resolved, - name, - containingFile, - resolved == null ? void 0 : resolved.resolvedFileName, - (resolved == null ? void 0 : resolved.packageId) && packageIdToString(resolved.packageId) - ); + trace(host, perFileCache === resolvedModuleNames ? (resolved == null ? void 0 : resolved.resolvedFileName) ? resolved.packageId ? Diagnostics.Reusing_resolution_of_module_0_from_1_of_old_program_it_was_successfully_resolved_to_2_with_Package_ID_3 : Diagnostics.Reusing_resolution_of_module_0_from_1_of_old_program_it_was_successfully_resolved_to_2 : Diagnostics.Reusing_resolution_of_module_0_from_1_of_old_program_it_was_not_resolved : (resolved == null ? void 0 : resolved.resolvedFileName) ? resolved.packageId ? Diagnostics.Reusing_resolution_of_type_reference_directive_0_from_1_of_old_program_it_was_successfully_resolved_to_2_with_Package_ID_3 : Diagnostics.Reusing_resolution_of_type_reference_directive_0_from_1_of_old_program_it_was_successfully_resolved_to_2 : Diagnostics.Reusing_resolution_of_type_reference_directive_0_from_1_of_old_program_it_was_not_resolved, name, containingFile, resolved == null ? void 0 : resolved.resolvedFileName, (resolved == null ? void 0 : resolved.packageId) && packageIdToString(resolved.packageId)); } } Debug.assert(resolution !== void 0 && !resolution.isInvalidated); seenNamesInFile.set(name, mode, true); resolvedModules.push(resolution); } - reusedNames == null ? void 0 : reusedNames.forEach( - (entry) => seenNamesInFile.set( - loader.nameAndMode.getName(entry), - loader.nameAndMode.getMode(entry, containingSourceFile), - true - ) - ); + reusedNames == null ? void 0 : reusedNames.forEach(entry => seenNamesInFile.set(loader.nameAndMode.getName(entry), loader.nameAndMode.getMode(entry, containingSourceFile), true)); if (resolutionsInFile.size() !== seenNamesInFile.size()) { resolutionsInFile.forEach((resolution, name, mode) => { if (!seenNamesInFile.has(name, mode)) { @@ -124794,15 +110812,9 @@ ${lanes.join("\n")} options, reusedNames, perFileCache: resolvedTypeReferenceDirectives, - loader: createTypeReferenceResolutionLoader( - containingFile, - redirectedReference, - options, - getModuleResolutionHost(resolutionHost), - typeReferenceDirectiveResolutionCache - ), + loader: createTypeReferenceResolutionLoader(containingFile, redirectedReference, options, getModuleResolutionHost(resolutionHost), typeReferenceDirectiveResolutionCache), getResolutionWithResolvedFileName: getResolvedTypeReferenceDirective, - shouldRetryResolution: (resolution) => resolution.resolvedTypeReferenceDirective === void 0, + shouldRetryResolution: resolution => resolution.resolvedTypeReferenceDirective === void 0, deferWatchingNonRelativeResolution: false }); } @@ -124815,20 +110827,15 @@ ${lanes.join("\n")} options, reusedNames, perFileCache: resolvedModuleNames, - loader: createModuleResolutionLoaderUsingGlobalCache( - containingFile, - redirectedReference, - options, - resolutionHost, - moduleResolutionCache - ), + loader: createModuleResolutionLoaderUsingGlobalCache(containingFile, redirectedReference, options, resolutionHost, moduleResolutionCache), getResolutionWithResolvedFileName: getResolvedModule, - shouldRetryResolution: (resolution) => !resolution.resolvedModule || !resolutionExtensionIsTSOrJson(resolution.resolvedModule.extension), + shouldRetryResolution: resolution => !resolution.resolvedModule || !resolutionExtensionIsTSOrJson(resolution.resolvedModule.extension), logChanges: logChangesWhenResolvingModule, deferWatchingNonRelativeResolution: true // Defer non relative resolution watch because we could be using ambient modules }); } + function resolveLibrary2(libraryName, resolveFrom, options, libFileName) { const host = getModuleResolutionHost(resolutionHost); let resolution = resolvedLibraries == null ? void 0 : resolvedLibraries.get(libFileName); @@ -124836,14 +110843,8 @@ ${lanes.join("\n")} const existingResolution = resolution; resolution = resolveLibrary(libraryName, resolveFrom, options, host, libraryResolutionCache); const path = resolutionHost.toPath(resolveFrom); - watchFailedLookupLocationsOfExternalModuleResolutions( - libraryName, - resolution, - path, - getResolvedModule, - /*deferWatchingNonRelativeResolution*/ - false - ); + watchFailedLookupLocationsOfExternalModuleResolutions(libraryName, resolution, path, getResolvedModule, /*deferWatchingNonRelativeResolution*/ + false); resolvedLibraries.set(libFileName, resolution); if (existingResolution) { stopWatchFailedLookupLocationOfResolution(existingResolution, path, getResolvedModule); @@ -124851,14 +110852,7 @@ ${lanes.join("\n")} } else { if (isTraceEnabled(options, host)) { const resolved = getResolvedModule(resolution); - trace( - host, - (resolved == null ? void 0 : resolved.resolvedFileName) ? resolved.packageId ? Diagnostics.Reusing_resolution_of_module_0_from_1_of_old_program_it_was_successfully_resolved_to_2_with_Package_ID_3 : Diagnostics.Reusing_resolution_of_module_0_from_1_of_old_program_it_was_successfully_resolved_to_2 : Diagnostics.Reusing_resolution_of_module_0_from_1_of_old_program_it_was_not_resolved, - libraryName, - resolveFrom, - resolved == null ? void 0 : resolved.resolvedFileName, - (resolved == null ? void 0 : resolved.packageId) && packageIdToString(resolved.packageId) - ); + trace(host, (resolved == null ? void 0 : resolved.resolvedFileName) ? resolved.packageId ? Diagnostics.Reusing_resolution_of_module_0_from_1_of_old_program_it_was_successfully_resolved_to_2_with_Package_ID_3 : Diagnostics.Reusing_resolution_of_module_0_from_1_of_old_program_it_was_successfully_resolved_to_2 : Diagnostics.Reusing_resolution_of_module_0_from_1_of_old_program_it_was_not_resolved, libraryName, resolveFrom, resolved == null ? void 0 : resolved.resolvedFileName, (resolved == null ? void 0 : resolved.packageId) && packageIdToString(resolved.packageId)); } } return resolution; @@ -124867,22 +110861,12 @@ ${lanes.join("\n")} var _a, _b; const path = resolutionHost.toPath(containingFile); const resolutionsInFile = resolvedModuleNames.get(path); - const resolution = resolutionsInFile == null ? void 0 : resolutionsInFile.get( - moduleName, - /*mode*/ - void 0 - ); - if (resolution && !resolution.isInvalidated) - return resolution; + const resolution = resolutionsInFile == null ? void 0 : resolutionsInFile.get(moduleName, /*mode*/ + void 0); + 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( - moduleName, - containingFile, - resolutionHost.getCompilationSettings(), - host, - moduleResolutionCache - ); + const result = resolveModuleName(moduleName, containingFile, resolutionHost.getCompilationSettings(), host, moduleResolutionCache); (_b = resolutionHost.afterResolveSingleModuleNameWithoutWatching) == null ? void 0 : _b.call(resolutionHost, moduleResolutionCache, moduleName, containingFile, result, data); return result; } @@ -124890,6 +110874,7 @@ ${lanes.join("\n")} return endsWith(dirPath, "/node_modules/@types"); } function watchFailedLookupLocationsOfExternalModuleResolutions(name, resolution, filePath, getResolutionWithResolvedFileName, deferWatchingNonRelativeResolution) { + var _resolution$files; var _a; if (resolution.refCount) { resolution.refCount++; @@ -124906,25 +110891,21 @@ ${lanes.join("\n")} 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); } } - (resolution.files ?? (resolution.files = /* @__PURE__ */ new Set())).add(filePath); + ((_resolution$files = resolution.files) !== null && _resolution$files !== void 0 ? _resolution$files : resolution.files = /* @__PURE__ */new Set()).add(filePath); } function watchFailedLookupLocation(failedLookupLocation, setAtRoot) { const failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation); - const toWatch = getDirectoryToWatchFailedLookupLocation( - failedLookupLocation, - failedLookupLocationPath, - rootDir, - rootPath, - rootPathComponents, - getCurrentDirectory - ); + const toWatch = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath, rootDir, rootPath, rootPathComponents, getCurrentDirectory); if (toWatch) { - const { dir, dirPath, nonRecursive } = toWatch; + const { + dir, + dirPath, + nonRecursive + } = toWatch; if (dirPath === rootPath) { Debug.assert(nonRecursive); setAtRoot = true; @@ -124936,51 +110917,42 @@ ${lanes.join("\n")} } function watchFailedLookupLocationOfResolution(resolution) { Debug.assert(!!resolution.refCount); - const { failedLookupLocations, affectingLocations, node10Result } = resolution; - if (!(failedLookupLocations == null ? void 0 : failedLookupLocations.length) && !(affectingLocations == null ? void 0 : affectingLocations.length) && !node10Result) - return; - if ((failedLookupLocations == null ? void 0 : failedLookupLocations.length) || node10Result) - resolutionsWithFailedLookups.add(resolution); + const { + failedLookupLocations, + affectingLocations, + node10Result + } = resolution; + if (!(failedLookupLocations == null ? void 0 : failedLookupLocations.length) && !(affectingLocations == null ? void 0 : affectingLocations.length) && !node10Result) return; + if ((failedLookupLocations == null ? void 0 : failedLookupLocations.length) || node10Result) resolutionsWithFailedLookups.add(resolution); let setAtRoot = false; if (failedLookupLocations) { for (const failedLookupLocation of failedLookupLocations) { setAtRoot = watchFailedLookupLocation(failedLookupLocation, setAtRoot); } } - if (node10Result) - setAtRoot = watchFailedLookupLocation(node10Result, setAtRoot); + if (node10Result) setAtRoot = watchFailedLookupLocation(node10Result, setAtRoot); if (setAtRoot) { - setDirectoryWatcher( - rootDir, - rootPath, - /*nonRecursive*/ - true - ); + setDirectoryWatcher(rootDir, rootPath, /*nonRecursive*/ + true); } watchAffectingLocationsOfResolution(resolution, !(failedLookupLocations == null ? void 0 : failedLookupLocations.length) && !node10Result); } function watchAffectingLocationsOfResolution(resolution, addToResolutionsWithOnlyAffectingLocations) { Debug.assert(!!resolution.refCount); - const { affectingLocations } = resolution; - if (!(affectingLocations == null ? void 0 : affectingLocations.length)) - return; - if (addToResolutionsWithOnlyAffectingLocations) - resolutionsWithOnlyAffectingLocations.add(resolution); + const { + affectingLocations + } = resolution; + if (!(affectingLocations == null ? void 0 : affectingLocations.length)) return; + if (addToResolutionsWithOnlyAffectingLocations) resolutionsWithOnlyAffectingLocations.add(resolution); for (const affectingLocation of affectingLocations) { - createFileWatcherOfAffectingLocation( - affectingLocation, - /*forResolution*/ - true - ); + createFileWatcherOfAffectingLocation(affectingLocation, /*forResolution*/ + true); } } 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; @@ -125007,10 +110979,10 @@ ${lanes.join("\n")} symlinks: void 0 }; fileWatchesOfAffectingLocations.set(locationToWatch, watcher); - if (isSymlink) - symlinkWatcher = watcher; + if (isSymlink) symlinkWatcher = watcher; } if (isSymlink) { + var _symlinkWatcher$symli; Debug.assert(!!symlinkWatcher); const watcher = { watcher: { @@ -125028,17 +111000,16 @@ ${lanes.join("\n")} symlinks: void 0 }; fileWatchesOfAffectingLocations.set(affectingLocation, watcher); - (symlinkWatcher.symlinks ?? (symlinkWatcher.symlinks = /* @__PURE__ */ new Set())).add(affectingLocation); + ((_symlinkWatcher$symli = symlinkWatcher.symlinks) !== null && _symlinkWatcher$symli !== void 0 ? _symlinkWatcher$symli : symlinkWatcher.symlinks = /* @__PURE__ */new Set()).add(affectingLocation); } } function invalidateAffectingFileWatcher(path, packageJsonMap) { + var _affectingPathChecks, _affectingPathChecksF; 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); - (_a = watcher == null ? void 0 : watcher.symlinks) == null ? void 0 : _a.forEach((path2) => invalidateAffectingFileWatcher(path2, packageJsonMap)); + if (watcher == null ? void 0 : watcher.resolutions) ((_affectingPathChecks = affectingPathChecks) !== null && _affectingPathChecks !== void 0 ? _affectingPathChecks : affectingPathChecks = /* @__PURE__ */new Set()).add(path); + if (watcher == null ? void 0 : watcher.files) ((_affectingPathChecksF = affectingPathChecksForFile) !== null && _affectingPathChecksF !== void 0 ? _affectingPathChecksF : 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)); } function watchFailedLookupLocationOfNonRelativeModuleResolutions(resolutions, name) { @@ -125046,11 +111017,8 @@ ${lanes.join("\n")} if (!program || !program.getTypeChecker().tryFindAmbientModuleWithoutAugmentations(name)) { resolutions.forEach(watchFailedLookupLocationOfResolution); } else { - resolutions.forEach((resolution) => watchAffectingLocationsOfResolution( - resolution, - /*addToResolutionsWithOnlyAffectingLocations*/ - true - )); + resolutions.forEach(resolution => watchAffectingLocationsOfResolution(resolution, /*addToResolutionsWithOnlyAffectingLocations*/ + true)); } } function setDirectoryWatcher(dir, dirPath, nonRecursive) { @@ -125059,21 +111027,20 @@ ${lanes.join("\n")} Debug.assert(!!nonRecursive === !!dirWatcher.nonRecursive); dirWatcher.refCount++; } else { - directoryWatchesOfFailedLookups.set(dirPath, { watcher: createDirectoryWatcher(dir, dirPath, nonRecursive), refCount: 1, nonRecursive }); + directoryWatchesOfFailedLookups.set(dirPath, { + watcher: createDirectoryWatcher(dir, dirPath, nonRecursive), + refCount: 1, + nonRecursive + }); } } function stopWatchFailedLookupLocation(failedLookupLocation, removeAtRoot, syncDirWatcherRemove) { const failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation); - const toWatch = getDirectoryToWatchFailedLookupLocation( - failedLookupLocation, - failedLookupLocationPath, - rootDir, - rootPath, - rootPathComponents, - getCurrentDirectory - ); + const toWatch = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath, rootDir, rootPath, rootPathComponents, getCurrentDirectory); if (toWatch) { - const { dirPath } = toWatch; + const { + dirPath + } = toWatch; if (dirPath === rootPath) { removeAtRoot = true; } else { @@ -125092,10 +111059,13 @@ ${lanes.join("\n")} 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, node10Result } = resolution; + const { + failedLookupLocations, + affectingLocations, + node10Result + } = resolution; if (resolutionsWithFailedLookups.delete(resolution)) { let removeAtRoot = false; if (failedLookupLocations) { @@ -125103,10 +111073,8 @@ ${lanes.join("\n")} removeAtRoot = stopWatchFailedLookupLocation(failedLookupLocation, removeAtRoot, syncDirWatcherRemove); } } - if (node10Result) - removeAtRoot = stopWatchFailedLookupLocation(node10Result, removeAtRoot, syncDirWatcherRemove); - if (removeAtRoot) - removeDirectoryWatcher(rootPath, syncDirWatcherRemove); + if (node10Result) removeAtRoot = stopWatchFailedLookupLocation(node10Result, removeAtRoot, syncDirWatcherRemove); + if (removeAtRoot) removeDirectoryWatcher(rootPath, syncDirWatcherRemove); } else if (affectingLocations == null ? void 0 : affectingLocations.length) { resolutionsWithOnlyAffectingLocations.delete(resolution); } @@ -125114,19 +111082,17 @@ ${lanes.join("\n")} 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) => { + return resolutionHost.watchDirectoryOfFailedLookupLocation(directory, fileOrDirectory => { const fileOrDirectoryPath = resolutionHost.toPath(fileOrDirectory); if (cachedDirectoryStructureHost) { cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath); @@ -125134,45 +111100,35 @@ ${lanes.join("\n")} scheduleInvalidateResolutionOfFailedLookupLocation(fileOrDirectoryPath, dirPath === fileOrDirectoryPath); }, nonRecursive ? 0 /* None */ : 1 /* Recursive */); } + function removeResolutionsOfFileFromCache(cache, filePath, getResolutionWithResolvedFileName, syncDirWatcherRemove) { const resolutions = cache.get(filePath); if (resolutions) { - resolutions.forEach( - (resolution) => stopWatchFailedLookupLocationOfResolution( - resolution, - filePath, - getResolutionWithResolvedFileName, - syncDirWatcherRemove - ) - ); + resolutions.forEach(resolution => stopWatchFailedLookupLocationOfResolution(resolution, filePath, getResolutionWithResolvedFileName, syncDirWatcherRemove)); cache.delete(filePath); } } 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; - resolvedProjectReference.commandLine.fileNames.forEach((f) => removeResolutionsOfFile(resolutionHost.toPath(f))); + if (!resolvedProjectReference) return; + resolvedProjectReference.commandLine.fileNames.forEach(f => removeResolutionsOfFile(resolutionHost.toPath(f))); } function removeResolutionsOfFile(filePath, syncDirWatcherRemove) { removeResolutionsOfFileFromCache(resolvedModuleNames, filePath, getResolvedModule, syncDirWatcherRemove); 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; + resolutions.forEach(resolution => { + 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); + var _filesWithInvalidated; + ((_filesWithInvalidated = filesWithInvalidatedResolutions) !== null && _filesWithInvalidated !== void 0 ? _filesWithInvalidated : filesWithInvalidatedResolutions = /* @__PURE__ */new Set()).add(containingFilePath); hasChangedAutomaticTypeDirectiveNames = hasChangedAutomaticTypeDirectiveNames || endsWith(containingFilePath, inferredTypesContainingFile); } }); @@ -125191,19 +111147,18 @@ ${lanes.join("\n")} } function scheduleInvalidateResolutionOfFailedLookupLocation(fileOrDirectoryPath, isCreatingWatchedDirectory) { if (isCreatingWatchedDirectory) { - (isInDirectoryChecks || (isInDirectoryChecks = /* @__PURE__ */ new Set())).add(fileOrDirectoryPath); + (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; } const dirOfFileOrDirectory = getDirectoryPath(fileOrDirectoryPath); if (isNodeModulesAtTypesDirectory(fileOrDirectoryPath) || isNodeModulesDirectory(fileOrDirectoryPath) || isNodeModulesAtTypesDirectory(dirOfFileOrDirectory) || isNodeModulesDirectory(dirOfFileOrDirectory)) { - (failedLookupChecks || (failedLookupChecks = /* @__PURE__ */ new Set())).add(fileOrDirectoryPath); - (startsWithPathChecks || (startsWithPathChecks = /* @__PURE__ */ new Set())).add(fileOrDirectoryPath); + (failedLookupChecks || (failedLookupChecks = /* @__PURE__ */new Set())).add(fileOrDirectoryPath); + (startsWithPathChecks || (startsWithPathChecks = /* @__PURE__ */new Set())).add(fileOrDirectoryPath); } else { if (isEmittedFileOfProgram(resolutionHost.getCurrentProgram(), fileOrDirectoryPath)) { return false; @@ -125211,14 +111166,10 @@ ${lanes.join("\n")} if (fileExtensionIs(fileOrDirectoryPath, ".map")) { return false; } - (failedLookupChecks || (failedLookupChecks = /* @__PURE__ */ new Set())).add(fileOrDirectoryPath); - const packagePath = parseNodeModuleFromPath( - fileOrDirectoryPath, - /*isFolder*/ - true - ); - if (packagePath) - (startsWithPathChecks || (startsWithPathChecks = /* @__PURE__ */ new Set())).add(packagePath); + (failedLookupChecks || (failedLookupChecks = /* @__PURE__ */new Set())).add(fileOrDirectoryPath); + const packagePath = parseNodeModuleFromPath(fileOrDirectoryPath, /*isFolder*/ + true); + if (packagePath) (startsWithPathChecks || (startsWithPathChecks = /* @__PURE__ */new Set())).add(packagePath); } } resolutionHost.scheduleInvalidateResolutionsOfFailedLookupLocations(); @@ -125245,9 +111196,10 @@ ${lanes.join("\n")} } let invalidated = false; if (affectingPathChecksForFile) { - (_a = resolutionHost.getCurrentProgram()) == null ? void 0 : _a.getSourceFiles().forEach((f) => { - if (some(f.packageJsonLocations, (location) => affectingPathChecksForFile.has(location))) { - (filesWithInvalidatedResolutions ?? (filesWithInvalidatedResolutions = /* @__PURE__ */ new Set())).add(f.path); + (_a = resolutionHost.getCurrentProgram()) == null ? void 0 : _a.getSourceFiles().forEach(f => { + if (some(f.packageJsonLocations, location => affectingPathChecksForFile.has(location))) { + var _filesWithInvalidated2; + ((_filesWithInvalidated2 = filesWithInvalidatedResolutions) !== null && _filesWithInvalidated2 !== void 0 ? _filesWithInvalidated2 : filesWithInvalidatedResolutions = /* @__PURE__ */new Set()).add(f.path); invalidated = true; } }); @@ -125267,38 +111219,29 @@ ${lanes.join("\n")} } function canInvalidateFailedLookupResolution(resolution) { var _a; - 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.node10Result && isInvalidatedFailedLookup(resolutionHost.toPath(resolution.node10Result)); + 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.node10Result && isInvalidatedFailedLookup(resolutionHost.toPath(resolution.node10Result)); } function isInvalidatedFailedLookup(locationPath) { - return (failedLookupChecks == null ? void 0 : failedLookupChecks.has(locationPath)) || firstDefinedIterator((startsWithPathChecks == null ? void 0 : startsWithPathChecks.keys()) || [], (fileOrDirectoryPath) => startsWith(locationPath, fileOrDirectoryPath) ? true : void 0) || firstDefinedIterator((isInDirectoryChecks == null ? void 0 : isInDirectoryChecks.keys()) || [], (dirPath) => locationPath.length > dirPath.length && startsWith(locationPath, dirPath) && (isDiskPathRoot(dirPath) || locationPath[dirPath.length] === directorySeparator) ? true : void 0); + return (failedLookupChecks == null ? void 0 : failedLookupChecks.has(locationPath)) || firstDefinedIterator((startsWithPathChecks == null ? void 0 : startsWithPathChecks.keys()) || [], fileOrDirectoryPath => startsWith(locationPath, fileOrDirectoryPath) ? true : void 0) || firstDefinedIterator((isInDirectoryChecks == null ? void 0 : isInDirectoryChecks.keys()) || [], dirPath => locationPath.length > dirPath.length && startsWith(locationPath, dirPath) && (isDiskPathRoot(dirPath) || locationPath[dirPath.length] === directorySeparator) ? true : void 0); } function canInvalidatedFailedLookupResolutionWithAffectingLocation(resolution) { var _a; - return !!affectingPathChecks && ((_a = resolution.affectingLocations) == null ? void 0 : _a.some((location) => affectingPathChecks.has(location))); + return !!affectingPathChecks && ((_a = resolution.affectingLocations) == null ? void 0 : _a.some(location => affectingPathChecks.has(location))); } function closeTypeRootsWatch() { clearMap(typeRootsWatches, closeFileWatcher); } function createTypeRootsWatch(typeRootPath, typeRoot) { - return canWatchTypeRootPath(typeRootPath) ? resolutionHost.watchTypeRootsDirectory(typeRoot, (fileOrDirectory) => { + return canWatchTypeRootPath(typeRootPath) ? resolutionHost.watchTypeRootsDirectory(typeRoot, fileOrDirectory => { const fileOrDirectoryPath = resolutionHost.toPath(fileOrDirectory); if (cachedDirectoryStructureHost) { cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath); } hasChangedAutomaticTypeDirectiveNames = true; resolutionHost.onChangedAutomaticTypeDirectiveNames(); - const dirPath = getDirectoryToWatchFailedLookupLocationFromTypeRoot( - typeRoot, - typeRootPath, - rootPath, - rootPathComponents, - getCurrentDirectory, - (dirPath2) => directoryWatchesOfFailedLookups.has(dirPath2) - ); + const dirPath = getDirectoryToWatchFailedLookupLocationFromTypeRoot(typeRoot, typeRootPath, rootPath, rootPathComponents, getCurrentDirectory, dirPath2 => directoryWatchesOfFailedLookups.has(dirPath2)); if (dirPath) { scheduleInvalidateResolutionOfFailedLookupLocation(fileOrDirectoryPath, dirPath === fileOrDirectoryPath); } @@ -125310,23 +111253,20 @@ ${lanes.join("\n")} closeTypeRootsWatch(); return; } - const typeRoots = getEffectiveTypeRoots(options, { getCurrentDirectory }); + const typeRoots = getEffectiveTypeRoots(options, { + getCurrentDirectory + }); if (typeRoots) { - mutateMap( - typeRootsWatches, - arrayToMap(typeRoots, (tr) => resolutionHost.toPath(tr)), - { - createNewValue: createTypeRootsWatch, - onDeleteValue: closeFileWatcher - } - ); + mutateMap(typeRootsWatches, arrayToMap(typeRoots, tr => resolutionHost.toPath(tr)), { + createNewValue: createTypeRootsWatch, + onDeleteValue: closeFileWatcher + }); } else { closeTypeRootsWatch(); } } function canWatchTypeRootPath(typeRoot) { - if (resolutionHost.getCompilationSettings().typeRoots) - return true; + if (resolutionHost.getCompilationSettings().typeRoots) return true; return canWatchAtTypes(resolutionHost.toPath(typeRoot)); } } @@ -125337,6 +111277,7 @@ ${lanes.join("\n")} var init_resolutionCache = __esm({ "src/compiler/resolutionCache.ts"() { "use strict"; + init_ts2(); } }); @@ -125349,10 +111290,10 @@ ${lanes.join("\n")} getCanonicalFileName: createGetCanonicalFileName(system.useCaseSensitiveFileNames) }; if (!pretty) { - return (diagnostic) => system.write(formatDiagnostic(diagnostic, host)); + return diagnostic => system.write(formatDiagnostic(diagnostic, host)); } const diagnostics = new Array(1); - return (diagnostic) => { + return diagnostic => { diagnostics[0] = diagnostic; system.write(formatDiagnosticsWithColorAndContext(diagnostics, host) + host.getNewLine()); diagnostics[0] = void 0; @@ -125369,14 +111310,15 @@ ${lanes.join("\n")} return contains(screenStartingMessageCodes, diagnostic.code) ? newLine + newLine : newLine; } function getLocaleTimeString(system) { - return !system.now ? (/* @__PURE__ */ new Date()).toLocaleTimeString() : ( - // On some systems / builds of Node, there's a non-breaking space between the time and AM/PM. - // This branch is solely for testing, so just switch it to a normal space for baseline stability. - // See: - // - https://github.com/nodejs/node/issues/45171 - // - https://github.com/nodejs/node/issues/45753 - system.now().toLocaleTimeString("en-US", { timeZone: "UTC" }).replace("\u202F", " ") - ); + return !system.now ? /* @__PURE__ */new Date().toLocaleTimeString() : + // On some systems / builds of Node, there's a non-breaking space between the time and AM/PM. + // This branch is solely for testing, so just switch it to a normal space for baseline stability. + // See: + // - https://github.com/nodejs/node/issues/45171 + // - https://github.com/nodejs/node/issues/45753 + system.now().toLocaleTimeString("en-US", { + timeZone: "UTC" + }).replace("\u202F", " "); } function createWatchStatusReporter(system, pretty) { return pretty ? (diagnostic, newLine, options) => { @@ -125396,29 +111338,29 @@ ${lanes.join("\n")} } function parseConfigFileWithSystem(configFileName, optionsToExtend, extendedConfigCache, watchOptionsToExtend, system, reportDiagnostic) { const host = system; - host.onUnRecoverableConfigFileDiagnostic = (diagnostic) => reportUnrecoverableDiagnostic(system, reportDiagnostic, diagnostic); + host.onUnRecoverableConfigFileDiagnostic = diagnostic => reportUnrecoverableDiagnostic(system, reportDiagnostic, diagnostic); const result = getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host, extendedConfigCache, watchOptionsToExtend); host.onUnRecoverableConfigFileDiagnostic = void 0; return result; } function getErrorCountForSummary(diagnostics) { - return countWhere(diagnostics, (diagnostic) => diagnostic.category === 1 /* Error */); + return countWhere(diagnostics, diagnostic => diagnostic.category === 1 /* Error */); } + function getFilesInErrorForSummary(diagnostics) { - const filesInError = filter(diagnostics, (diagnostic) => diagnostic.category === 1 /* Error */).map( - (errorDiagnostic) => { - if (errorDiagnostic.file === void 0) - return; - return `${errorDiagnostic.file.fileName}`; - } - ); - return filesInError.map((fileName) => { + const filesInError = filter(diagnostics, diagnostic => diagnostic.category === 1 /* Error */).map(errorDiagnostic => { + if (errorDiagnostic.file === void 0) return; + return `${errorDiagnostic.file.fileName}`; + }); + return filesInError.map(fileName => { if (fileName === void 0) { return void 0; } - const diagnosticForFileName = find(diagnostics, (diagnostic) => diagnostic.file !== void 0 && diagnostic.file.fileName === fileName); + const diagnosticForFileName = find(diagnostics, diagnostic => diagnostic.file !== void 0 && diagnostic.file.fileName === fileName); if (diagnosticForFileName !== void 0) { - const { line } = getLineAndCharacterOfPosition(diagnosticForFileName.file, diagnosticForFileName.start); + const { + line + } = getLineAndCharacterOfPosition(diagnosticForFileName.file, diagnosticForFileName.start); return { fileName, line: line + 1 @@ -125432,20 +111374,15 @@ ${lanes.join("\n")} function prettyPathForFileError(error2, cwd) { const line = formatColorAndReset(":" + error2.line, "\x1B[90m" /* Grey */); if (pathIsAbsolute(error2.fileName) && pathIsAbsolute(cwd)) { - return getRelativePathFromDirectory( - cwd, - error2.fileName, - /*ignoreCase*/ - false - ) + line; + return getRelativePathFromDirectory(cwd, error2.fileName, /*ignoreCase*/ + false) + line; } return error2.fileName + line; } function getErrorSummaryText(errorCount, filesInError, newLine, host) { - if (errorCount === 0) - return ""; - const nonNilFiles = filesInError.filter((fileInError) => fileInError !== void 0); - const distinctFileNamesWithLines = nonNilFiles.map((fileInError) => `${fileInError.fileName}:${fileInError.line}`).filter((value, index, self) => self.indexOf(value) === index); + 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()); let messageAndArgs; if (errorCount === 1) { @@ -125458,11 +111395,10 @@ ${lanes.join("\n")} return `${newLine}${flattenDiagnosticMessageText(d.messageText, newLine)}${newLine}${newLine}${suffix}`; } 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 ""; - const numberLength = (num) => Math.log(num) * Math.LOG10E + 1; - const fileToErrorCount = distinctFiles.map((file) => [file, countWhere(filesInError, (fileInError) => fileInError.fileName === file.fileName)]); + 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 ""; + 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); const headerRow = Diagnostics.Errors_Files.message; const leftColumnHeadingLength = headerRow.split(" ")[0].length; @@ -125470,7 +111406,7 @@ ${lanes.join("\n")} const headerPadding = Math.max(numberLength(maxErrors) - leftColumnHeadingLength, 0); let tabularData = ""; tabularData += " ".repeat(headerPadding) + headerRow + "\n"; - fileToErrorCount.forEach((row) => { + fileToErrorCount.forEach(row => { const [file, errorCount] = row; const errorCountDigitsLength = Math.log(errorCount) * Math.LOG10E + 1 | 0; const leftPadding = errorCountDigitsLength < leftPaddingGoal ? " ".repeat(leftPaddingGoal - errorCountDigitsLength) : ""; @@ -125488,7 +111424,7 @@ ${lanes.join("\n")} if (options.explainFiles) { explainFiles(isBuilderProgram2(program) ? program.getProgram() : program, write); } else if (options.listFiles || options.listFilesOnly) { - forEach(program.getSourceFiles(), (file) => { + forEach(program.getSourceFiles(), file => { write(file.fileName); }); } @@ -125496,58 +111432,44 @@ ${lanes.join("\n")} function explainFiles(program, write) { var _a, _b; const reasons = program.getFileIncludeReasons(); - const relativeFileName = (fileName) => convertToRelativePath(fileName, program.getCurrentDirectory(), program.getCanonicalFileName); + const relativeFileName = fileName => convertToRelativePath(fileName, program.getCurrentDirectory(), program.getCanonicalFileName); for (const file of program.getSourceFiles()) { write(`${toFileName(file, relativeFileName)}`); - (_a = reasons.get(file.path)) == null ? void 0 : _a.forEach((reason) => write(` ${fileIncludeReasonToDiagnostics(program, reason, relativeFileName).messageText}`)); - (_b = explainIfFileIsRedirectAndImpliedFormat(file, relativeFileName)) == null ? void 0 : _b.forEach((d) => write(` ${d.messageText}`)); + (_a = reasons.get(file.path)) == null ? void 0 : _a.forEach(reason => write(` ${fileIncludeReasonToDiagnostics(program, reason, relativeFileName).messageText}`)); + (_b = explainIfFileIsRedirectAndImpliedFormat(file, relativeFileName)) == null ? void 0 : _b.forEach(d => write(` ${d.messageText}`)); } } function explainIfFileIsRedirectAndImpliedFormat(file, fileNameConvertor) { var _a; let result; if (file.path !== file.resolvedPath) { - (result ?? (result = [])).push(chainDiagnosticMessages( - /*details*/ - void 0, - Diagnostics.File_is_output_of_project_reference_source_0, - toFileName(file.originalFileName, fileNameConvertor) - )); + var _result5; + ((_result5 = result) !== null && _result5 !== void 0 ? _result5 : result = []).push(chainDiagnosticMessages( /*details*/ + void 0, Diagnostics.File_is_output_of_project_reference_source_0, toFileName(file.originalFileName, fileNameConvertor))); } if (file.redirectInfo) { - (result ?? (result = [])).push(chainDiagnosticMessages( - /*details*/ - void 0, - Diagnostics.File_redirects_to_file_0, - toFileName(file.redirectInfo.redirectTarget, fileNameConvertor) - )); + var _result6; + ((_result6 = result) !== null && _result6 !== void 0 ? _result6 : result = []).push(chainDiagnosticMessages( /*details*/ + void 0, Diagnostics.File_redirects_to_file_0, toFileName(file.redirectInfo.redirectTarget, fileNameConvertor))); } if (isExternalOrCommonJsModule(file)) { switch (file.impliedNodeFormat) { case 99 /* ESNext */: if (file.packageJsonScope) { - (result ?? (result = [])).push(chainDiagnosticMessages( - /*details*/ - void 0, - Diagnostics.File_is_ECMAScript_module_because_0_has_field_type_with_value_module, - toFileName(last(file.packageJsonLocations), fileNameConvertor) - )); + var _result7; + ((_result7 = result) !== null && _result7 !== void 0 ? _result7 : result = []).push(chainDiagnosticMessages( /*details*/ + void 0, Diagnostics.File_is_ECMAScript_module_because_0_has_field_type_with_value_module, toFileName(last(file.packageJsonLocations), fileNameConvertor))); } break; case 1 /* CommonJS */: if (file.packageJsonScope) { - (result ?? (result = [])).push(chainDiagnosticMessages( - /*details*/ - void 0, - file.packageJsonScope.contents.packageJsonContent.type ? Diagnostics.File_is_CommonJS_module_because_0_has_field_type_whose_value_is_not_module : Diagnostics.File_is_CommonJS_module_because_0_does_not_have_field_type, - toFileName(last(file.packageJsonLocations), fileNameConvertor) - )); + var _result8; + ((_result8 = result) !== null && _result8 !== void 0 ? _result8 : result = []).push(chainDiagnosticMessages( /*details*/ + void 0, file.packageJsonScope.contents.packageJsonContent.type ? Diagnostics.File_is_CommonJS_module_because_0_has_field_type_whose_value_is_not_module : Diagnostics.File_is_CommonJS_module_because_0_does_not_have_field_type, toFileName(last(file.packageJsonLocations), fileNameConvertor))); } else if ((_a = file.packageJsonLocations) == null ? void 0 : _a.length) { - (result ?? (result = [])).push(chainDiagnosticMessages( - /*details*/ - void 0, - Diagnostics.File_is_CommonJS_module_because_package_json_was_not_found - )); + var _result9; + ((_result9 = result) !== null && _result9 !== void 0 ? _result9 : result = []).push(chainDiagnosticMessages( /*details*/ + void 0, Diagnostics.File_is_CommonJS_module_because_package_json_was_not_found)); } break; } @@ -125557,25 +111479,21 @@ ${lanes.join("\n")} 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())); - return find(configFile.configFileSpecs.validatedFilesSpec, (fileSpec) => program.getCanonicalFileName(getNormalizedAbsolutePath(fileSpec, basePath)) === filePath); + return find(configFile.configFileSpecs.validatedFilesSpec, fileSpec => program.getCanonicalFileName(getNormalizedAbsolutePath(fileSpec, basePath)) === filePath); } 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(); - return find((_b = configFile == null ? void 0 : configFile.configFileSpecs) == null ? void 0 : _b.validatedIncludeSpecs, (includeSpec) => { - if (isJsonFile && !endsWith(includeSpec, ".json" /* Json */)) - return false; + return find((_b = configFile == null ? void 0 : configFile.configFileSpecs) == null ? void 0 : _b.validatedIncludeSpecs, includeSpec => { + if (isJsonFile && !endsWith(includeSpec, ".json" /* Json */)) return false; const pattern = getPatternFromSpec(includeSpec, basePath, "files"); return !!pattern && getRegexFromPattern(`(${pattern})$`, useCaseSensitiveFileNames2).test(fileName); }); @@ -125612,81 +111530,44 @@ ${lanes.join("\n")} default: Debug.assertNever(reason); } - return chainDiagnosticMessages( - /*details*/ - void 0, - message, - referenceText, - toFileName(referenceLocation.file, fileNameConvertor), - referenceLocation.packageId && packageIdToString(referenceLocation.packageId) - ); + return chainDiagnosticMessages( /*details*/ + void 0, message, referenceText, toFileName(referenceLocation.file, fileNameConvertor), referenceLocation.packageId && packageIdToString(referenceLocation.packageId)); } 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*/ - void 0, - Diagnostics.Matched_by_include_pattern_0_in_1, - matchedByInclude, - toFileName(options.configFile, fileNameConvertor) - ) : ( - // Could be additional files specified as roots or matched by default include - chainDiagnosticMessages( - /*details*/ - void 0, - matchedByInclude ? Diagnostics.Matched_by_default_include_pattern_Asterisk_Asterisk_Slash_Asterisk : Diagnostics.Root_file_specified_for_compilation - ) - ); + return isString(matchedByInclude) ? chainDiagnosticMessages( /*details*/ + void 0, Diagnostics.Matched_by_include_pattern_0_in_1, matchedByInclude, toFileName(options.configFile, fileNameConvertor)) : + // Could be additional files specified as roots or matched by default include + chainDiagnosticMessages( /*details*/ + void 0, matchedByInclude ? Diagnostics.Matched_by_default_include_pattern_Asterisk_Asterisk_Slash_Asterisk : Diagnostics.Root_file_specified_for_compilation); case 1 /* SourceFromProjectReference */: case 2 /* OutputFromProjectReference */: const isOutput = reason.kind === 2 /* OutputFromProjectReference */; const referencedResolvedRef = Debug.checkDefined((_b = program.getResolvedProjectReferences()) == null ? void 0 : _b[reason.index]); - return chainDiagnosticMessages( - /*details*/ - void 0, - outFile(options) ? isOutput ? Diagnostics.Output_from_referenced_project_0_included_because_1_specified : Diagnostics.Source_from_referenced_project_0_included_because_1_specified : isOutput ? Diagnostics.Output_from_referenced_project_0_included_because_module_is_specified_as_none : Diagnostics.Source_from_referenced_project_0_included_because_module_is_specified_as_none, - toFileName(referencedResolvedRef.sourceFile.fileName, fileNameConvertor), - options.outFile ? "--outFile" : "--out" - ); - case 8 /* AutomaticTypeDirectiveFile */: { - const messageAndArgs = options.types ? reason.packageId ? [Diagnostics.Entry_point_of_type_library_0_specified_in_compilerOptions_with_packageId_1, reason.typeReference, packageIdToString(reason.packageId)] : [Diagnostics.Entry_point_of_type_library_0_specified_in_compilerOptions, reason.typeReference] : reason.packageId ? [Diagnostics.Entry_point_for_implicit_type_library_0_with_packageId_1, reason.typeReference, packageIdToString(reason.packageId)] : [Diagnostics.Entry_point_for_implicit_type_library_0, reason.typeReference]; - return chainDiagnosticMessages( - /*details*/ - void 0, - ...messageAndArgs - ); - } - case 6 /* LibFile */: { - if (reason.index !== void 0) - return chainDiagnosticMessages( - /*details*/ - void 0, - Diagnostics.Library_0_specified_in_compilerOptions, - options.lib[reason.index] - ); - const target = forEachEntry(targetOptionDeclaration.type, (value, key) => value === getEmitScriptTarget(options) ? key : void 0); - const messageAndArgs = target ? [Diagnostics.Default_library_for_target_0, target] : [Diagnostics.Default_library]; - return chainDiagnosticMessages( - /*details*/ - void 0, - ...messageAndArgs - ); - } + return chainDiagnosticMessages( /*details*/ + void 0, outFile(options) ? isOutput ? Diagnostics.Output_from_referenced_project_0_included_because_1_specified : Diagnostics.Source_from_referenced_project_0_included_because_1_specified : isOutput ? Diagnostics.Output_from_referenced_project_0_included_because_module_is_specified_as_none : Diagnostics.Source_from_referenced_project_0_included_because_module_is_specified_as_none, toFileName(referencedResolvedRef.sourceFile.fileName, fileNameConvertor), options.outFile ? "--outFile" : "--out"); + case 8 /* AutomaticTypeDirectiveFile */: + { + const messageAndArgs = options.types ? reason.packageId ? [Diagnostics.Entry_point_of_type_library_0_specified_in_compilerOptions_with_packageId_1, reason.typeReference, packageIdToString(reason.packageId)] : [Diagnostics.Entry_point_of_type_library_0_specified_in_compilerOptions, reason.typeReference] : reason.packageId ? [Diagnostics.Entry_point_for_implicit_type_library_0_with_packageId_1, reason.typeReference, packageIdToString(reason.packageId)] : [Diagnostics.Entry_point_for_implicit_type_library_0, reason.typeReference]; + return chainDiagnosticMessages( /*details*/ + void 0, ...messageAndArgs); + } + case 6 /* LibFile */: + { + if (reason.index !== void 0) return chainDiagnosticMessages( /*details*/ + void 0, Diagnostics.Library_0_specified_in_compilerOptions, options.lib[reason.index]); + const target = forEachEntry(targetOptionDeclaration.type, (value, key) => value === getEmitScriptTarget(options) ? key : void 0); + const messageAndArgs = target ? [Diagnostics.Default_library_for_target_0, target] : [Diagnostics.Default_library]; + return chainDiagnosticMessages( /*details*/ + void 0, ...messageAndArgs); + } default: Debug.assertNever(reason); } @@ -125699,39 +111580,33 @@ ${lanes.join("\n")} const isListFilesOnly = !!program.getCompilerOptions().listFilesOnly; const allDiagnostics = program.getConfigFileParsingDiagnostics().slice(); const configFileParsingDiagnosticsLength = allDiagnostics.length; - addRange(allDiagnostics, program.getSyntacticDiagnostics( - /*sourceFile*/ - void 0, - cancellationToken - )); + addRange(allDiagnostics, program.getSyntacticDiagnostics( /*sourceFile*/ + void 0, cancellationToken)); if (allDiagnostics.length === configFileParsingDiagnosticsLength) { addRange(allDiagnostics, program.getOptionsDiagnostics(cancellationToken)); if (!isListFilesOnly) { addRange(allDiagnostics, program.getGlobalDiagnostics(cancellationToken)); if (allDiagnostics.length === configFileParsingDiagnosticsLength) { - addRange(allDiagnostics, program.getSemanticDiagnostics( - /*sourceFile*/ - void 0, - cancellationToken - )); + addRange(allDiagnostics, program.getSemanticDiagnostics( /*sourceFile*/ + void 0, cancellationToken)); } } } - const emitResult = isListFilesOnly ? { emitSkipped: true, diagnostics: emptyArray } : program.emit( - /*targetSourceFile*/ - void 0, - writeFile2, - cancellationToken, - emitOnlyDtsFiles, - customTransformers - ); - const { emittedFiles, diagnostics: emitDiagnostics } = emitResult; + const emitResult = isListFilesOnly ? { + emitSkipped: true, + diagnostics: emptyArray + } : program.emit( /*targetSourceFile*/ + void 0, writeFile2, cancellationToken, emitOnlyDtsFiles, customTransformers); + const { + emittedFiles, + diagnostics: emitDiagnostics + } = emitResult; addRange(allDiagnostics, emitDiagnostics); const diagnostics = sortAndDeduplicateDiagnostics(allDiagnostics); diagnostics.forEach(reportDiagnostic); if (write) { const currentDir = program.getCurrentDirectory(); - forEach(emittedFiles, (file) => { + forEach(emittedFiles, file => { const filepath = getNormalizedAbsolutePath(file, currentDir); write(`TSFILE: ${filepath}`); }); @@ -125746,23 +111621,19 @@ ${lanes.join("\n")} }; } function emitFilesAndReportErrorsAndGetExitStatus(program, reportDiagnostic, write, reportSummary, writeFile2, cancellationToken, emitOnlyDtsFiles, customTransformers) { - const { emitResult, diagnostics } = emitFilesAndReportErrors( - program, - reportDiagnostic, - write, - reportSummary, - writeFile2, - cancellationToken, - emitOnlyDtsFiles, - customTransformers - ); + const { + emitResult, + diagnostics + } = emitFilesAndReportErrors(program, reportDiagnostic, write, reportSummary, writeFile2, cancellationToken, emitOnlyDtsFiles, customTransformers); if (emitResult.emitSkipped && diagnostics.length > 0) { return 1 /* DiagnosticsPresent_OutputsSkipped */; } else if (diagnostics.length > 0) { return 2 /* DiagnosticsPresent_OutputsGenerated */; } + return 0 /* Success */; } + function createWatchHost(system = sys, reportWatchStatus2) { const onWatchStatusChange = reportWatchStatus2 || createWatchStatusReporter(system); return { @@ -125775,7 +111646,7 @@ ${lanes.join("\n")} } function createWatchFactory(host, options) { const watchLogLevel = host.trace ? options.extendedDiagnostics ? 2 /* Verbose */ : options.diagnostics ? 1 /* TriggerOnly */ : 0 /* None */ : 0 /* None */; - const writeLog = watchLogLevel !== 0 /* None */ ? (s) => host.trace(s) : noop; + const writeLog = watchLogLevel !== 0 /* None */ ? s => host.trace(s) : noop; const result = getWatchFactory(host, watchLogLevel, writeLog); result.writeLog = writeLog; return result; @@ -125783,25 +111654,17 @@ ${lanes.join("\n")} function createCompilerHostFromProgramHost(host, getCompilerOptions, directoryStructureHost = host) { const useCaseSensitiveFileNames2 = host.useCaseSensitiveFileNames(); const compilerHost = { - getSourceFile: createGetSourceFile( - (fileName, encoding) => !encoding ? compilerHost.readFile(fileName) : host.readFile(fileName, encoding), - getCompilerOptions, - /*setParentNodes*/ - void 0 - ), + getSourceFile: createGetSourceFile((fileName, encoding) => !encoding ? compilerHost.readFile(fileName) : host.readFile(fileName, encoding), getCompilerOptions, /*setParentNodes*/ + void 0), getDefaultLibLocation: maybeBind(host, host.getDefaultLibLocation), - getDefaultLibFileName: (options) => host.getDefaultLibFileName(options), - writeFile: createWriteFileMeasuringIO( - (path, data, writeByteOrderMark) => host.writeFile(path, data, writeByteOrderMark), - (path) => host.createDirectory(path), - (path) => host.directoryExists(path) - ), + getDefaultLibFileName: options => host.getDefaultLibFileName(options), + writeFile: createWriteFileMeasuringIO((path, data, writeByteOrderMark) => host.writeFile(path, data, writeByteOrderMark), path => host.createDirectory(path), path => host.directoryExists(path)), getCurrentDirectory: memoize(() => host.getCurrentDirectory()), useCaseSensitiveFileNames: () => useCaseSensitiveFileNames2, getCanonicalFileName: createGetCanonicalFileName(useCaseSensitiveFileNames2), getNewLine: () => getNewLineCharacter(getCompilerOptions()), - fileExists: (f) => host.fileExists(f), - readFile: (f) => host.readFile(f), + fileExists: f => host.fileExists(f), + readFile: f => host.readFile(f), trace: maybeBind(host, host.trace), directoryExists: maybeBind(directoryStructureHost, directoryStructureHost.directoryExists), getDirectories: maybeBind(directoryStructureHost, directoryStructureHost.getDirectories), @@ -125863,16 +111726,16 @@ ${lanes.join("\n")} getNewLine: () => system.newLine, getCurrentDirectory: memoize(() => system.getCurrentDirectory()), getDefaultLibLocation, - getDefaultLibFileName: (options) => combinePaths(getDefaultLibLocation(), getDefaultLibFileName(options)), - fileExists: (path) => system.fileExists(path), + getDefaultLibFileName: options => combinePaths(getDefaultLibLocation(), getDefaultLibFileName(options)), + fileExists: path => system.fileExists(path), readFile: (path, encoding) => system.readFile(path, encoding), - directoryExists: (path) => system.directoryExists(path), - getDirectories: (path) => system.getDirectories(path), + directoryExists: path => system.directoryExists(path), + getDirectories: path => system.getDirectories(path), readDirectory: (path, extensions, exclude, include, depth) => system.readDirectory(path, extensions, exclude, include, depth), realpath: maybeBind(system, system.realpath), getEnvironmentVariable: maybeBind(system, system.getEnvironmentVariable), - trace: (s) => system.write(s + system.newLine), - createDirectory: (path) => system.createDirectory(path), + trace: s => system.write(s + system.newLine), + createDirectory: path => system.createDirectory(path), writeFile: (path, data, writeByteOrderMark) => system.writeFile(path, data, writeByteOrderMark), createHash: maybeBind(system, system.createHash), createProgram: createProgram2 || createEmitAndSemanticDiagnosticsBuilderProgram, @@ -125881,23 +111744,13 @@ ${lanes.join("\n")} }; } function createWatchCompilerHost(system = sys, createProgram2, reportDiagnostic, reportWatchStatus2) { - const write = (s) => system.write(s + system.newLine); + const write = s => system.write(s + system.newLine); const result = createProgramHost(system, createProgram2); copyProperties(result, createWatchHost(system, reportWatchStatus2)); - result.afterProgramCreate = (builderProgram) => { + result.afterProgramCreate = builderProgram => { const compilerOptions = builderProgram.getCompilerOptions(); const newLine = getNewLineCharacter(compilerOptions); - emitFilesAndReportErrors( - builderProgram, - reportDiagnostic, - write, - (errorCount) => result.onWatchStatusChange( - createCompilerDiagnostic(getWatchErrorSummaryDiagnosticMessage(errorCount), errorCount), - newLine, - compilerOptions, - errorCount - ) - ); + emitFilesAndReportErrors(builderProgram, reportDiagnostic, write, errorCount => result.onWatchStatusChange(createCompilerDiagnostic(getWatchErrorSummaryDiagnosticMessage(errorCount), errorCount), newLine, compilerOptions, errorCount)); }; return result; } @@ -125905,6 +111758,7 @@ ${lanes.join("\n")} reportDiagnostic(diagnostic); system.exit(1 /* DiagnosticsPresent_OutputsSkipped */); } + function createWatchCompilerHostOfConfigFile({ configFileName, optionsToExtend, @@ -125917,7 +111771,7 @@ ${lanes.join("\n")} }) { const diagnosticReporter = reportDiagnostic || createDiagnosticReporter(system); const host = createWatchCompilerHost(system, createProgram2, diagnosticReporter, reportWatchStatus2); - host.onUnRecoverableConfigFileDiagnostic = (diagnostic) => reportUnrecoverableDiagnostic(system, diagnosticReporter, diagnostic); + host.onUnRecoverableConfigFileDiagnostic = diagnostic => reportUnrecoverableDiagnostic(system, diagnosticReporter, diagnostic); host.configFileName = configFileName; host.optionsToExtend = optionsToExtend; host.watchOptionsToExtend = watchOptionsToExtend; @@ -125945,31 +111799,25 @@ ${lanes.join("\n")} const system = input.system || sys; const host = input.host || (input.host = createIncrementalCompilerHost(input.options, system)); const builderProgram = createIncrementalProgram(input); - const exitStatus = emitFilesAndReportErrorsAndGetExitStatus( - builderProgram, - input.reportDiagnostic || createDiagnosticReporter(system), - (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); + const exitStatus = emitFilesAndReportErrorsAndGetExitStatus(builderProgram, input.reportDiagnostic || createDiagnosticReporter(system), 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); return exitStatus; } var sysFormatDiagnosticsHost, screenStartingMessageCodes, noopFileWatcher, returnNoopFileWatcher, WatchType; var init_watch = __esm({ "src/compiler/watch.ts"() { "use strict"; + init_ts2(); sysFormatDiagnosticsHost = sys ? { getCurrentDirectory: () => sys.getCurrentDirectory(), getNewLine: () => sys.newLine, getCanonicalFileName: createGetCanonicalFileName(sys.useCaseSensitiveFileNames) } : void 0; - screenStartingMessageCodes = [ - Diagnostics.Starting_compilation_in_watch_mode.code, - Diagnostics.File_change_detected_Starting_incremental_compilation.code - ]; - noopFileWatcher = { close: noop }; + screenStartingMessageCodes = [Diagnostics.Starting_compilation_in_watch_mode.code, Diagnostics.File_change_detected_Starting_incremental_compilation.code]; + noopFileWatcher = { + close: noop + }; returnNoopFileWatcher = () => noopFileWatcher; WatchType = { ConfigFile: "Config file", @@ -126000,32 +111848,25 @@ ${lanes.join("\n")} // 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) { - const host = createCompilerHostWorker( - options, - /*setParentNodes*/ - void 0, - system - ); + const host = createCompilerHostWorker(options, /*setParentNodes*/ + void 0, system); host.createHash = maybeBind(system, system.createHash); host.storeFilesChangingSignatureDuringEmit = system.storeFilesChangingSignatureDuringEmit; setGetSourceFileAsHashVersioned(host); - changeCompilerHostLikeToUseCache(host, (fileName) => toPath(fileName, host.getCurrentDirectory(), host.getCanonicalFileName)); + changeCompilerHostLikeToUseCache(host, fileName => toPath(fileName, host.getCurrentDirectory(), host.getCanonicalFileName)); return host; } function createIncrementalProgram({ @@ -126077,13 +111918,24 @@ ${lanes.join("\n")} let sharedExtendedConfigFileWatchers; let extendedConfigCache = host.extendedConfigCache; let reportFileChangeDetectedOnCreateProgram = false; - const sourceFilesCache = /* @__PURE__ */ new Map(); + const sourceFilesCache = /* @__PURE__ */new Map(); let missingFilePathsRequestedForRelease; let hasChangedCompilerOptions = false; const useCaseSensitiveFileNames2 = host.useCaseSensitiveFileNames(); const currentDirectory = host.getCurrentDirectory(); - const { configFileName, optionsToExtend: optionsToExtendForConfigFile = {}, watchOptionsToExtend, extraFileExtensions, createProgram: createProgram2 } = host; - let { rootFiles: rootFileNames, options: compilerOptions, watchOptions, projectReferences } = host; + const { + configFileName, + optionsToExtend: optionsToExtendForConfigFile = {}, + watchOptionsToExtend, + extraFileExtensions, + createProgram: createProgram2 + } = host; + let { + rootFiles: rootFileNames, + options: compilerOptions, + watchOptions, + projectReferences + } = host; let wildcardDirectories; let configFileParsingDiagnostics; let canConfigFileJsonReportNoInputFiles = false; @@ -126105,7 +111957,11 @@ ${lanes.join("\n")} } Debug.assert(compilerOptions); Debug.assert(rootFileNames); - const { watchFile: watchFile2, watchDirectory, writeLog } = createWatchFactory(host, compilerOptions); + const { + watchFile: watchFile2, + watchDirectory, + writeLog + } = createWatchFactory(host, compilerOptions); const getCanonicalFileName = createGetCanonicalFileName(useCaseSensitiveFileNames2); writeLog(`Current directory: ${currentDirectory} CaseSensitiveFileNames: ${useCaseSensitiveFileNames2}`); let configFileWatcher; @@ -126135,12 +111991,8 @@ ${lanes.join("\n")} compilerHost.getCurrentProgram = getCurrentProgram; compilerHost.writeLog = writeLog; compilerHost.getParsedCommandLine = getParsedCommandLine; - const resolutionCache = createResolutionCache( - compilerHost, - configFileName ? getDirectoryPath(getNormalizedAbsolutePath(configFileName, currentDirectory)) : currentDirectory, - /*logChangesWhenResolvingModule*/ - false - ); + const resolutionCache = createResolutionCache(compilerHost, configFileName ? getDirectoryPath(getNormalizedAbsolutePath(configFileName, currentDirectory)) : currentDirectory, /*logChangesWhenResolvingModule*/ + false); compilerHost.resolveModuleNameLiterals = maybeBind(host, host.resolveModuleNameLiterals); compilerHost.resolveModuleNames = maybeBind(host, host.resolveModuleNames); if (!compilerHost.resolveModuleNameLiterals && !compilerHost.resolveModuleNames) { @@ -126159,13 +112011,23 @@ ${lanes.join("\n")} builderProgram = readBuilderProgram(compilerOptions, compilerHost); synchronizeProgram(); watchConfigFileWildCardDirectories(); - if (configFileName) - updateExtendedConfigFilesWatches(toPath3(configFileName), compilerOptions, watchOptions, WatchType.ExtendedConfigFile); - return configFileName ? { getCurrentProgram: getCurrentBuilderProgram, getProgram: updateProgram, close, getResolutionCache } : { getCurrentProgram: getCurrentBuilderProgram, getProgram: updateProgram, updateRootFileNames, close, getResolutionCache }; + 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(); resolutionCache.clear(); - clearMap(sourceFilesCache, (value) => { + clearMap(sourceFilesCache, value => { if (value && value.fileWatcher) { value.fileWatcher.close(); value.fileWatcher = void 0; @@ -126190,12 +112052,11 @@ ${lanes.join("\n")} missingFilesMap = void 0; } if (parsedConfigs) { - clearMap(parsedConfigs, (config) => { + clearMap(parsedConfigs, config => { 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; @@ -126222,7 +112083,10 @@ ${lanes.join("\n")} resolutionCache.onChangesAffectModuleResolution(); } } - const { hasInvalidatedResolutions, hasInvalidatedLibResolutions } = resolutionCache.createHasInvalidatedResolutions(customHasInvalidatedResolutions, customHasInvalidLibResolutions); + const { + hasInvalidatedResolutions, + hasInvalidatedLibResolutions + } = resolutionCache.createHasInvalidatedResolutions(customHasInvalidatedResolutions, customHasInvalidLibResolutions); const { originalReadFile, originalFileExists, @@ -126231,21 +112095,14 @@ ${lanes.join("\n")} originalWriteFile, readFileWithCache } = changeCompilerHostLikeToUseCache(compilerHost, toPath3); - if (isProgramUptoDate(getCurrentProgram(), rootFileNames, compilerOptions, (path) => getSourceVersion(path, readFileWithCache), (fileName) => compilerHost.fileExists(fileName), hasInvalidatedResolutions, hasInvalidatedLibResolutions, hasChangedAutomaticTypeDirectiveNames, getParsedCommandLine, projectReferences)) { + if (isProgramUptoDate(getCurrentProgram(), rootFileNames, compilerOptions, path => getSourceVersion(path, readFileWithCache), fileName => compilerHost.fileExists(fileName), hasInvalidatedResolutions, hasInvalidatedLibResolutions, hasChangedAutomaticTypeDirectiveNames, getParsedCommandLine, projectReferences)) { if (hasChangedConfigFileParsingErrors) { if (reportFileChangeDetectedOnCreateProgram) { reportWatchDiagnostic(Diagnostics.File_change_detected_Starting_incremental_compilation); } - builderProgram = createProgram2( - /*rootNames*/ - void 0, - /*options*/ - void 0, - compilerHost, - builderProgram, - configFileParsingDiagnostics, - projectReferences - ); + builderProgram = createProgram2( /*rootNames*/ + void 0, /*options*/ + void 0, compilerHost, builderProgram, configFileParsingDiagnostics, projectReferences); hasChangedConfigFileParsingErrors = false; } } else { @@ -126269,8 +112126,7 @@ ${lanes.join("\n")} 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; @@ -126281,7 +112137,7 @@ ${lanes.join("\n")} const oldProgram = getCurrentProgram(); builderProgram = createProgram2(rootFileNames, compilerOptions, compilerHost, builderProgram, configFileParsingDiagnostics, projectReferences); resolutionCache.finishCachingPerDirectoryResolution(builderProgram.getProgram(), oldProgram); - updateMissingFilePathsWatch(builderProgram.getProgram(), missingFilesMap || (missingFilesMap = /* @__PURE__ */ new Map()), watchMissingFilePath); + updateMissingFilePathsWatch(builderProgram.getProgram(), missingFilesMap || (missingFilesMap = /* @__PURE__ */new Map()), watchMissingFilePath); if (needsUpdateInTypeRootWatch) { resolutionCache.updateTypeRootsWatch(); } @@ -126342,7 +112198,11 @@ ${lanes.join("\n")} } else { if (sourceFile) { const fileWatcher = watchFilePath(path, fileName, onSourceFileChange, 250 /* Low */, watchOptions, WatchType.SourceFile); - sourceFilesCache.set(path, { sourceFile, version: sourceFile.version, fileWatcher }); + sourceFilesCache.set(path, { + sourceFile, + version: sourceFile.version, + fileWatcher + }); } else { sourceFilesCache.set(path, false); } @@ -126355,7 +112215,9 @@ ${lanes.join("\n")} const hostSourceFile = sourceFilesCache.get(path); if (hostSourceFile !== void 0) { if (isFileMissingOnHost(hostSourceFile)) { - sourceFilesCache.set(path, { version: false }); + sourceFilesCache.set(path, { + version: false + }); } else { hostSourceFile.version = false; } @@ -126363,10 +112225,8 @@ ${lanes.join("\n")} } 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; } @@ -126395,8 +112255,7 @@ ${lanes.join("\n")} return resolutionCache.hasChangedAutomaticTypeDirectiveNames(); } function clearInvalidateResolutionsOfFailedLookupLocations() { - if (!timerToInvalidateFailedLookupResolutions) - return false; + if (!timerToInvalidateFailedLookupResolutions) return false; host.clearTimeout(timerToInvalidateFailedLookupResolutions); timerToInvalidateFailedLookupResolutions = void 0; return true; @@ -126480,16 +112339,7 @@ ${lanes.join("\n")} } function parseConfigFile2() { Debug.assert(configFileName); - setConfigFileParsingResult( - getParsedCommandLineOfConfigFile( - configFileName, - optionsToExtendForConfigFile, - parseConfigFileHost, - extendedConfigCache || (extendedConfigCache = /* @__PURE__ */ new Map()), - watchOptionsToExtend, - extraFileExtensions - ) - ); + setConfigFileParsingResult(getParsedCommandLineOfConfigFile(configFileName, optionsToExtendForConfigFile, parseConfigFileHost, extendedConfigCache || (extendedConfigCache = /* @__PURE__ */new Map()), watchOptionsToExtend, extraFileExtensions)); } function setConfigFileParsingResult(configFileParseResult) { rootFileNames = configFileParseResult.fileNames; @@ -126505,18 +112355,15 @@ ${lanes.join("\n")} 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); - const fileNames = getFileNamesFromConfigSpecs( - config.parsedCommandLine.options.configFile.configFileSpecs, - getNormalizedAbsolutePath(getDirectoryPath(configFileName2), currentDirectory), - compilerOptions, - parseConfigFileHost - ); - config.parsedCommandLine = { ...config.parsedCommandLine, fileNames }; + const fileNames = getFileNamesFromConfigSpecs(config.parsedCommandLine.options.configFile.configFileSpecs, getNormalizedAbsolutePath(getDirectoryPath(configFileName2), currentDirectory), compilerOptions, parseConfigFileHost); + config.parsedCommandLine = { + ...config.parsedCommandLine, + fileNames + }; config.updateLevel = void 0; return config.parsedCommandLine; } @@ -126527,7 +112374,9 @@ ${lanes.join("\n")} config.parsedCommandLine = parsedCommandLine; config.updateLevel = void 0; } else { - (parsedConfigs || (parsedConfigs = /* @__PURE__ */ new Map())).set(configPath, config = { parsedCommandLine }); + (parsedConfigs || (parsedConfigs = /* @__PURE__ */new Map())).set(configPath, config = { + parsedCommandLine + }); } watchReferencedProject(configFileName2, configPath, config); return parsedCommandLine; @@ -126535,14 +112384,8 @@ ${lanes.join("\n")} function getParsedCommandLineFromConfigFileHost(configFileName2) { const onUnRecoverableConfigFileDiagnostic = parseConfigFileHost.onUnRecoverableConfigFileDiagnostic; parseConfigFileHost.onUnRecoverableConfigFileDiagnostic = noop; - const parsedCommandLine = getParsedCommandLineOfConfigFile( - configFileName2, - /*optionsToExtend*/ - void 0, - parseConfigFileHost, - extendedConfigCache || (extendedConfigCache = /* @__PURE__ */ new Map()), - watchOptionsToExtend - ); + const parsedCommandLine = getParsedCommandLineOfConfigFile(configFileName2, /*optionsToExtend*/ + void 0, parseConfigFileHost, extendedConfigCache || (extendedConfigCache = /* @__PURE__ */new Map()), watchOptionsToExtend); parseConfigFileHost.onUnRecoverableConfigFileDiagnostic = onUnRecoverableConfigFileDiagnostic; return parsedCommandLine; } @@ -126550,11 +112393,9 @@ ${lanes.join("\n")} 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); } @@ -126588,156 +112429,107 @@ ${lanes.join("\n")} } function watchConfigFileWildCardDirectories() { if (wildcardDirectories) { - updateWatchingWildcardDirectories( - watchedWildcardDirectories || (watchedWildcardDirectories = /* @__PURE__ */ new Map()), - new Map(Object.entries(wildcardDirectories)), - watchWildcardDirectory - ); + updateWatchingWildcardDirectories(watchedWildcardDirectories || (watchedWildcardDirectories = /* @__PURE__ */new Map()), new Map(Object.entries(wildcardDirectories)), watchWildcardDirectory); } else if (watchedWildcardDirectories) { clearMap(watchedWildcardDirectories, closeFileWatcherOf); } } function watchWildcardDirectory(directory, flags) { - return watchDirectory( - directory, - (fileOrDirectory) => { - Debug.assert(configFileName); - Debug.assert(compilerOptions); - const fileOrDirectoryPath = toPath3(fileOrDirectory); - if (cachedDirectoryStructureHost) { - cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath); - } - nextSourceFileVersion(fileOrDirectoryPath); - if (isIgnoredFileFromWildCardWatching({ - watchedDirPath: toPath3(directory), - fileOrDirectory, - fileOrDirectoryPath, - configFileName, - extraFileExtensions, - options: compilerOptions, - program: getCurrentBuilderProgram() || rootFileNames, - currentDirectory, - useCaseSensitiveFileNames: useCaseSensitiveFileNames2, - writeLog, - toPath: toPath3 - })) - return; - if (updateLevel !== 2 /* Full */) { - updateLevel = 1 /* RootNamesAndUpdate */; - scheduleProgramUpdate(); - } - }, - flags, - watchOptions, - WatchType.WildcardDirectory - ); + return watchDirectory(directory, fileOrDirectory => { + Debug.assert(configFileName); + Debug.assert(compilerOptions); + const fileOrDirectoryPath = toPath3(fileOrDirectory); + if (cachedDirectoryStructureHost) { + cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath); + } + nextSourceFileVersion(fileOrDirectoryPath); + if (isIgnoredFileFromWildCardWatching({ + watchedDirPath: toPath3(directory), + fileOrDirectory, + fileOrDirectoryPath, + configFileName, + extraFileExtensions, + options: compilerOptions, + program: getCurrentBuilderProgram() || rootFileNames, + currentDirectory, + useCaseSensitiveFileNames: useCaseSensitiveFileNames2, + writeLog, + toPath: toPath3 + })) return; + if (updateLevel !== 2 /* Full */) { + updateLevel = 1 /* RootNamesAndUpdate */; + scheduleProgramUpdate(); + } + }, flags, watchOptions, WatchType.WildcardDirectory); } function updateExtendedConfigFilesWatches(forProjectPath, options, watchOptions2, watchType) { - updateSharedExtendedConfigFileWatcher( - forProjectPath, - options, - sharedExtendedConfigFileWatchers || (sharedExtendedConfigFileWatchers = /* @__PURE__ */ new Map()), - (extendedConfigFileName, extendedConfigFilePath) => watchFile2( - extendedConfigFileName, - (_fileName, eventKind) => { - var _a; - updateCachedSystemWithFile(extendedConfigFileName, extendedConfigFilePath, eventKind); - 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; - 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 */; - resolutionCache.removeResolutionsFromProjectReferenceRedirects(projectPath); - } - scheduleProgramUpdate(); - }); - }, - 2e3 /* High */, - watchOptions2, - watchType - ), - toPath3 - ); + updateSharedExtendedConfigFileWatcher(forProjectPath, options, sharedExtendedConfigFileWatchers || (sharedExtendedConfigFileWatchers = /* @__PURE__ */new Map()), (extendedConfigFileName, extendedConfigFilePath) => watchFile2(extendedConfigFileName, (_fileName, eventKind) => { + var _a; + updateCachedSystemWithFile(extendedConfigFileName, extendedConfigFilePath, eventKind); + 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; + 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 */; + resolutionCache.removeResolutionsFromProjectReferenceRedirects(projectPath); + } + scheduleProgramUpdate(); + }); + }, 2e3 /* High */, watchOptions2, watchType), toPath3); } function watchReferencedProject(configFileName2, configPath, commandLine) { var _a, _b, _c, _d, _e; - commandLine.watcher || (commandLine.watcher = watchFile2( - configFileName2, - (_fileName, eventKind) => { - updateCachedSystemWithFile(configFileName2, configPath, eventKind); - const config = parsedConfigs == null ? void 0 : parsedConfigs.get(configPath); - if (config) - config.updateLevel = 2 /* Full */; - resolutionCache.removeResolutionsFromProjectReferenceRedirects(configPath); - scheduleProgramUpdate(); - }, - 2e3 /* High */, - ((_a = commandLine.parsedCommandLine) == null ? void 0 : _a.watchOptions) || watchOptions, - WatchType.ConfigFileOfReferencedProject - )); + commandLine.watcher || (commandLine.watcher = watchFile2(configFileName2, (_fileName, eventKind) => { + updateCachedSystemWithFile(configFileName2, configPath, eventKind); + const config = parsedConfigs == null ? void 0 : parsedConfigs.get(configPath); + if (config) config.updateLevel = 2 /* Full */; + resolutionCache.removeResolutionsFromProjectReferenceRedirects(configPath); + scheduleProgramUpdate(); + }, 2e3 /* High */, ((_a = commandLine.parsedCommandLine) == null ? void 0 : _a.watchOptions) || watchOptions, WatchType.ConfigFileOfReferencedProject)); if ((_b = commandLine.parsedCommandLine) == null ? void 0 : _b.wildcardDirectories) { - updateWatchingWildcardDirectories( - commandLine.watchedDirectories || (commandLine.watchedDirectories = /* @__PURE__ */ new Map()), - new Map(Object.entries((_c = commandLine.parsedCommandLine) == null ? void 0 : _c.wildcardDirectories)), - (directory, flags) => { - var _a2; - return watchDirectory( - directory, - (fileOrDirectory) => { - const fileOrDirectoryPath = toPath3(fileOrDirectory); - if (cachedDirectoryStructureHost) { - cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath); - } - nextSourceFileVersion(fileOrDirectoryPath); - const config = parsedConfigs == null ? void 0 : parsedConfigs.get(configPath); - if (!(config == null ? void 0 : config.parsedCommandLine)) - return; - if (isIgnoredFileFromWildCardWatching({ - watchedDirPath: toPath3(directory), - fileOrDirectory, - fileOrDirectoryPath, - configFileName: configFileName2, - options: config.parsedCommandLine.options, - program: config.parsedCommandLine.fileNames, - currentDirectory, - useCaseSensitiveFileNames: useCaseSensitiveFileNames2, - writeLog, - toPath: toPath3 - })) - return; - if (config.updateLevel !== 2 /* Full */) { - config.updateLevel = 1 /* RootNamesAndUpdate */; - scheduleProgramUpdate(); - } - }, - flags, - ((_a2 = commandLine.parsedCommandLine) == null ? void 0 : _a2.watchOptions) || watchOptions, - WatchType.WildcardDirectoryOfReferencedProject - ); - } - ); + updateWatchingWildcardDirectories(commandLine.watchedDirectories || (commandLine.watchedDirectories = /* @__PURE__ */new Map()), new Map(Object.entries((_c = commandLine.parsedCommandLine) == null ? void 0 : _c.wildcardDirectories)), (directory, flags) => { + var _a2; + return watchDirectory(directory, fileOrDirectory => { + const fileOrDirectoryPath = toPath3(fileOrDirectory); + if (cachedDirectoryStructureHost) { + cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath); + } + nextSourceFileVersion(fileOrDirectoryPath); + const config = parsedConfigs == null ? void 0 : parsedConfigs.get(configPath); + if (!(config == null ? void 0 : config.parsedCommandLine)) return; + if (isIgnoredFileFromWildCardWatching({ + watchedDirPath: toPath3(directory), + fileOrDirectory, + fileOrDirectoryPath, + configFileName: configFileName2, + options: config.parsedCommandLine.options, + program: config.parsedCommandLine.fileNames, + currentDirectory, + useCaseSensitiveFileNames: useCaseSensitiveFileNames2, + writeLog, + toPath: toPath3 + })) return; + if (config.updateLevel !== 2 /* Full */) { + config.updateLevel = 1 /* RootNamesAndUpdate */; + scheduleProgramUpdate(); + } + }, flags, ((_a2 = commandLine.parsedCommandLine) == null ? void 0 : _a2.watchOptions) || watchOptions, WatchType.WildcardDirectoryOfReferencedProject); + }); } else if (commandLine.watchedDirectories) { clearMap(commandLine.watchedDirectories, closeFileWatcherOf); commandLine.watchedDirectories = void 0; } - updateExtendedConfigFilesWatches( - configPath, - (_d = commandLine.parsedCommandLine) == null ? void 0 : _d.options, - ((_e = commandLine.parsedCommandLine) == null ? void 0 : _e.watchOptions) || watchOptions, - WatchType.ExtendedConfigOfReferencedProject - ); + updateExtendedConfigFilesWatches(configPath, (_d = commandLine.parsedCommandLine) == null ? void 0 : _d.options, ((_e = commandLine.parsedCommandLine) == null ? void 0 : _e.watchOptions) || watchOptions, WatchType.ExtendedConfigOfReferencedProject); } } var init_watchPublic = __esm({ "src/compiler/watchPublic.ts"() { "use strict"; + init_ts2(); } }); @@ -126753,8 +112545,9 @@ ${lanes.join("\n")} var init_tsbuild = __esm({ "src/compiler/tsbuild.ts"() { "use strict"; + init_ts2(); - UpToDateStatusType = /* @__PURE__ */ ((UpToDateStatusType2) => { + UpToDateStatusType = /* @__PURE__ */(UpToDateStatusType2 => { UpToDateStatusType2[UpToDateStatusType2["Unbuildable"] = 0] = "Unbuildable"; UpToDateStatusType2[UpToDateStatusType2["UpToDate"] = 1] = "UpToDate"; UpToDateStatusType2[UpToDateStatusType2["UpToDateWithUpstreamTypes"] = 2] = "UpToDateWithUpstreamTypes"; @@ -126789,10 +112582,10 @@ ${lanes.join("\n")} return existingValue || newValue; } function getOrCreateValueMapFromConfigFileMap(configFileMap, resolved) { - return getOrCreateValueFromConfigFileMap(configFileMap, resolved, () => /* @__PURE__ */ new Map()); + return getOrCreateValueFromConfigFileMap(configFileMap, resolved, () => /* @__PURE__ */new Map()); } function getCurrentTime(host) { - return host.now ? host.now() : /* @__PURE__ */ new Date(); + return host.now ? host.now() : /* @__PURE__ */new Date(); } function isCircularBuildOrder(buildOrder) { return !!buildOrder && !!buildOrder.buildOrder; @@ -126801,7 +112594,7 @@ ${lanes.join("\n")} return isCircularBuildOrder(anyBuildOrder) ? anyBuildOrder.buildOrder : anyBuildOrder; } function createBuilderStatusReporter(system, pretty) { - return (diagnostic) => { + return diagnostic => { let output = pretty ? `[${formatColorAndReset(getLocaleTimeString(system), "\x1B[90m" /* Grey */)}] ` : `${getLocaleTimeString(system)} - `; output += `${flattenDiagnosticMessageText(diagnostic.messageText, system.newLine)}${system.newLine + system.newLine}`; system.write(output); @@ -126809,9 +112602,9 @@ ${lanes.join("\n")} } function createSolutionBuilderHostBase(system, createProgram2, reportDiagnostic, reportSolutionBuilderStatus) { const host = createProgramHost(system, createProgram2); - host.getModifiedTime = system.getModifiedTime ? (path) => system.getModifiedTime(path) : returnUndefined; + host.getModifiedTime = system.getModifiedTime ? path => system.getModifiedTime(path) : returnUndefined; host.setModifiedTime = system.setModifiedTime ? (path, date) => system.setModifiedTime(path, date) : noop; - host.deleteFile = system.deleteFile ? (path) => system.deleteFile(path) : noop; + host.deleteFile = system.deleteFile ? path => system.deleteFile(path) : noop; host.reportDiagnostic = reportDiagnostic || createDiagnosticReporter(system); host.reportSolutionBuilderStatus = reportSolutionBuilderStatus || createBuilderStatusReporter(system); host.now = maybeBind(system, system.now); @@ -126830,30 +112623,18 @@ ${lanes.join("\n")} } function getCompilerOptionsOfBuildOptions(buildOptions) { const result = {}; - commonOptionsWithBuild.forEach((option) => { - if (hasProperty(buildOptions, option.name)) - result[option.name] = buildOptions[option.name]; + commonOptionsWithBuild.forEach(option => { + if (hasProperty(buildOptions, option.name)) result[option.name] = buildOptions[option.name]; }); return result; } function createSolutionBuilder(host, rootNames, defaultOptions) { - return createSolutionBuilderWorker( - /*watch*/ - false, - host, - rootNames, - defaultOptions - ); + return createSolutionBuilderWorker( /*watch*/ + false, host, rootNames, defaultOptions); } function createSolutionBuilderWithWatch(host, rootNames, defaultOptions, baseWatchOptions) { - return createSolutionBuilderWorker( - /*watch*/ - true, - host, - rootNames, - defaultOptions, - baseWatchOptions - ); + return createSolutionBuilderWorker( /*watch*/ + true, host, rootNames, defaultOptions, baseWatchOptions); } function createSolutionBuilderState(watch, hostOrHostWithWatch, rootNames, options, baseWatchOptions) { const host = hostOrHostWithWatch; @@ -126861,7 +112642,7 @@ ${lanes.join("\n")} const baseCompilerOptions = getCompilerOptionsOfBuildOptions(options); const compilerHost = createCompilerHostFromProgramHost(host, () => state.projectCompilerOptions); setGetSourceFileAsHashVersioned(compilerHost); - compilerHost.getParsedCommandLine = (fileName) => parseConfigFile(state, fileName, toResolvedConfigFilePath(state, fileName)); + compilerHost.getParsedCommandLine = fileName => parseConfigFile(state, fileName, toResolvedConfigFilePath(state, fileName)); compilerHost.resolveModuleNameLiterals = maybeBind(host, host.resolveModuleNameLiterals); compilerHost.resolveTypeReferenceDirectiveReferences = maybeBind(host, host.resolveTypeReferenceDirectiveReferences); compilerHost.resolveLibrary = maybeBind(host, host.resolveLibrary); @@ -126871,63 +112652,27 @@ ${lanes.join("\n")} let moduleResolutionCache, typeReferenceDirectiveResolutionCache; if (!compilerHost.resolveModuleNameLiterals && !compilerHost.resolveModuleNames) { moduleResolutionCache = createModuleResolutionCache(compilerHost.getCurrentDirectory(), compilerHost.getCanonicalFileName); - compilerHost.resolveModuleNameLiterals = (moduleNames, containingFile, redirectedReference, options2, containingSourceFile) => loadWithModeAwareCache( - moduleNames, - containingFile, - redirectedReference, - options2, - containingSourceFile, - host, - moduleResolutionCache, - createModuleResolutionLoader - ); + compilerHost.resolveModuleNameLiterals = (moduleNames, containingFile, redirectedReference, options2, containingSourceFile) => loadWithModeAwareCache(moduleNames, containingFile, redirectedReference, options2, containingSourceFile, host, moduleResolutionCache, createModuleResolutionLoader); compilerHost.getModuleResolutionCache = () => moduleResolutionCache; } if (!compilerHost.resolveTypeReferenceDirectiveReferences && !compilerHost.resolveTypeReferenceDirectives) { - typeReferenceDirectiveResolutionCache = createTypeReferenceDirectiveResolutionCache( - compilerHost.getCurrentDirectory(), - compilerHost.getCanonicalFileName, - /*options*/ - void 0, - moduleResolutionCache == null ? void 0 : moduleResolutionCache.getPackageJsonInfoCache(), - moduleResolutionCache == null ? void 0 : moduleResolutionCache.optionsToRedirectsKey - ); - compilerHost.resolveTypeReferenceDirectiveReferences = (typeDirectiveNames, containingFile, redirectedReference, options2, containingSourceFile) => loadWithModeAwareCache( - typeDirectiveNames, - containingFile, - redirectedReference, - options2, - containingSourceFile, - host, - typeReferenceDirectiveResolutionCache, - createTypeReferenceResolutionLoader - ); + typeReferenceDirectiveResolutionCache = createTypeReferenceDirectiveResolutionCache(compilerHost.getCurrentDirectory(), compilerHost.getCanonicalFileName, /*options*/ + void 0, moduleResolutionCache == null ? void 0 : moduleResolutionCache.getPackageJsonInfoCache(), moduleResolutionCache == null ? void 0 : moduleResolutionCache.optionsToRedirectsKey); + compilerHost.resolveTypeReferenceDirectiveReferences = (typeDirectiveNames, containingFile, redirectedReference, options2, containingSourceFile) => loadWithModeAwareCache(typeDirectiveNames, containingFile, redirectedReference, options2, containingSourceFile, host, typeReferenceDirectiveResolutionCache, createTypeReferenceResolutionLoader); } let libraryResolutionCache; if (!compilerHost.resolveLibrary) { - libraryResolutionCache = createModuleResolutionCache( - compilerHost.getCurrentDirectory(), - compilerHost.getCanonicalFileName, - /*options*/ - void 0, - moduleResolutionCache == null ? void 0 : moduleResolutionCache.getPackageJsonInfoCache() - ); - compilerHost.resolveLibrary = (libraryName, resolveFrom, options2) => resolveLibrary( - libraryName, - resolveFrom, - options2, - host, - libraryResolutionCache - ); + libraryResolutionCache = createModuleResolutionCache(compilerHost.getCurrentDirectory(), compilerHost.getCanonicalFileName, /*options*/ + void 0, moduleResolutionCache == null ? void 0 : moduleResolutionCache.getPackageJsonInfoCache()); + compilerHost.resolveLibrary = (libraryName, resolveFrom, options2) => resolveLibrary(libraryName, resolveFrom, options2, host, libraryResolutionCache); } - compilerHost.getBuildInfo = (fileName, configFilePath) => getBuildInfo3( - state, - fileName, - toResolvedConfigFilePath(state, configFilePath), - /*modifiedTime*/ - void 0 - ); - const { watchFile: watchFile2, watchDirectory, writeLog } = createWatchFactory(hostWithWatch, options); + compilerHost.getBuildInfo = (fileName, configFilePath) => getBuildInfo3(state, fileName, toResolvedConfigFilePath(state, configFilePath), /*modifiedTime*/ + void 0); + const { + watchFile: watchFile2, + watchDirectory, + writeLog + } = createWatchFactory(hostWithWatch, options); const state = { host, hostWithWatch, @@ -126938,23 +112683,23 @@ ${lanes.join("\n")} baseCompilerOptions, rootNames, baseWatchOptions, - resolvedConfigFilePaths: /* @__PURE__ */ new Map(), - configFileCache: /* @__PURE__ */ new Map(), - projectStatus: /* @__PURE__ */ new Map(), - extendedConfigCache: /* @__PURE__ */ new Map(), - buildInfoCache: /* @__PURE__ */ new Map(), - outputTimeStamps: /* @__PURE__ */ new Map(), - builderPrograms: /* @__PURE__ */ new Map(), - diagnostics: /* @__PURE__ */ new Map(), - projectPendingBuild: /* @__PURE__ */ new Map(), - projectErrorsReported: /* @__PURE__ */ new Map(), + resolvedConfigFilePaths: /* @__PURE__ */new Map(), + configFileCache: /* @__PURE__ */new Map(), + projectStatus: /* @__PURE__ */new Map(), + extendedConfigCache: /* @__PURE__ */new Map(), + buildInfoCache: /* @__PURE__ */new Map(), + outputTimeStamps: /* @__PURE__ */new Map(), + builderPrograms: /* @__PURE__ */new Map(), + diagnostics: /* @__PURE__ */new Map(), + projectPendingBuild: /* @__PURE__ */new Map(), + projectErrorsReported: /* @__PURE__ */new Map(), compilerHost, moduleResolutionCache, typeReferenceDirectiveResolutionCache, libraryResolutionCache, // Mutable state buildOrder: void 0, - readFileWithCache: (f) => host.readFile(f), + readFileWithCache: f => host.readFile(f), projectCompilerOptions: baseCompilerOptions, cache: void 0, allProjectBuildPending: true, @@ -126962,13 +112707,13 @@ ${lanes.join("\n")} watchAllProjectsPending: watch, // Watch state watch, - allWatchedWildcardDirectories: /* @__PURE__ */ new Map(), - allWatchedInputFiles: /* @__PURE__ */ new Map(), - allWatchedConfigFiles: /* @__PURE__ */ new Map(), - allWatchedExtendedConfigFiles: /* @__PURE__ */ new Map(), - allWatchedPackageJsonFiles: /* @__PURE__ */ new Map(), - filesWatched: /* @__PURE__ */ new Map(), - lastCachedPackageJsonLookups: /* @__PURE__ */ new Map(), + allWatchedWildcardDirectories: /* @__PURE__ */new Map(), + allWatchedInputFiles: /* @__PURE__ */new Map(), + allWatchedConfigFiles: /* @__PURE__ */new Map(), + allWatchedExtendedConfigFiles: /* @__PURE__ */new Map(), + allWatchedPackageJsonFiles: /* @__PURE__ */new Map(), + filesWatched: /* @__PURE__ */new Map(), + lastCachedPackageJsonLookups: /* @__PURE__ */new Map(), timerToBuildInvalidatedProject: void 0, reportFileChangeDetected: false, watchFile: watchFile2, @@ -126981,10 +112726,11 @@ ${lanes.join("\n")} return toPath(fileName, state.compilerHost.getCurrentDirectory(), state.compilerHost.getCanonicalFileName); } function toResolvedConfigFilePath(state, fileName) { - const { resolvedConfigFilePaths } = state; + 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; @@ -126997,21 +112743,28 @@ ${lanes.join("\n")} return value && isParsedCommandLine(value) ? value : void 0; } function parseConfigFile(state, configFileName, configFilePath) { - const { configFileCache } = state; + const { + configFileCache + } = state; const value = configFileCache.get(configFilePath); if (value) { return isParsedCommandLine(value) ? value : void 0; } mark("SolutionBuilder::beforeConfigFileParsing"); let diagnostic; - const { parseConfigFileHost, baseCompilerOptions, baseWatchOptions, extendedConfigCache, host } = state; + const { + parseConfigFileHost, + baseCompilerOptions, + baseWatchOptions, + extendedConfigCache, + host + } = state; 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; + parseConfigFileHost.onUnRecoverableConfigFileDiagnostic = d => diagnostic = d; parsed = getParsedCommandLineOfConfigFile(configFileName, baseCompilerOptions, parseConfigFileHost, extendedConfigCache, baseWatchOptions); parseConfigFileHost.onUnRecoverableConfigFileDiagnostic = noop; } @@ -127024,27 +112777,24 @@ ${lanes.join("\n")} return resolveConfigFileProjectName(resolvePath(state.compilerHost.getCurrentDirectory(), name)); } function createBuildOrder(state, roots) { - const temporaryMarks = /* @__PURE__ */ new Map(); - const permanentMarks = /* @__PURE__ */ new Map(); + const temporaryMarks = /* @__PURE__ */new Map(); + const permanentMarks = /* @__PURE__ */new Map(); const circularityReportStack = []; let buildOrder; let circularDiagnostics; for (const root of roots) { visit(root); } - return circularDiagnostics ? { buildOrder: buildOrder || emptyArray, circularDiagnostics } : buildOrder || emptyArray; + 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( - createCompilerDiagnostic( - Diagnostics.Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0, - circularityReportStack.join("\r\n") - ) - ); + (circularDiagnostics || (circularDiagnostics = [])).push(createCompilerDiagnostic(Diagnostics.Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0, circularityReportStack.join("\r\n"))); } return; } @@ -127066,14 +112816,12 @@ ${lanes.join("\n")} return state.buildOrder || createStateBuildOrder(state); } function createStateBuildOrder(state) { - const buildOrder = createBuildOrder(state, state.rootNames.map((f) => resolveProjectName(state, f))); + const buildOrder = createBuildOrder(state, state.rootNames.map(f => resolveProjectName(state, f))); state.resolvedConfigFilePaths.clear(); - const currentProjects = new Map( - getBuildOrderFromAnyBuildOrder(buildOrder).map( - (resolved) => [toResolvedConfigFilePath(state, resolved), true] - ) - ); - const noopOnDelete = { onDeleteValue: noop }; + const currentProjects = new Map(getBuildOrderFromAnyBuildOrder(buildOrder).map(resolved => [toResolvedConfigFilePath(state, resolved), true])); + const noopOnDelete = { + onDeleteValue: noop + }; mutateMapSkippingNewValues(state.configFileCache, currentProjects, noopOnDelete); mutateMapSkippingNewValues(state.projectStatus, currentProjects, noopOnDelete); mutateMapSkippingNewValues(state.builderPrograms, currentProjects, noopOnDelete); @@ -127083,50 +112831,37 @@ ${lanes.join("\n")} mutateMapSkippingNewValues(state.buildInfoCache, currentProjects, noopOnDelete); mutateMapSkippingNewValues(state.outputTimeStamps, currentProjects, noopOnDelete); if (state.watch) { - mutateMapSkippingNewValues( - state.allWatchedConfigFiles, - currentProjects, - { onDeleteValue: closeFileWatcher } - ); - state.allWatchedExtendedConfigFiles.forEach((watcher) => { - watcher.projects.forEach((project) => { + mutateMapSkippingNewValues(state.allWatchedConfigFiles, currentProjects, { + onDeleteValue: closeFileWatcher + }); + state.allWatchedExtendedConfigFiles.forEach(watcher => { + watcher.projects.forEach(project => { if (!currentProjects.has(project)) { watcher.projects.delete(project); } }); watcher.close(); }); - mutateMapSkippingNewValues( - state.allWatchedWildcardDirectories, - currentProjects, - { onDeleteValue: (existingMap) => existingMap.forEach(closeFileWatcherOf) } - ); - mutateMapSkippingNewValues( - state.allWatchedInputFiles, - currentProjects, - { onDeleteValue: (existingMap) => existingMap.forEach(closeFileWatcher) } - ); - mutateMapSkippingNewValues( - state.allWatchedPackageJsonFiles, - currentProjects, - { onDeleteValue: (existingMap) => existingMap.forEach(closeFileWatcher) } - ); + mutateMapSkippingNewValues(state.allWatchedWildcardDirectories, currentProjects, { + onDeleteValue: existingMap => existingMap.forEach(closeFileWatcherOf) + }); + mutateMapSkippingNewValues(state.allWatchedInputFiles, currentProjects, { + onDeleteValue: existingMap => existingMap.forEach(closeFileWatcher) + }); + mutateMapSkippingNewValues(state.allWatchedPackageJsonFiles, currentProjects, { + onDeleteValue: existingMap => existingMap.forEach(closeFileWatcher) + }); } return state.buildOrder = buildOrder; } 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; + const projectIndex = findIndex(buildOrderFromState, configFileName => toResolvedConfigFilePath(state, configFileName) === projectPath); + if (projectIndex === -1) return void 0; } const buildOrder = resolvedProject ? createBuildOrder(state, [resolvedProject]) : buildOrderFromState; Debug.assert(!isCircularBuildOrder(buildOrder)); @@ -127138,7 +112873,10 @@ ${lanes.join("\n")} if (state.cache) { disableCache(state); } - const { compilerHost, host } = state; + const { + compilerHost, + host + } = state; const originalReadFileWithCache = state.readFileWithCache; const originalGetSourceFile = compilerHost.getSourceFile; const { @@ -127149,11 +112887,7 @@ ${lanes.join("\n")} originalWriteFile, getSourceFileWithCache, readFileWithCache - } = changeCompilerHostLikeToUseCache( - host, - (fileName) => toPath2(state, fileName), - (...args) => originalGetSourceFile.call(compilerHost, ...args) - ); + } = changeCompilerHostLikeToUseCache(host, fileName => toPath2(state, fileName), (...args) => originalGetSourceFile.call(compilerHost, ...args)); state.readFileWithCache = readFileWithCache; compilerHost.getSourceFile = getSourceFileWithCache; state.cache = { @@ -127167,9 +112901,16 @@ ${lanes.join("\n")} }; } function disableCache(state) { - if (!state.cache) - return; - const { cache, host, compilerHost, extendedConfigCache, moduleResolutionCache, typeReferenceDirectiveResolutionCache, libraryResolutionCache } = state; + if (!state.cache) return; + const { + cache, + host, + compilerHost, + extendedConfigCache, + moduleResolutionCache, + typeReferenceDirectiveResolutionCache, + libraryResolutionCache + } = state; host.readFile = cache.originalReadFile; host.fileExists = cache.originalFileExists; host.directoryExists = cache.originalDirectoryExists; @@ -127187,7 +112928,9 @@ ${lanes.join("\n")} state.projectStatus.delete(resolved); state.diagnostics.delete(resolved); } - function addProjToQueue({ projectPendingBuild }, proj, updateLevel) { + function addProjToQueue({ + projectPendingBuild + }, proj, updateLevel) { const value = projectPendingBuild.get(proj); if (value === void 0) { projectPendingBuild.set(proj, updateLevel); @@ -127196,19 +112939,13 @@ ${lanes.join("\n")} } } 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( - (configFileName) => state.projectPendingBuild.set( - toResolvedConfigFilePath(state, configFileName), - 0 /* Update */ - ) - ); + buildOrder.forEach(configFileName => state.projectPendingBuild.set(toResolvedConfigFilePath(state, configFileName), 0 /* Update */)); + if (cancellationToken) { cancellationToken.throwIfCancellationRequested(); } @@ -127217,6 +112954,7 @@ ${lanes.join("\n")} state.projectPendingBuild.delete(projectPath); return state.diagnostics.has(projectPath) ? 1 /* DiagnosticsPresent_OutputsSkipped */ : 0 /* Success */; } + function createUpdateOutputFileStampsProject(state, project, projectPath, config, buildOrder) { let updateOutputFileStampsPending = true; return { @@ -127252,51 +112990,28 @@ ${lanes.join("\n")} getCompilerOptions: () => config.options, getCurrentDirectory: () => state.compilerHost.getCurrentDirectory(), getBuilderProgram: () => withProgramOrUndefined(identity), - getProgram: () => withProgramOrUndefined( - (program2) => program2.getProgramOrUndefined() - ), - getSourceFile: (fileName) => withProgramOrUndefined( - (program2) => program2.getSourceFile(fileName) - ), - getSourceFiles: () => withProgramOrEmptyArray( - (program2) => program2.getSourceFiles() - ), - getOptionsDiagnostics: (cancellationToken) => withProgramOrEmptyArray( - (program2) => program2.getOptionsDiagnostics(cancellationToken) - ), - getGlobalDiagnostics: (cancellationToken) => withProgramOrEmptyArray( - (program2) => program2.getGlobalDiagnostics(cancellationToken) - ), - getConfigFileParsingDiagnostics: () => withProgramOrEmptyArray( - (program2) => program2.getConfigFileParsingDiagnostics() - ), - getSyntacticDiagnostics: (sourceFile, cancellationToken) => withProgramOrEmptyArray( - (program2) => program2.getSyntacticDiagnostics(sourceFile, cancellationToken) - ), - getAllDependencies: (sourceFile) => withProgramOrEmptyArray( - (program2) => program2.getAllDependencies(sourceFile) - ), - getSemanticDiagnostics: (sourceFile, cancellationToken) => withProgramOrEmptyArray( - (program2) => program2.getSemanticDiagnostics(sourceFile, cancellationToken) - ), - getSemanticDiagnosticsOfNextAffectedFile: (cancellationToken, ignoreSourceFile) => withProgramOrUndefined( - (program2) => program2.getSemanticDiagnosticsOfNextAffectedFile && program2.getSemanticDiagnosticsOfNextAffectedFile(cancellationToken, ignoreSourceFile) - ), + getProgram: () => withProgramOrUndefined(program2 => program2.getProgramOrUndefined()), + getSourceFile: fileName => withProgramOrUndefined(program2 => program2.getSourceFile(fileName)), + getSourceFiles: () => withProgramOrEmptyArray(program2 => program2.getSourceFiles()), + getOptionsDiagnostics: cancellationToken => withProgramOrEmptyArray(program2 => program2.getOptionsDiagnostics(cancellationToken)), + getGlobalDiagnostics: cancellationToken => withProgramOrEmptyArray(program2 => program2.getGlobalDiagnostics(cancellationToken)), + getConfigFileParsingDiagnostics: () => withProgramOrEmptyArray(program2 => program2.getConfigFileParsingDiagnostics()), + getSyntacticDiagnostics: (sourceFile, cancellationToken) => withProgramOrEmptyArray(program2 => program2.getSyntacticDiagnostics(sourceFile, cancellationToken)), + getAllDependencies: sourceFile => withProgramOrEmptyArray(program2 => program2.getAllDependencies(sourceFile)), + getSemanticDiagnostics: (sourceFile, cancellationToken) => withProgramOrEmptyArray(program2 => program2.getSemanticDiagnostics(sourceFile, cancellationToken)), + getSemanticDiagnosticsOfNextAffectedFile: (cancellationToken, ignoreSourceFile) => withProgramOrUndefined(program2 => program2.getSemanticDiagnosticsOfNextAffectedFile && program2.getSemanticDiagnosticsOfNextAffectedFile(cancellationToken, ignoreSourceFile)), emit: (targetSourceFile, writeFile2, cancellationToken, emitOnlyDtsFiles, customTransformers) => { if (targetSourceFile || emitOnlyDtsFiles) { - return withProgramOrUndefined( - (program2) => { - var _a, _b; - return program2.emit(targetSourceFile, writeFile2, cancellationToken, emitOnlyDtsFiles, customTransformers || ((_b = (_a = state.host).getCustomTransformers) == null ? void 0 : _b.call(_a, project))); - } - ); + return withProgramOrUndefined(program2 => { + var _a, _b; + return program2.emit(targetSourceFile, writeFile2, cancellationToken, emitOnlyDtsFiles, customTransformers || ((_b = (_a = state.host).getCustomTransformers) == null ? void 0 : _b.call(_a, project))); + }); } executeSteps(2 /* SemanticDiagnostics */, cancellationToken); if (step === 5 /* EmitBuildInfo */) { return emitBuildInfo(writeFile2, cancellationToken); } - if (step !== 3 /* Emit */) - return void 0; + if (step !== 3 /* Emit */) return void 0; return emit(writeFile2, cancellationToken, customTransformers); }, done @@ -127308,18 +113023,14 @@ ${lanes.join("\n")} getCompilerOptions: () => config.options, getCurrentDirectory: () => state.compilerHost.getCurrentDirectory(), emit: (writeFile2, customTransformers) => { - if (step !== 4 /* EmitBundle */) - return invalidatedProjectOfBundle; + if (step !== 4 /* EmitBundle */) return invalidatedProjectOfBundle; return emitBundle(writeFile2, customTransformers); }, done }; function done(cancellationToken, writeFile2, customTransformers) { executeSteps(8 /* Done */, cancellationToken, writeFile2, customTransformers); - if (kind === 0 /* Build */) - mark("SolutionBuilder::Projects built"); - else - mark("SolutionBuilder::Bundles updated"); + if (kind === 0 /* Build */) mark("SolutionBuilder::Projects built");else mark("SolutionBuilder::Bundles updated"); return doneInvalidatedProject(state, projectPath); } function withProgramOrUndefined(action) { @@ -127338,80 +113049,45 @@ ${lanes.join("\n")} step = 7 /* 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 */; step = 7 /* QueueReferencingProjects */; return; } - const { host, compilerHost } = state; + const { + host, + compilerHost + } = state; state.projectCompilerOptions = config.options; (_a = state.moduleResolutionCache) == null ? void 0 : _a.update(config.options); (_b = state.typeReferenceDirectiveResolutionCache) == null ? void 0 : _b.update(config.options); - program = host.createProgram( - config.fileNames, - config.options, - compilerHost, - getOldProgram(state, projectPath, config), - getConfigFileParsingDiagnostics(config), - config.projectReferences - ); + program = host.createProgram(config.fileNames, config.options, compilerHost, getOldProgram(state, projectPath, config), getConfigFileParsingDiagnostics(config), config.projectReferences); if (state.watch) { - state.lastCachedPackageJsonLookups.set( - projectPath, - state.moduleResolutionCache && map( - state.moduleResolutionCache.getPackageJsonInfoCache().entries(), - ([path, data]) => [state.host.realpath && data ? toPath2(state, state.host.realpath(path)) : path, data] - ) - ); + state.lastCachedPackageJsonLookups.set(projectPath, state.moduleResolutionCache && map(state.moduleResolutionCache.getPackageJsonInfoCache().entries(), ([path, data]) => [state.host.realpath && data ? toPath2(state, state.host.realpath(path)) : path, data])); state.builderPrograms.set(projectPath, program); } step++; } function handleDiagnostics(diagnostics, errorFlags, errorType) { if (diagnostics.length) { - ({ buildResult, step } = buildErrors( - state, - projectPath, - program, - config, - diagnostics, - errorFlags, - errorType - )); + ({ + buildResult, + step + } = buildErrors(state, projectPath, program, config, diagnostics, errorFlags, errorType)); } else { step++; } } function getSyntaxDiagnostics(cancellationToken) { Debug.assertIsDefined(program); - handleDiagnostics( - [ - ...program.getConfigFileParsingDiagnostics(), - ...program.getOptionsDiagnostics(cancellationToken), - ...program.getGlobalDiagnostics(cancellationToken), - ...program.getSyntacticDiagnostics( - /*sourceFile*/ - void 0, - cancellationToken - ) - ], - 8 /* SyntaxErrors */, - "Syntactic" - ); + handleDiagnostics([...program.getConfigFileParsingDiagnostics(), ...program.getOptionsDiagnostics(cancellationToken), ...program.getGlobalDiagnostics(cancellationToken), ...program.getSyntacticDiagnostics( /*sourceFile*/ + void 0, cancellationToken)], 8 /* SyntaxErrors */, "Syntactic"); } function getSemanticDiagnostics(cancellationToken) { - handleDiagnostics( - Debug.checkDefined(program).getSemanticDiagnostics( - /*sourceFile*/ - void 0, - cancellationToken - ), - 16 /* TypeErrors */, - "Semantic" - ); + handleDiagnostics(Debug.checkDefined(program).getSemanticDiagnostics( /*sourceFile*/ + void 0, cancellationToken), 16 /* TypeErrors */, "Semantic"); } function emit(writeFileCallback, cancellationToken, customTransformers) { var _a, _b, _c; @@ -127419,76 +113095,67 @@ ${lanes.join("\n")} Debug.assert(step === 3 /* Emit */); const saved = program.saveEmitState(); let declDiagnostics; - const reportDeclarationDiagnostics = (d) => (declDiagnostics || (declDiagnostics = [])).push(d); + const reportDeclarationDiagnostics = d => (declDiagnostics || (declDiagnostics = [])).push(d); const outputFiles = []; - const { emitResult } = emitFilesAndReportErrors( - program, - reportDeclarationDiagnostics, - /*write*/ - void 0, - /*reportSummary*/ - void 0, - (name, text, writeByteOrderMark, _onError, _sourceFiles, data) => outputFiles.push({ name, text, writeByteOrderMark, data }), - cancellationToken, - /*emitOnlyDtsFiles*/ - false, - customTransformers || ((_b = (_a = state.host).getCustomTransformers) == null ? void 0 : _b.call(_a, project)) - ); + const { + emitResult + } = emitFilesAndReportErrors(program, reportDeclarationDiagnostics, /*write*/ + void 0, /*reportSummary*/ + void 0, (name, text, writeByteOrderMark, _onError, _sourceFiles, data) => outputFiles.push({ + name, + text, + writeByteOrderMark, + data + }), cancellationToken, /*emitOnlyDtsFiles*/ + false, customTransformers || ((_b = (_a = state.host).getCustomTransformers) == null ? void 0 : _b.call(_a, project))); if (declDiagnostics) { program.restoreEmitState(saved); - ({ buildResult, step } = buildErrors( - state, - projectPath, - program, - config, - declDiagnostics, - 32 /* DeclarationEmitErrors */, - "Declaration file" - )); + ({ + buildResult, + step + } = buildErrors(state, projectPath, program, config, declDiagnostics, 32 /* DeclarationEmitErrors */, "Declaration file")); return { emitSkipped: true, diagnostics: emitResult.diagnostics }; } - const { host, compilerHost } = state; + const { + host, + compilerHost + } = state; const resultFlags = ((_c = program.hasChangedEmitSignature) == null ? void 0 : _c.call(program)) ? 0 /* None */ : 2 /* DeclarationOutputUnchanged */; const emitterDiagnostics = createDiagnosticCollection(); - const emittedOutputs = /* @__PURE__ */ new Map(); + const emittedOutputs = /* @__PURE__ */new Map(); const options = program.getCompilerOptions(); const isIncremental = isIncrementalCompilation(options); let outputTimeStampMap; let now; - outputFiles.forEach(({ name, text, writeByteOrderMark, data }) => { + 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); - else if (!isIncremental && state.watch) { + writeFile(writeFileCallback ? { + writeFile: writeFileCallback + } : compilerHost, emitterDiagnostics, name, text, writeByteOrderMark); + 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))); } }); - finishEmit( - emitterDiagnostics, - emittedOutputs, - outputFiles.length ? outputFiles[0].name : getFirstProjectOutput(config, !host.useCaseSensitiveFileNames()), - resultFlags - ); + finishEmit(emitterDiagnostics, emittedOutputs, outputFiles.length ? outputFiles[0].name : getFirstProjectOutput(config, !host.useCaseSensitiveFileNames()), resultFlags); return emitResult; } function emitBuildInfo(writeFileCallback, cancellationToken) { Debug.assertIsDefined(program); Debug.assert(step === 5 /* 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); @@ -127496,7 +113163,7 @@ ${lanes.join("\n")} buildResult = 64 /* EmitErrors */ & buildResult; } if (emitResult.emittedFiles && state.write) { - emitResult.emittedFiles.forEach((name) => listEmittedFile(state, config, name)); + emitResult.emittedFiles.forEach(name => listEmittedFile(state, config, name)); } afterProgramDone(state, program, config); step = 7 /* QueueReferencingProjects */; @@ -127505,19 +113172,14 @@ ${lanes.join("\n")} function finishEmit(emitterDiagnostics, emittedOutputs, oldestOutputFileName, resultFlags) { const emitDiagnostics = emitterDiagnostics.getDiagnostics(); if (emitDiagnostics.length) { - ({ buildResult, step } = buildErrors( - state, - projectPath, - program, - config, - emitDiagnostics, - 64 /* EmitErrors */, - "Emit" - )); + ({ + buildResult, + step + } = buildErrors(state, projectPath, program, config, emitDiagnostics, 64 /* EmitErrors */, "Emit")); return emitDiagnostics; } if (state.write) { - emittedOutputs.forEach((name) => listEmittedFile(state, config, name)); + emittedOutputs.forEach(name => listEmittedFile(state, config, name)); } updateOutputTimestampsWorker(state, config, projectPath, Diagnostics.Updating_unchanged_output_timestamps_of_project_0, emittedOutputs); state.diagnostics.delete(projectPath); @@ -127539,56 +113201,50 @@ ${lanes.join("\n")} step = 7 /* QueueReferencingProjects */; return void 0; } - if (state.options.verbose) - reportStatus(state, Diagnostics.Updating_output_of_project_0, project); - const { compilerHost } = state; + if (state.options.verbose) reportStatus(state, Diagnostics.Updating_output_of_project_0, project); + const { + compilerHost + } = state; state.projectCompilerOptions = config.options; (_b = (_a = state.host).beforeEmitBundle) == null ? void 0 : _b.call(_a, config); - const outputFiles = emitUsingBuildInfo( - config, - compilerHost, - (ref) => { - const refName = resolveProjectName(state, ref.path); - return parseConfigFile(state, refName, toResolvedConfigFilePath(state, refName)); - }, - customTransformers || ((_d = (_c = state.host).getCustomTransformers) == null ? void 0 : _d.call(_c, project)) - ); + const outputFiles = emitUsingBuildInfo(config, compilerHost, ref => { + const refName = resolveProjectName(state, ref.path); + return parseConfigFile(state, refName, toResolvedConfigFilePath(state, refName)); + }, customTransformers || ((_d = (_c = state.host).getCustomTransformers) == null ? void 0 : _d.call(_c, project))); if (isString(outputFiles)) { reportStatus(state, Diagnostics.Cannot_update_output_of_project_0_because_there_was_error_reading_file_1, project, relName(state, outputFiles)); step = 6 /* BuildInvalidatedProjectOfBundle */; - return invalidatedProjectOfBundle = createBuildOrUpdateInvalidedProject( - 0 /* Build */, - state, - project, - projectPath, - projectIndex, - config, - buildOrder - ); + return invalidatedProjectOfBundle = createBuildOrUpdateInvalidedProject(0 /* Build */, state, project, projectPath, projectIndex, config, buildOrder); } Debug.assert(!!outputFiles.length); const emitterDiagnostics = createDiagnosticCollection(); - const emittedOutputs = /* @__PURE__ */ new Map(); + const emittedOutputs = /* @__PURE__ */new Map(); let resultFlags = 2 /* DeclarationOutputUnchanged */; const existingBuildInfo = state.buildInfoCache.get(projectPath).buildInfo || void 0; - outputFiles.forEach(({ name, text, writeByteOrderMark, data }) => { + outputFiles.forEach(({ + name, + text, + writeByteOrderMark, + data + }) => { var _a2, _b2; emittedOutputs.set(toPath2(state, name), name); if (data == null ? void 0 : data.buildInfo) { if (((_a2 = data.buildInfo.program) == null ? void 0 : _a2.outSignature) !== ((_b2 = existingBuildInfo == null ? void 0 : existingBuildInfo.program) == null ? void 0 : _b2.outSignature)) { resultFlags &= ~2 /* DeclarationOutputUnchanged */; } + setBuildInfo(state, data.buildInfo, projectPath, config.options, resultFlags); } - writeFile(writeFileCallback ? { writeFile: writeFileCallback } : compilerHost, emitterDiagnostics, name, text, writeByteOrderMark); + writeFile(writeFileCallback ? { + writeFile: writeFileCallback + } : compilerHost, emitterDiagnostics, name, text, writeByteOrderMark); }); - const emitDiagnostics = finishEmit( - emitterDiagnostics, - emittedOutputs, - outputFiles[0].name, - resultFlags - ); - return { emitSkipped: false, diagnostics: emitDiagnostics }; + const emitDiagnostics = finishEmit(emitterDiagnostics, emittedOutputs, outputFiles[0].name, resultFlags); + return { + emitSkipped: false, + diagnostics: emitDiagnostics + }; } function executeSteps(till, cancellationToken, writeFile2, customTransformers) { while (step <= till && step < 8 /* Done */) { @@ -127628,23 +113284,24 @@ ${lanes.join("\n")} } } } - function needsBuild({ options }, status, config) { - if (status.type !== 3 /* OutOfDateWithPrepend */ || options.force) - return true; + function needsBuild({ + options + }, status, config) { + if (status.type !== 3 /* OutOfDateWithPrepend */ || options.force) return true; return config.fileNames.length === 0 || !!getConfigFileParsingDiagnostics(config).length || !isIncrementalCompilation(config.options); } function getNextInvalidatedProjectCreateInfo(state, buildOrder, reportQueue) { - if (!state.projectPendingBuild.size) - return void 0; - if (isCircularBuildOrder(buildOrder)) - return void 0; - const { options, projectPendingBuild } = state; + 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); @@ -127695,12 +113352,7 @@ ${lanes.join("\n")} reportAndStoreErrors(state, projectPath, getConfigFileParsingDiagnostics(config)); projectPendingBuild.delete(projectPath); if (options.verbose) { - reportStatus( - state, - status.upstreamProjectBlocked ? Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_was_not_built : Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, - project, - status.upstreamProjectName - ); + reportStatus(state, status.upstreamProjectBlocked ? Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_was_not_built : Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, project, status.upstreamProjectName); } continue; } @@ -127723,45 +113375,33 @@ ${lanes.join("\n")} } function createInvalidatedProjectWithInfo(state, info, buildOrder) { verboseReportProjectStatus(state, info.project, info.status); - return info.kind !== 2 /* UpdateOutputFileStamps */ ? createBuildOrUpdateInvalidedProject( - info.kind, - state, - info.project, - info.projectPath, - info.projectIndex, - info.config, - buildOrder - ) : createUpdateOutputFileStampsProject( - state, - info.project, - info.projectPath, - info.config, - buildOrder - ); + return info.kind !== 2 /* UpdateOutputFileStamps */ ? createBuildOrUpdateInvalidedProject(info.kind, state, info.project, info.projectPath, info.projectIndex, info.config, buildOrder) : createUpdateOutputFileStampsProject(state, info.project, info.projectPath, info.config, 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) { + function listEmittedFile({ + write + }, proj, file) { if (write && proj.options.listEmittedFiles) { write(`TSFILE: ${file}`); } } - function getOldProgram({ options, builderPrograms, compilerHost }, proj, parsed) { - if (options.force) - return void 0; + function getOldProgram({ + options, + builderPrograms, + compilerHost + }, proj, parsed) { + 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, config) { if (program) { - if (state.write) - listFiles(program, state.write); + if (state.write) listFiles(program, state.write); if (state.host.afterProgramEmitAndDiagnostics) { state.host.afterProgramEmitAndDiagnostics(program); } @@ -127774,12 +113414,21 @@ ${lanes.join("\n")} function buildErrors(state, resolvedPath, program, config, diagnostics, buildResult, errorType) { const canEmitBuildInfo = program && !outFile(program.getCompilerOptions()); reportAndStoreErrors(state, resolvedPath, diagnostics); - state.projectStatus.set(resolvedPath, { type: 0 /* Unbuildable */, reason: `${errorType} errors` }); - if (canEmitBuildInfo) - return { buildResult, step: 5 /* EmitBuildInfo */ }; + state.projectStatus.set(resolvedPath, { + type: 0 /* Unbuildable */, + reason: `${errorType} errors` + }); + if (canEmitBuildInfo) return { + buildResult, + step: 5 /* EmitBuildInfo */ + }; afterProgramDone(state, program, config); - return { buildResult, step: 7 /* QueueReferencingProjects */ }; + return { + buildResult, + step: 7 /* QueueReferencingProjects */ + }; } + function isFileWatcherWithModifiedTime(value) { return !!value.watcher; } @@ -127787,17 +113436,12 @@ ${lanes.join("\n")} 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; } @@ -127807,20 +113451,17 @@ ${lanes.join("\n")} if (existing && isFileWatcherWithModifiedTime(existing)) { existing.callbacks.push(callback); } else { - const watcher = state.watchFile( - file, - (fileName, eventKind, modifiedTime) => { - const existing2 = Debug.checkDefined(state.filesWatched.get(path)); - Debug.assert(isFileWatcherWithModifiedTime(existing2)); - existing2.modifiedTime = modifiedTime; - existing2.callbacks.forEach((cb) => cb(fileName, eventKind, modifiedTime)); - }, - pollingInterval, - options, - watchType, - project - ); - state.filesWatched.set(path, { callbacks: [callback], watcher, modifiedTime: existing }); + const watcher = state.watchFile(file, (fileName, eventKind, modifiedTime) => { + const existing2 = Debug.checkDefined(state.filesWatched.get(path)); + Debug.assert(isFileWatcherWithModifiedTime(existing2)); + existing2.modifiedTime = modifiedTime; + existing2.callbacks.forEach(cb => cb(fileName, eventKind, modifiedTime)); + }, pollingInterval, options, watchType, project); + state.filesWatched.set(path, { + callbacks: [callback], + watcher, + modifiedTime: existing + }); } return { close: () => { @@ -127836,11 +113477,9 @@ ${lanes.join("\n")} }; } 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) { @@ -127850,8 +113489,7 @@ ${lanes.join("\n")} 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), @@ -127874,7 +113512,11 @@ ${lanes.join("\n")} } const value = state.readFileWithCache(buildInfoPath); const buildInfo = value ? getBuildInfo(buildInfoPath, value) : void 0; - state.buildInfoCache.set(resolvedConfigPath, { path, buildInfo: buildInfo || false, modifiedTime: modifiedTime || missingFileModifiedTime }); + state.buildInfoCache.set(resolvedConfigPath, { + path, + buildInfo: buildInfo || false, + modifiedTime: modifiedTime || missingFileModifiedTime + }); return buildInfo; } function checkConfigFileUpToDateStatus(state, configFile, oldestOutputFileTime, oldestOutputFileName) { @@ -127894,10 +113536,13 @@ ${lanes.join("\n")} type: 16 /* ContainerOnly */ }; } + let referenceStatuses; const force = !!state.options.force; if (project.projectReferences) { - state.projectStatus.set(resolvedPath, { type: 13 /* ComputingUpstream */ }); + state.projectStatus.set(resolvedPath, { + type: 13 /* ComputingUpstream */ + }); for (const ref of project.projectReferences) { const resolvedRef = resolveProjectReferencePath(ref); const resolvedRefPath = toResolvedConfigFilePath(state, resolvedRef); @@ -127913,19 +113558,27 @@ ${lanes.join("\n")} upstreamProjectBlocked: refStatus.type === 12 /* UpstreamBlocked */ }; } + if (refStatus.type !== 1 /* UpToDate */) { return { type: 11 /* UpstreamOutOfDate */, 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: 17 /* ForceBuild */ }; - const { host } = state; + if (force) return { + type: 17 /* ForceBuild */ + }; + const { + host + } = state; const buildInfoPath = getTsBuildInfoEmitOutputFilePath(project.options); let oldestOutputFileName; let oldestOutputFileTime = maximumDate; @@ -127982,7 +113635,7 @@ ${lanes.join("\n")} let newestInputFileName = void 0; let newestInputFileTime = minimumDate; let pseudoInputUpToDate = false; - const seenRoots = /* @__PURE__ */ new Set(); + const seenRoots = /* @__PURE__ */new Set(); for (const inputFile of project.fileNames) { const inputTime = getModifiedTime2(state, inputFile); if (inputTime === missingFileModifiedTime) { @@ -127995,13 +113648,11 @@ ${lanes.join("\n")} let version2; let currentVersion; if (buildInfoProgram) { - if (!buildInfoVersionMap) - buildInfoVersionMap = getBuildInfoFileVersionMap(buildInfoProgram, buildInfoPath, host); + if (!buildInfoVersionMap) buildInfoVersionMap = getBuildInfoFileVersionMap(buildInfoProgram, buildInfoPath, host); version2 = buildInfoVersionMap.fileInfos.get(toPath2(state, inputFile)); const text = version2 ? state.readFileWithCache(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 { @@ -128015,12 +113666,10 @@ ${lanes.join("\n")} newestInputFileName = inputFile; newestInputFileTime = inputTime; } - if (buildInfoProgram) - seenRoots.add(toPath2(state, inputFile)); + if (buildInfoProgram) seenRoots.add(toPath2(state, inputFile)); } if (buildInfoProgram) { - if (!buildInfoVersionMap) - buildInfoVersionMap = getBuildInfoFileVersionMap(buildInfoProgram, buildInfoPath, host); + if (!buildInfoVersionMap) buildInfoVersionMap = getBuildInfoFileVersionMap(buildInfoProgram, buildInfoPath, host); for (const existingRoot of buildInfoVersionMap.roots) { if (!seenRoots.has(existingRoot)) { return { @@ -128065,7 +113714,12 @@ ${lanes.join("\n")} let usesPrepend = false; let upstreamChangedProject; if (referenceStatuses) { - for (const { ref, refStatus, resolvedConfig, resolvedRefPath } of referenceStatuses) { + for (const { + ref, + refStatus, + resolvedConfig, + resolvedRefPath + } of referenceStatuses) { usesPrepend = usesPrepend || !!ref.prepend; if (refStatus.newestInputFileTime && refStatus.newestInputFileTime <= oldestOutputFileTime) { continue; @@ -128092,17 +113746,11 @@ ${lanes.join("\n")} } } const configStatus = checkConfigFileUpToDateStatus(state, project.options.configFilePath, oldestOutputFileTime, oldestOutputFileName); - if (configStatus) - return configStatus; - const extendedConfigStatus = forEach(project.options.configFile.extendedSourceFiles || emptyArray, (configFile) => checkConfigFileUpToDateStatus(state, configFile, oldestOutputFileTime, oldestOutputFileName)); - if (extendedConfigStatus) - return extendedConfigStatus; - const dependentPackageFileStatus = forEach( - state.lastCachedPackageJsonLookups.get(resolvedPath) || emptyArray, - ([path]) => checkConfigFileUpToDateStatus(state, path, oldestOutputFileTime, oldestOutputFileName) - ); - if (dependentPackageFileStatus) - return dependentPackageFileStatus; + if (configStatus) return configStatus; + const extendedConfigStatus = forEach(project.options.configFile.extendedSourceFiles || emptyArray, configFile => checkConfigFileUpToDateStatus(state, configFile, oldestOutputFileTime, oldestOutputFileName)); + if (extendedConfigStatus) return extendedConfigStatus; + const dependentPackageFileStatus = forEach(state.lastCachedPackageJsonLookups.get(resolvedPath) || emptyArray, ([path]) => checkConfigFileUpToDateStatus(state, path, oldestOutputFileTime, oldestOutputFileName)); + if (dependentPackageFileStatus) return dependentPackageFileStatus; if (usesPrepend && pseudoUpToDate) { return { type: 3 /* OutOfDateWithPrepend */, @@ -128123,7 +113771,10 @@ ${lanes.join("\n")} } function getUpToDateStatus(state, project, resolvedPath) { if (project === void 0) { - return { type: 0 /* Unbuildable */, reason: "File deleted mid-build" }; + return { + type: 0 /* Unbuildable */, + reason: "File deleted mid-build" + }; } const prior = state.projectStatus.get(resolvedPath); if (prior !== void 0) { @@ -128137,30 +113788,29 @@ ${lanes.join("\n")} 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; } state.outputTimeStamps.delete(projectPath); return; } - const { host } = state; + const { + host + } = state; const outputs = getAllProjectOutputs(proj, !host.useCaseSensitiveFileNames()); const outputTimeStampMap = getOutputTimeStampMap(state, projectPath); - const modifiedOutputs = outputTimeStampMap ? /* @__PURE__ */ new Set() : void 0; + const modifiedOutputs = outputTimeStampMap ? /* @__PURE__ */new Set() : void 0; if (!skipOutputs || outputs.length !== skipOutputs.size) { 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); @@ -128173,16 +113823,13 @@ ${lanes.join("\n")} } } 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; @@ -128198,22 +113845,17 @@ ${lanes.join("\n")} }); } 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) { @@ -128228,6 +113870,7 @@ ${lanes.join("\n")} } else { status.type = 2 /* UpToDateWithUpstreamTypes */; } + break; } case 15 /* UpToDateWithInputFileText */: @@ -128262,25 +113905,23 @@ ${lanes.join("\n")} } 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); startWatching(state, buildOrder); - return isCircularBuildOrder(buildOrder) ? 4 /* ProjectReferenceCycle_OutputsSkipped */ : !buildOrder.some((p) => state.diagnostics.has(toResolvedConfigFilePath(state, p))) ? 0 /* Success */ : successfulProjects ? 2 /* DiagnosticsPresent_OutputsGenerated */ : 1 /* DiagnosticsPresent_OutputsSkipped */; + return isCircularBuildOrder(buildOrder) ? 4 /* ProjectReferenceCycle_OutputsSkipped */ : !buildOrder.some(p => state.diagnostics.has(toResolvedConfigFilePath(state, p))) ? 0 /* Success */ : successfulProjects ? 2 /* DiagnosticsPresent_OutputsGenerated */ : 1 /* DiagnosticsPresent_OutputsSkipped */; } + function clean(state, project, onlyReferences) { mark("SolutionBuilder::beforeClean"); const result = cleanWorker(state, project, onlyReferences); @@ -128290,13 +113931,16 @@ ${lanes.join("\n")} } 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 */; } - const { options, host } = state; + + const { + options, + host + } = state; const filesToDelete = options.dry ? [] : void 0; for (const proj of buildOrder) { const resolvedPath = toResolvedConfigFilePath(state, proj); @@ -128306,12 +113950,10 @@ ${lanes.join("\n")} continue; } const outputs = getAllProjectOutputs(parsed, !host.useCaseSensitiveFileNames()); - if (!outputs.length) - continue; - const inputFileNames = new Set(parsed.fileNames.map((f) => toPath2(state, f))); + 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); @@ -128322,16 +113964,19 @@ ${lanes.join("\n")} } } } + if (filesToDelete) { - reportStatus(state, Diagnostics.A_non_dry_build_would_delete_the_following_files_Colon_0, filesToDelete.map((f) => `\r + reportStatus(state, Diagnostics.A_non_dry_build_would_delete_the_following_files_Colon_0, filesToDelete.map(f => `\r * ${f}`).join("")); } return 0 /* Success */; } + function invalidateProject(state, resolved, updateLevel) { if (state.host.getParsedCommandLine && updateLevel === 1 /* RootNamesAndUpdate */) { updateLevel = 2 /* Full */; } + if (updateLevel === 2 /* Full */) { state.configFileCache.delete(resolved); state.buildOrder = void 0; @@ -128344,15 +113989,13 @@ ${lanes.join("\n")} function invalidateProjectAndScheduleBuilds(state, resolvedPath, updateLevel) { state.reportFileChangeDetected = true; invalidateProject(state, resolvedPath, updateLevel); - scheduleBuildInvalidatedProject( - state, - 250, - /*changeDetected*/ - true - ); + scheduleBuildInvalidatedProject(state, 250, /*changeDetected*/ + true); } function scheduleBuildInvalidatedProject(state, time, changeDetected) { - const { hostWithWatch } = state; + const { + hostWithWatch + } = state; if (!hostWithWatch.setTimeout || !hostWithWatch.clearTimeout) { return; } @@ -128366,8 +114009,7 @@ ${lanes.join("\n")} 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; @@ -128378,154 +114020,74 @@ ${lanes.join("\n")} } let projectsBuilt = 0; const buildOrder = getBuildOrder(state); - const invalidatedProject = getNextInvalidatedProject( - state, - buildOrder, - /*reportQueue*/ - false - ); + const invalidatedProject = getNextInvalidatedProject(state, buildOrder, /*reportQueue*/ + false); if (invalidatedProject) { invalidatedProject.done(); projectsBuilt++; while (state.projectPendingBuild.size) { - if (state.timerToBuildInvalidatedProject) - return; - const info = getNextInvalidatedProjectCreateInfo( - state, - buildOrder, - /*reportQueue*/ - false - ); - if (!info) - break; + if (state.timerToBuildInvalidatedProject) return; + const info = getNextInvalidatedProjectCreateInfo(state, buildOrder, /*reportQueue*/ + false); + if (!info) break; if (info.kind !== 2 /* UpdateOutputFileStamps */ && (changeDetected || projectsBuilt === 5)) { - scheduleBuildInvalidatedProject( - state, - 100, - /*changeDetected*/ - false - ); + scheduleBuildInvalidatedProject(state, 100, /*changeDetected*/ + false); return; } const project = createInvalidatedProjectWithInfo(state, info, buildOrder); project.done(); - if (info.kind !== 2 /* UpdateOutputFileStamps */) - projectsBuilt++; + if (info.kind !== 2 /* UpdateOutputFileStamps */) projectsBuilt++; } } disableCache(state); return buildOrder; } function watchConfigFile(state, resolved, resolvedPath, parsed) { - if (!state.watch || state.allWatchedConfigFiles.has(resolvedPath)) - return; - state.allWatchedConfigFiles.set( - resolvedPath, - watchFile( - state, - resolved, - () => invalidateProjectAndScheduleBuilds(state, resolvedPath, 2 /* Full */), - 2e3 /* High */, - parsed == null ? void 0 : parsed.watchOptions, - WatchType.ConfigFile, - resolved - ) - ); + if (!state.watch || state.allWatchedConfigFiles.has(resolvedPath)) return; + state.allWatchedConfigFiles.set(resolvedPath, watchFile(state, resolved, () => invalidateProjectAndScheduleBuilds(state, resolvedPath, 2 /* Full */), 2e3 /* High */, parsed == null ? void 0 : parsed.watchOptions, WatchType.ConfigFile, resolved)); } function watchExtendedConfigFiles(state, resolvedPath, parsed) { - updateSharedExtendedConfigFileWatcher( - resolvedPath, - parsed == null ? void 0 : parsed.options, - state.allWatchedExtendedConfigFiles, - (extendedConfigFileName, extendedConfigFilePath) => watchFile( - state, - extendedConfigFileName, - () => { - var _a; - return (_a = state.allWatchedExtendedConfigFiles.get(extendedConfigFilePath)) == null ? void 0 : _a.projects.forEach((projectConfigFilePath) => invalidateProjectAndScheduleBuilds(state, projectConfigFilePath, 2 /* Full */)); - }, - 2e3 /* High */, - parsed == null ? void 0 : parsed.watchOptions, - WatchType.ExtendedConfigFile - ), - (fileName) => toPath2(state, fileName) - ); + updateSharedExtendedConfigFileWatcher(resolvedPath, parsed == null ? void 0 : parsed.options, state.allWatchedExtendedConfigFiles, (extendedConfigFileName, extendedConfigFilePath) => watchFile(state, extendedConfigFileName, () => { + var _a; + return (_a = state.allWatchedExtendedConfigFiles.get(extendedConfigFilePath)) == null ? void 0 : _a.projects.forEach(projectConfigFilePath => invalidateProjectAndScheduleBuilds(state, projectConfigFilePath, 2 /* Full */)); + }, 2e3 /* High */, parsed == null ? void 0 : parsed.watchOptions, WatchType.ExtendedConfigFile), fileName => toPath2(state, fileName)); } function watchWildCardDirectories(state, resolved, resolvedPath, parsed) { - if (!state.watch) - return; - updateWatchingWildcardDirectories( - getOrCreateValueMapFromConfigFileMap(state.allWatchedWildcardDirectories, resolvedPath), - new Map(Object.entries(parsed.wildcardDirectories)), - (dir, flags) => state.watchDirectory( - dir, - (fileOrDirectory) => { - var _a; - if (isIgnoredFileFromWildCardWatching({ - watchedDirPath: toPath2(state, dir), - fileOrDirectory, - fileOrDirectoryPath: toPath2(state, fileOrDirectory), - configFileName: resolved, - currentDirectory: state.compilerHost.getCurrentDirectory(), - options: parsed.options, - program: state.builderPrograms.get(resolvedPath) || ((_a = getCachedParsedConfigFile(state, resolvedPath)) == null ? void 0 : _a.fileNames), - useCaseSensitiveFileNames: state.parseConfigFileHost.useCaseSensitiveFileNames, - writeLog: (s) => state.writeLog(s), - toPath: (fileName) => toPath2(state, fileName) - })) - return; - invalidateProjectAndScheduleBuilds(state, resolvedPath, 1 /* RootNamesAndUpdate */); - }, - flags, - parsed == null ? void 0 : parsed.watchOptions, - WatchType.WildcardDirectory, - resolved - ) - ); + if (!state.watch) return; + updateWatchingWildcardDirectories(getOrCreateValueMapFromConfigFileMap(state.allWatchedWildcardDirectories, resolvedPath), new Map(Object.entries(parsed.wildcardDirectories)), (dir, flags) => state.watchDirectory(dir, fileOrDirectory => { + var _a; + if (isIgnoredFileFromWildCardWatching({ + watchedDirPath: toPath2(state, dir), + fileOrDirectory, + fileOrDirectoryPath: toPath2(state, fileOrDirectory), + configFileName: resolved, + currentDirectory: state.compilerHost.getCurrentDirectory(), + options: parsed.options, + program: state.builderPrograms.get(resolvedPath) || ((_a = getCachedParsedConfigFile(state, resolvedPath)) == null ? void 0 : _a.fileNames), + useCaseSensitiveFileNames: state.parseConfigFileHost.useCaseSensitiveFileNames, + writeLog: s => state.writeLog(s), + toPath: fileName => toPath2(state, fileName) + })) return; + invalidateProjectAndScheduleBuilds(state, resolvedPath, 1 /* RootNamesAndUpdate */); + }, flags, parsed == null ? void 0 : parsed.watchOptions, WatchType.WildcardDirectory, resolved)); } function watchInputFiles(state, resolved, resolvedPath, parsed) { - if (!state.watch) - return; - mutateMap( - getOrCreateValueMapFromConfigFileMap(state.allWatchedInputFiles, resolvedPath), - arrayToMap(parsed.fileNames, (fileName) => toPath2(state, fileName)), - { - createNewValue: (_path, input) => watchFile( - state, - input, - () => invalidateProjectAndScheduleBuilds(state, resolvedPath, 0 /* Update */), - 250 /* Low */, - parsed == null ? void 0 : parsed.watchOptions, - WatchType.SourceFile, - resolved - ), - onDeleteValue: closeFileWatcher - } - ); + if (!state.watch) return; + mutateMap(getOrCreateValueMapFromConfigFileMap(state.allWatchedInputFiles, resolvedPath), arrayToMap(parsed.fileNames, fileName => toPath2(state, fileName)), { + createNewValue: (_path, input) => watchFile(state, input, () => invalidateProjectAndScheduleBuilds(state, resolvedPath, 0 /* Update */), 250 /* Low */, parsed == null ? void 0 : parsed.watchOptions, WatchType.SourceFile, resolved), + onDeleteValue: closeFileWatcher + }); } function watchPackageJsonFiles(state, resolved, resolvedPath, parsed) { - if (!state.watch || !state.lastCachedPackageJsonLookups) - return; - mutateMap( - getOrCreateValueMapFromConfigFileMap(state.allWatchedPackageJsonFiles, resolvedPath), - new Map(state.lastCachedPackageJsonLookups.get(resolvedPath)), - { - createNewValue: (path, _input) => watchFile( - state, - path, - () => invalidateProjectAndScheduleBuilds(state, resolvedPath, 0 /* Update */), - 2e3 /* High */, - parsed == null ? void 0 : parsed.watchOptions, - WatchType.PackageJson, - resolved - ), - onDeleteValue: closeFileWatcher - } - ); + if (!state.watch || !state.lastCachedPackageJsonLookups) return; + mutateMap(getOrCreateValueMapFromConfigFileMap(state.allWatchedPackageJsonFiles, resolvedPath), new Map(state.lastCachedPackageJsonLookups.get(resolvedPath)), { + createNewValue: (path, _input) => watchFile(state, path, () => invalidateProjectAndScheduleBuilds(state, resolvedPath, 0 /* Update */), 2e3 /* High */, parsed == null ? void 0 : parsed.watchOptions, WatchType.PackageJson, resolved), + onDeleteValue: closeFileWatcher + }); } function startWatching(state, buildOrder) { - if (!state.watchAllProjectsPending) - return; + if (!state.watchAllProjectsPending) return; mark("SolutionBuilder::beforeWatcherCreation"); state.watchAllProjectsPending = false; for (const resolved of getBuildOrderFromAnyBuildOrder(buildOrder)) { @@ -128545,41 +114107,26 @@ ${lanes.join("\n")} function stopWatching(state) { clearMap(state.allWatchedConfigFiles, closeFileWatcher); clearMap(state.allWatchedExtendedConfigFiles, closeFileWatcherOf); - clearMap(state.allWatchedWildcardDirectories, (watchedWildcardDirectories) => clearMap(watchedWildcardDirectories, closeFileWatcherOf)); - clearMap(state.allWatchedInputFiles, (watchedWildcardDirectories) => clearMap(watchedWildcardDirectories, closeFileWatcher)); - clearMap(state.allWatchedPackageJsonFiles, (watchedPacageJsonFiles) => clearMap(watchedPacageJsonFiles, closeFileWatcher)); + clearMap(state.allWatchedWildcardDirectories, watchedWildcardDirectories => clearMap(watchedWildcardDirectories, closeFileWatcherOf)); + clearMap(state.allWatchedInputFiles, watchedWildcardDirectories => clearMap(watchedWildcardDirectories, closeFileWatcher)); + clearMap(state.allWatchedPackageJsonFiles, watchedPacageJsonFiles => clearMap(watchedPacageJsonFiles, closeFileWatcher)); } function createSolutionBuilderWorker(watch, hostOrHostWithWatch, rootNames, options, baseWatchOptions) { const state = createSolutionBuilderState(watch, hostOrHostWithWatch, rootNames, options, baseWatchOptions); return { build: (project, cancellationToken, writeFile2, getCustomTransformers) => build(state, project, cancellationToken, writeFile2, getCustomTransformers), - clean: (project) => clean(state, project), - buildReferences: (project, cancellationToken, writeFile2, getCustomTransformers) => build( - state, - project, - cancellationToken, - writeFile2, - getCustomTransformers, - /*onlyReferences*/ - true - ), - cleanReferences: (project) => clean( - state, - project, - /*onlyReferences*/ - true - ), - getNextInvalidatedProject: (cancellationToken) => { + clean: project => clean(state, project), + buildReferences: (project, cancellationToken, writeFile2, getCustomTransformers) => build(state, project, cancellationToken, writeFile2, getCustomTransformers, /*onlyReferences*/ + true), + cleanReferences: project => clean(state, project, /*onlyReferences*/ + true), + getNextInvalidatedProject: cancellationToken => { setupInitialBuild(state, cancellationToken); - return getNextInvalidatedProject( - state, - getBuildOrder(state), - /*reportQueue*/ - false - ); + return getNextInvalidatedProject(state, getBuildOrder(state), /*reportQueue*/ + false); }, getBuildOrder: () => getBuildOrder(state), - getUpToDateStatusOfProject: (project) => { + getUpToDateStatusOfProject: project => { const configFileName = resolveProjectName(state, project); const configFilePath = toResolvedConfigFilePath(state, configFileName); return getUpToDateStatus(state, parseConfigFile(state, configFileName, configFilePath), configFilePath); @@ -128598,8 +114145,10 @@ ${lanes.join("\n")} var _a, _b; (_b = (_a = state.hostWithWatch).onWatchStatusChange) == null ? void 0 : _b.call(_a, createCompilerDiagnostic(message, ...args), state.host.getNewLine(), state.baseCompilerOptions); } - function reportErrors({ host }, errors) { - errors.forEach((err) => host.reportDiagnostic(err)); + function reportErrors({ + host + }, errors) { + errors.forEach(err => host.reportDiagnostic(err)); } function reportAndStoreErrors(state, proj, errors) { reportErrors(state, errors); @@ -128612,31 +114161,28 @@ ${lanes.join("\n")} 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; + const { + diagnostics + } = state; let totalErrors = 0; let filesInError = []; 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) => { + buildOrder.forEach(project => { const projectPath = toResolvedConfigFilePath(state, project); if (!state.projectErrorsReported.has(projectPath)) { 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); @@ -128646,128 +114192,46 @@ ${lanes.join("\n")} } function reportBuildQueue(state, buildQueue) { if (state.options.verbose) { - reportStatus(state, Diagnostics.Projects_in_this_build_Colon_0, buildQueue.map((s) => "\r\n * " + relName(state, s)).join("")); + reportStatus(state, Diagnostics.Projects_in_this_build_Colon_0, buildQueue.map(s => "\r\n * " + relName(state, s)).join("")); } } function reportUpToDateStatus(state, configFileName, status) { switch (status.type) { case 6 /* OutOfDateWithSelf */: - return reportStatus( - state, - Diagnostics.Project_0_is_out_of_date_because_output_1_is_older_than_input_2, - relName(state, configFileName), - relName(state, status.outOfDateOutputFileName), - relName(state, status.newerInputFileName) - ); + return reportStatus(state, Diagnostics.Project_0_is_out_of_date_because_output_1_is_older_than_input_2, relName(state, configFileName), relName(state, status.outOfDateOutputFileName), relName(state, status.newerInputFileName)); case 7 /* OutOfDateWithUpstream */: - return reportStatus( - state, - Diagnostics.Project_0_is_out_of_date_because_output_1_is_older_than_input_2, - relName(state, configFileName), - relName(state, status.outOfDateOutputFileName), - relName(state, status.newerProjectName) - ); + return reportStatus(state, Diagnostics.Project_0_is_out_of_date_because_output_1_is_older_than_input_2, relName(state, configFileName), relName(state, status.outOfDateOutputFileName), relName(state, status.newerProjectName)); case 4 /* OutputMissing */: - return reportStatus( - state, - Diagnostics.Project_0_is_out_of_date_because_output_file_1_does_not_exist, - relName(state, configFileName), - relName(state, status.missingOutputFileName) - ); + return reportStatus(state, Diagnostics.Project_0_is_out_of_date_because_output_file_1_does_not_exist, relName(state, configFileName), relName(state, status.missingOutputFileName)); case 5 /* ErrorReadingFile */: - return reportStatus( - state, - Diagnostics.Project_0_is_out_of_date_because_there_was_error_reading_file_1, - relName(state, configFileName), - relName(state, status.fileName) - ); + return reportStatus(state, Diagnostics.Project_0_is_out_of_date_because_there_was_error_reading_file_1, relName(state, configFileName), relName(state, status.fileName)); case 8 /* OutOfDateBuildInfo */: - return reportStatus( - state, - Diagnostics.Project_0_is_out_of_date_because_buildinfo_file_1_indicates_that_some_of_the_changes_were_not_emitted, - relName(state, configFileName), - relName(state, status.buildInfoFile) - ); + return reportStatus(state, Diagnostics.Project_0_is_out_of_date_because_buildinfo_file_1_indicates_that_some_of_the_changes_were_not_emitted, relName(state, configFileName), relName(state, status.buildInfoFile)); case 9 /* OutOfDateOptions */: - return reportStatus( - state, - Diagnostics.Project_0_is_out_of_date_because_buildinfo_file_1_indicates_there_is_change_in_compilerOptions, - relName(state, configFileName), - relName(state, status.buildInfoFile) - ); + return reportStatus(state, Diagnostics.Project_0_is_out_of_date_because_buildinfo_file_1_indicates_there_is_change_in_compilerOptions, relName(state, configFileName), relName(state, status.buildInfoFile)); case 10 /* OutOfDateRoots */: - return reportStatus( - state, - Diagnostics.Project_0_is_out_of_date_because_buildinfo_file_1_indicates_that_file_2_was_root_file_of_compilation_but_not_any_more, - relName(state, configFileName), - relName(state, status.buildInfoFile), - relName(state, status.inputFile) - ); + return reportStatus(state, Diagnostics.Project_0_is_out_of_date_because_buildinfo_file_1_indicates_that_file_2_was_root_file_of_compilation_but_not_any_more, relName(state, configFileName), relName(state, status.buildInfoFile), relName(state, status.inputFile)); case 1 /* UpToDate */: if (status.newestInputFileTime !== void 0) { - return reportStatus( - state, - Diagnostics.Project_0_is_up_to_date_because_newest_input_1_is_older_than_output_2, - relName(state, configFileName), - relName(state, status.newestInputFileName || ""), - relName(state, status.oldestOutputFileName || "") - ); + return reportStatus(state, Diagnostics.Project_0_is_up_to_date_because_newest_input_1_is_older_than_output_2, relName(state, configFileName), relName(state, status.newestInputFileName || ""), relName(state, status.oldestOutputFileName || "")); } break; case 3 /* OutOfDateWithPrepend */: - return reportStatus( - state, - Diagnostics.Project_0_is_out_of_date_because_output_of_its_dependency_1_has_changed, - relName(state, configFileName), - relName(state, status.newerProjectName) - ); + return reportStatus(state, Diagnostics.Project_0_is_out_of_date_because_output_of_its_dependency_1_has_changed, relName(state, configFileName), relName(state, status.newerProjectName)); case 2 /* UpToDateWithUpstreamTypes */: - return reportStatus( - state, - Diagnostics.Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies, - relName(state, configFileName) - ); + return reportStatus(state, Diagnostics.Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies, relName(state, configFileName)); case 15 /* UpToDateWithInputFileText */: - return reportStatus( - state, - Diagnostics.Project_0_is_up_to_date_but_needs_to_update_timestamps_of_output_files_that_are_older_than_input_files, - relName(state, configFileName) - ); + return reportStatus(state, Diagnostics.Project_0_is_up_to_date_but_needs_to_update_timestamps_of_output_files_that_are_older_than_input_files, relName(state, configFileName)); case 11 /* UpstreamOutOfDate */: - return reportStatus( - state, - Diagnostics.Project_0_is_out_of_date_because_its_dependency_1_is_out_of_date, - relName(state, configFileName), - relName(state, status.upstreamProjectName) - ); + return reportStatus(state, Diagnostics.Project_0_is_out_of_date_because_its_dependency_1_is_out_of_date, relName(state, configFileName), relName(state, status.upstreamProjectName)); case 12 /* UpstreamBlocked */: - return reportStatus( - state, - status.upstreamProjectBlocked ? Diagnostics.Project_0_can_t_be_built_because_its_dependency_1_was_not_built : Diagnostics.Project_0_can_t_be_built_because_its_dependency_1_has_errors, - relName(state, configFileName), - relName(state, status.upstreamProjectName) - ); + return reportStatus(state, status.upstreamProjectBlocked ? Diagnostics.Project_0_can_t_be_built_because_its_dependency_1_was_not_built : Diagnostics.Project_0_can_t_be_built_because_its_dependency_1_has_errors, relName(state, configFileName), relName(state, status.upstreamProjectName)); case 0 /* Unbuildable */: - return reportStatus( - state, - Diagnostics.Failed_to_parse_file_0_Colon_1, - relName(state, configFileName), - status.reason - ); + return reportStatus(state, Diagnostics.Failed_to_parse_file_0_Colon_1, relName(state, configFileName), status.reason); case 14 /* TsVersionOutputOfDate */: - return reportStatus( - state, - Diagnostics.Project_0_is_out_of_date_because_output_for_it_was_generated_with_version_1_that_differs_with_current_version_2, - relName(state, configFileName), - status.version, - version - ); + return reportStatus(state, Diagnostics.Project_0_is_out_of_date_because_output_for_it_was_generated_with_version_1_that_differs_with_current_version_2, relName(state, configFileName), status.version, version); case 17 /* ForceBuild */: - return reportStatus( - state, - Diagnostics.Project_0_is_being_forcibly_rebuilt, - relName(state, configFileName) - ); + return reportStatus(state, Diagnostics.Project_0_is_being_forcibly_rebuilt, relName(state, configFileName)); case 16 /* ContainerOnly */: case 13 /* ComputingUpstream */: break; @@ -128784,11 +114248,12 @@ ${lanes.join("\n")} var init_tsbuildPublic = __esm({ "src/compiler/tsbuildPublic.ts"() { "use strict"; + init_ts2(); init_ts_performance(); - minimumDate = /* @__PURE__ */ new Date(-864e13); - maximumDate = /* @__PURE__ */ new Date(864e13); - InvalidatedProjectKind = /* @__PURE__ */ ((InvalidatedProjectKind2) => { + minimumDate = /* @__PURE__ */new Date(-864e13); + maximumDate = /* @__PURE__ */new Date(864e13); + InvalidatedProjectKind = /* @__PURE__ */(InvalidatedProjectKind2 => { InvalidatedProjectKind2[InvalidatedProjectKind2["Build"] = 0] = "Build"; InvalidatedProjectKind2[InvalidatedProjectKind2["UpdateBundle"] = 1] = "UpdateBundle"; InvalidatedProjectKind2[InvalidatedProjectKind2["UpdateOutputFileStamps"] = 2] = "UpdateOutputFileStamps"; @@ -128801,6 +114266,7 @@ ${lanes.join("\n")} var init_ts2 = __esm({ "src/compiler/_namespaces/ts.ts"() { "use strict"; + init_corePublic(); init_core(); init_debug(); @@ -128886,7 +114352,7 @@ ${lanes.join("\n")} return index >= 0 && index < sys.args.length - 1 ? sys.args[index + 1] : void 0; } function nowString() { - const d = /* @__PURE__ */ new Date(); + const d = /* @__PURE__ */new Date(); return `${d.getHours().toString().padStart(2, "0")}:${d.getMinutes().toString().padStart(2, "0")}:${d.getSeconds().toString().padStart(2, "0")}.${d.getMilliseconds().toString().padStart(3, "0")}`; } function indent2(str) { @@ -128899,6 +114365,7 @@ ${lanes.join("\n")} var init_shared = __esm({ "src/jsTyping/shared.ts"() { "use strict"; + init_ts3(); ActionSet = "action::set"; ActionInvalidate = "action::invalidate"; @@ -128908,7 +114375,7 @@ ${lanes.join("\n")} EventEndInstallTypes = "event::endInstallTypes"; EventInitializationFailed = "event::initializationFailed"; ActionWatchTypingLocations = "action::watchTypingLocations"; - ((Arguments2) => { + (Arguments2 => { Arguments2.GlobalCacheLocation = "--globalTypingsCacheLocation"; Arguments2.LogFile = "--logFile"; Arguments2.EnableTelemetry = "--enableTelemetry"; @@ -128932,6 +114399,7 @@ ${lanes.join("\n")} var init_ts_server = __esm({ "src/jsTyping/_namespaces/ts.server.ts"() { "use strict"; + init_shared(); init_types2(); } @@ -128946,12 +114414,12 @@ ${lanes.join("\n")} return nodeCoreModules.has(moduleName) ? "node" : moduleName; } function loadSafeList(host, safeListPath) { - const result = readConfigFile(safeListPath, (path) => host.readFile(path)); + const result = readConfigFile(safeListPath, path => host.readFile(path)); return new Map(Object.entries(result.config)); } function loadTypesMap(host, typesMapPath) { var _a; - const result = readConfigFile(typesMapPath, (path) => host.readFile(path)); + const result = readConfigFile(typesMapPath, path => host.readFile(path)); if ((_a = result.config) == null ? void 0 : _a.simpleMap) { return new Map(Object.entries(result.config.simpleMap)); } @@ -128959,23 +114427,26 @@ ${lanes.join("\n")} } function discoverTypings(host, log, fileNames, projectRootPath, safeList, packageNameToTypingLocation, typeAcquisition, unresolvedImports, typesRegistry, compilerOptions) { if (!typeAcquisition || !typeAcquisition.enable) { - return { cachedTypingPaths: [], newTypingNames: [], filesToWatch: [] }; + return { + cachedTypingPaths: [], + newTypingNames: [], + filesToWatch: [] + }; } - const inferredTypings = /* @__PURE__ */ new Map(); - fileNames = mapDefined(fileNames, (fileName) => { + const inferredTypings = /* @__PURE__ */new Map(); + fileNames = mapDefined(fileNames, fileName => { const path = normalizePath(fileName); if (hasJSFileExtension(path)) { return path; } }); 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)); possibleSearchDirs.add(projectRootPath); - possibleSearchDirs.forEach((searchDir) => { + possibleSearchDirs.forEach(searchDir => { getTypingNames(searchDir, "bower.json", "bower_components", filesToWatch); getTypingNames(searchDir, "package.json", "node_modules", filesToWatch); }); @@ -128984,17 +114455,12 @@ ${lanes.join("\n")} getTypingNamesFromSourceFileNames(fileNames); } if (unresolvedImports) { - const module2 = deduplicate( - unresolvedImports.map(nonRelativeModuleNameForTypingCache), - equateStringsCaseSensitive, - compareStringsCaseSensitive - ); + const module2 = deduplicate(unresolvedImports.map(nonRelativeModuleNameForTypingCache), equateStringsCaseSensitive, compareStringsCaseSensitive); addInferredTypings(module2, "Inferred typings from unresolved imports"); } 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); @@ -129011,9 +114477,12 @@ ${lanes.join("\n")} newTypingNames.push(typing); } }); - const result = { cachedTypingPaths, newTypingNames, filesToWatch }; - if (log) - log(`Finished typings discovery:${stringifyIndented(result)}`); + const result = { + cachedTypingPaths, + newTypingNames, + filesToWatch + }; + if (log) log(`Finished typings discovery:${stringifyIndented(result)}`); return result; function addInferredTyping(typingName) { if (!inferredTypings.has(typingName)) { @@ -129021,8 +114490,7 @@ ${lanes.join("\n")} } } 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) { @@ -129031,7 +114499,7 @@ ${lanes.join("\n")} let manifestTypingNames; if (host.fileExists(manifestPath)) { filesToWatch2.push(manifestPath); - manifest = readConfigFile(manifestPath, (path) => host.readFile(path)).config; + manifest = readConfigFile(manifestPath, path => host.readFile(path)).config; manifestTypingNames = flatMap([manifest.dependencies, manifest.devDependencies, manifest.optionalDependencies, manifest.peerDependencies], getOwnKeys); addInferredTypings(manifestTypingNames, `Typing names in '${manifestPath}' dependencies`); } @@ -129041,29 +114509,23 @@ ${lanes.join("\n")} return; } const packageNames = []; - const dependencyManifestNames = manifestTypingNames ? manifestTypingNames.map((typingName) => combinePaths(packagesFolderPath, typingName, manifestName)) : host.readDirectory( - packagesFolderPath, - [".json" /* Json */], - /*excludes*/ - void 0, - /*includes*/ - void 0, - /*depth*/ - 3 - ).filter((manifestPath2) => { + const dependencyManifestNames = manifestTypingNames ? manifestTypingNames.map(typingName => combinePaths(packagesFolderPath, typingName, manifestName)) : host.readDirectory(packagesFolderPath, [".json" /* Json */], /*excludes*/ + void 0, /*includes*/ + void 0, /*depth*/ + 3).filter(manifestPath2 => { if (getBaseFileName(manifestPath2) !== manifestName) { return false; } const pathComponents2 = getPathComponents(normalizePath(manifestPath2)); const isScoped = pathComponents2[pathComponents2.length - 3][0] === "@"; - return isScoped && toFileNameLowerCase(pathComponents2[pathComponents2.length - 4]) === modulesDirName || // `node_modules/@foo/bar` + 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)); + const result2 = readConfigFile(normalizedFileName, path => host.readFile(path)); const manifest2 = result2.config; if (!manifest2.name) { continue; @@ -129072,12 +114534,10 @@ ${lanes.join("\n")} 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); @@ -129086,9 +114546,8 @@ ${lanes.join("\n")} addInferredTypings(packageNames, " Found package names"); } function getTypingNamesFromSourceFileNames(fileNames2) { - const fromFileNames = mapDefined(fileNames2, (j) => { - if (!hasJSFileExtension(j)) - return void 0; + const fromFileNames = mapDefined(fileNames2, j => { + if (!hasJSFileExtension(j)) return void 0; const inferredTypingName = removeFileExtension(toFileNameLowerCase(getBaseFileName(j))); const cleanedTypingName = removeMinAndVersionNumbers(inferredTypingName); return safeList.get(cleanedTypingName); @@ -129096,69 +114555,69 @@ ${lanes.join("\n")} if (fromFileNames.length) { addInferredTypings(fromFileNames, "Inferred typings from file names"); } - const hasJsxFile = some(fileNames2, (f) => fileExtensionIs(f, ".jsx" /* Jsx */)); + 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"); } } } function validatePackageName(packageName) { - return validatePackageNameWorker( - packageName, - /*supportScopedPackage*/ - true - ); + return validatePackageNameWorker(packageName, /*supportScopedPackage*/ + true); } function validatePackageNameWorker(packageName, supportScopedPackage) { if (!packageName) { return 1 /* EmptyName */; } + if (packageName.length > maxPackageNameLength) { return 2 /* NameTooLong */; } + if (packageName.charCodeAt(0) === 46 /* dot */) { return 3 /* NameStartsWithDot */; } + if (packageName.charCodeAt(0) === 95 /* _ */) { return 4 /* NameStartsWithUnderscore */; } + if (supportScopedPackage) { const matches = /^@([^/]+)\/([^/]+)$/.exec(packageName); if (matches) { - const scopeResult = validatePackageNameWorker( - matches[1], - /*supportScopedPackage*/ - false - ); + const scopeResult = validatePackageNameWorker(matches[1], /*supportScopedPackage*/ + false); if (scopeResult !== 0 /* Ok */) { - return { name: matches[1], isScopeName: true, result: scopeResult }; + return { + name: matches[1], + isScopeName: true, + result: scopeResult + }; } - const packageResult = validatePackageNameWorker( - matches[2], - /*supportScopedPackage*/ - false - ); + const packageResult = validatePackageNameWorker(matches[2], /*supportScopedPackage*/ + false); if (packageResult !== 0 /* Ok */) { - return { name: matches[2], isScopeName: false, result: packageResult }; + return { + name: matches[2], + isScopeName: false, + result: packageResult + }; } return 0 /* Ok */; } } + if (encodeURIComponent(packageName) !== packageName) { return 5 /* NameContainsNonURISafeCharacters */; } + return 0 /* Ok */; } + function renderPackageNameValidationFailure(result, typing) { - return typeof result === "object" ? renderPackageNameValidationFailureWorker(typing, result.result, result.name, result.isScopeName) : renderPackageNameValidationFailureWorker( - typing, - result, - typing, - /*isScopeName*/ - false - ); + return typeof result === "object" ? renderPackageNameValidationFailureWorker(typing, result.result, result.name, result.isScopeName) : renderPackageNameValidationFailureWorker(typing, result, typing, /*isScopeName*/ + false); } function renderPackageNameValidationFailureWorker(typing, result, name, isScopeName) { const kind = isScopeName ? "Scope" : "Package"; @@ -129183,61 +114642,14 @@ ${lanes.join("\n")} var init_jsTyping = __esm({ "src/jsTyping/jsTyping.ts"() { "use strict"; + init_ts3(); init_ts_server(); - unprefixedNodeCoreModuleList = [ - "assert", - "assert/strict", - "async_hooks", - "buffer", - "child_process", - "cluster", - "console", - "constants", - "crypto", - "dgram", - "diagnostics_channel", - "dns", - "dns/promises", - "domain", - "events", - "fs", - "fs/promises", - "http", - "https", - "http2", - "inspector", - "module", - "net", - "os", - "path", - "perf_hooks", - "process", - "punycode", - "querystring", - "readline", - "repl", - "stream", - "stream/promises", - "string_decoder", - "timers", - "timers/promises", - "tls", - "trace_events", - "tty", - "url", - "util", - "util/types", - "v8", - "vm", - "wasi", - "worker_threads", - "zlib" - ]; - prefixedNodeCoreModuleList = unprefixedNodeCoreModuleList.map((name) => `node:${name}`); + unprefixedNodeCoreModuleList = ["assert", "assert/strict", "async_hooks", "buffer", "child_process", "cluster", "console", "constants", "crypto", "dgram", "diagnostics_channel", "dns", "dns/promises", "domain", "events", "fs", "fs/promises", "http", "https", "http2", "inspector", "module", "net", "os", "path", "perf_hooks", "process", "punycode", "querystring", "readline", "repl", "stream", "stream/promises", "string_decoder", "timers", "timers/promises", "tls", "trace_events", "tty", "url", "util", "util/types", "v8", "vm", "wasi", "worker_threads", "zlib"]; + prefixedNodeCoreModuleList = unprefixedNodeCoreModuleList.map(name => `node:${name}`); nodeCoreModuleList = [...unprefixedNodeCoreModuleList, ...prefixedNodeCoreModuleList]; nodeCoreModules = new Set(nodeCoreModuleList); - NameValidationResult = /* @__PURE__ */ ((NameValidationResult2) => { + NameValidationResult = /* @__PURE__ */(NameValidationResult2 => { NameValidationResult2[NameValidationResult2["Ok"] = 0] = "Ok"; NameValidationResult2[NameValidationResult2["EmptyName"] = 1] = "EmptyName"; NameValidationResult2[NameValidationResult2["NameTooLong"] = 2] = "NameTooLong"; @@ -129268,6 +114680,7 @@ ${lanes.join("\n")} var init_ts_JsTyping = __esm({ "src/jsTyping/_namespaces/ts.JsTyping.ts"() { "use strict"; + init_jsTyping(); } }); @@ -129276,6 +114689,7 @@ ${lanes.join("\n")} var init_ts3 = __esm({ "src/jsTyping/_namespaces/ts.ts"() { "use strict"; + init_ts2(); init_ts_JsTyping(); init_ts_server(); @@ -129313,7 +114727,8 @@ ${lanes.join("\n")} var init_types3 = __esm({ "src/services/types.ts"() { "use strict"; - ((ScriptSnapshot2) => { + + (ScriptSnapshot2 => { class StringScriptSnapshot { constructor(text) { this.text = text; @@ -129333,7 +114748,7 @@ ${lanes.join("\n")} } ScriptSnapshot2.fromString = fromString; })(ScriptSnapshot || (ScriptSnapshot = {})); - PackageJsonDependencyGroup = /* @__PURE__ */ ((PackageJsonDependencyGroup2) => { + PackageJsonDependencyGroup = /* @__PURE__ */(PackageJsonDependencyGroup2 => { PackageJsonDependencyGroup2[PackageJsonDependencyGroup2["Dependencies"] = 1] = "Dependencies"; PackageJsonDependencyGroup2[PackageJsonDependencyGroup2["DevDependencies"] = 2] = "DevDependencies"; PackageJsonDependencyGroup2[PackageJsonDependencyGroup2["PeerDependencies"] = 4] = "PeerDependencies"; @@ -129341,63 +114756,63 @@ ${lanes.join("\n")} PackageJsonDependencyGroup2[PackageJsonDependencyGroup2["All"] = 15] = "All"; return PackageJsonDependencyGroup2; })(PackageJsonDependencyGroup || {}); - PackageJsonAutoImportPreference = /* @__PURE__ */ ((PackageJsonAutoImportPreference2) => { + PackageJsonAutoImportPreference = /* @__PURE__ */(PackageJsonAutoImportPreference2 => { PackageJsonAutoImportPreference2[PackageJsonAutoImportPreference2["Off"] = 0] = "Off"; PackageJsonAutoImportPreference2[PackageJsonAutoImportPreference2["On"] = 1] = "On"; PackageJsonAutoImportPreference2[PackageJsonAutoImportPreference2["Auto"] = 2] = "Auto"; return PackageJsonAutoImportPreference2; })(PackageJsonAutoImportPreference || {}); - LanguageServiceMode = /* @__PURE__ */ ((LanguageServiceMode2) => { + LanguageServiceMode = /* @__PURE__ */(LanguageServiceMode2 => { LanguageServiceMode2[LanguageServiceMode2["Semantic"] = 0] = "Semantic"; LanguageServiceMode2[LanguageServiceMode2["PartialSemantic"] = 1] = "PartialSemantic"; LanguageServiceMode2[LanguageServiceMode2["Syntactic"] = 2] = "Syntactic"; return LanguageServiceMode2; })(LanguageServiceMode || {}); emptyOptions = {}; - SemanticClassificationFormat = /* @__PURE__ */ ((SemanticClassificationFormat2) => { + SemanticClassificationFormat = /* @__PURE__ */(SemanticClassificationFormat2 => { SemanticClassificationFormat2["Original"] = "original"; SemanticClassificationFormat2["TwentyTwenty"] = "2020"; return SemanticClassificationFormat2; })(SemanticClassificationFormat || {}); - OrganizeImportsMode = /* @__PURE__ */ ((OrganizeImportsMode3) => { + OrganizeImportsMode = /* @__PURE__ */(OrganizeImportsMode3 => { OrganizeImportsMode3["All"] = "All"; OrganizeImportsMode3["SortAndCombine"] = "SortAndCombine"; OrganizeImportsMode3["RemoveUnused"] = "RemoveUnused"; return OrganizeImportsMode3; })(OrganizeImportsMode || {}); - CompletionTriggerKind = /* @__PURE__ */ ((CompletionTriggerKind4) => { + CompletionTriggerKind = /* @__PURE__ */(CompletionTriggerKind4 => { CompletionTriggerKind4[CompletionTriggerKind4["Invoked"] = 1] = "Invoked"; CompletionTriggerKind4[CompletionTriggerKind4["TriggerCharacter"] = 2] = "TriggerCharacter"; CompletionTriggerKind4[CompletionTriggerKind4["TriggerForIncompleteCompletions"] = 3] = "TriggerForIncompleteCompletions"; return CompletionTriggerKind4; })(CompletionTriggerKind || {}); - InlayHintKind = /* @__PURE__ */ ((InlayHintKind2) => { + InlayHintKind = /* @__PURE__ */(InlayHintKind2 => { InlayHintKind2["Type"] = "Type"; InlayHintKind2["Parameter"] = "Parameter"; InlayHintKind2["Enum"] = "Enum"; return InlayHintKind2; })(InlayHintKind || {}); - HighlightSpanKind = /* @__PURE__ */ ((HighlightSpanKind2) => { + HighlightSpanKind = /* @__PURE__ */(HighlightSpanKind2 => { HighlightSpanKind2["none"] = "none"; HighlightSpanKind2["definition"] = "definition"; HighlightSpanKind2["reference"] = "reference"; HighlightSpanKind2["writtenReference"] = "writtenReference"; return HighlightSpanKind2; })(HighlightSpanKind || {}); - IndentStyle = /* @__PURE__ */ ((IndentStyle3) => { + IndentStyle = /* @__PURE__ */(IndentStyle3 => { IndentStyle3[IndentStyle3["None"] = 0] = "None"; IndentStyle3[IndentStyle3["Block"] = 1] = "Block"; IndentStyle3[IndentStyle3["Smart"] = 2] = "Smart"; return IndentStyle3; })(IndentStyle || {}); - SemicolonPreference = /* @__PURE__ */ ((SemicolonPreference3) => { + SemicolonPreference = /* @__PURE__ */(SemicolonPreference3 => { SemicolonPreference3["Ignore"] = "ignore"; SemicolonPreference3["Insert"] = "insert"; SemicolonPreference3["Remove"] = "remove"; return SemicolonPreference3; })(SemicolonPreference || {}); testFormatSettings = getDefaultFormatCodeSettings("\n"); - SymbolDisplayPartKind = /* @__PURE__ */ ((SymbolDisplayPartKind2) => { + SymbolDisplayPartKind = /* @__PURE__ */(SymbolDisplayPartKind2 => { SymbolDisplayPartKind2[SymbolDisplayPartKind2["aliasName"] = 0] = "aliasName"; SymbolDisplayPartKind2[SymbolDisplayPartKind2["className"] = 1] = "className"; SymbolDisplayPartKind2[SymbolDisplayPartKind2["enumName"] = 2] = "enumName"; @@ -129425,7 +114840,7 @@ ${lanes.join("\n")} SymbolDisplayPartKind2[SymbolDisplayPartKind2["linkText"] = 24] = "linkText"; return SymbolDisplayPartKind2; })(SymbolDisplayPartKind || {}); - CompletionInfoFlags = /* @__PURE__ */ ((CompletionInfoFlags2) => { + CompletionInfoFlags = /* @__PURE__ */(CompletionInfoFlags2 => { CompletionInfoFlags2[CompletionInfoFlags2["None"] = 0] = "None"; CompletionInfoFlags2[CompletionInfoFlags2["MayIncludeAutoImports"] = 1] = "MayIncludeAutoImports"; CompletionInfoFlags2[CompletionInfoFlags2["IsImportStatementCompletion"] = 2] = "IsImportStatementCompletion"; @@ -129435,20 +114850,20 @@ ${lanes.join("\n")} CompletionInfoFlags2[CompletionInfoFlags2["MayIncludeMethodSnippets"] = 32] = "MayIncludeMethodSnippets"; return CompletionInfoFlags2; })(CompletionInfoFlags || {}); - OutliningSpanKind = /* @__PURE__ */ ((OutliningSpanKind2) => { + OutliningSpanKind = /* @__PURE__ */(OutliningSpanKind2 => { OutliningSpanKind2["Comment"] = "comment"; OutliningSpanKind2["Region"] = "region"; OutliningSpanKind2["Code"] = "code"; OutliningSpanKind2["Imports"] = "imports"; return OutliningSpanKind2; })(OutliningSpanKind || {}); - OutputFileType = /* @__PURE__ */ ((OutputFileType2) => { + OutputFileType = /* @__PURE__ */(OutputFileType2 => { OutputFileType2[OutputFileType2["JavaScript"] = 0] = "JavaScript"; OutputFileType2[OutputFileType2["SourceMap"] = 1] = "SourceMap"; OutputFileType2[OutputFileType2["Declaration"] = 2] = "Declaration"; return OutputFileType2; })(OutputFileType || {}); - EndOfLineState = /* @__PURE__ */ ((EndOfLineState2) => { + EndOfLineState = /* @__PURE__ */(EndOfLineState2 => { EndOfLineState2[EndOfLineState2["None"] = 0] = "None"; EndOfLineState2[EndOfLineState2["InMultiLineCommentTrivia"] = 1] = "InMultiLineCommentTrivia"; EndOfLineState2[EndOfLineState2["InSingleQuoteStringLiteral"] = 2] = "InSingleQuoteStringLiteral"; @@ -129458,7 +114873,7 @@ ${lanes.join("\n")} EndOfLineState2[EndOfLineState2["InTemplateSubstitutionPosition"] = 6] = "InTemplateSubstitutionPosition"; return EndOfLineState2; })(EndOfLineState || {}); - TokenClass = /* @__PURE__ */ ((TokenClass2) => { + TokenClass = /* @__PURE__ */(TokenClass2 => { TokenClass2[TokenClass2["Punctuation"] = 0] = "Punctuation"; TokenClass2[TokenClass2["Keyword"] = 1] = "Keyword"; TokenClass2[TokenClass2["Operator"] = 2] = "Operator"; @@ -129471,7 +114886,7 @@ ${lanes.join("\n")} TokenClass2[TokenClass2["RegExpLiteral"] = 9] = "RegExpLiteral"; return TokenClass2; })(TokenClass || {}); - ScriptElementKind = /* @__PURE__ */ ((ScriptElementKind2) => { + ScriptElementKind = /* @__PURE__ */(ScriptElementKind2 => { ScriptElementKind2["unknown"] = ""; ScriptElementKind2["warning"] = "warning"; ScriptElementKind2["keyword"] = "keyword"; @@ -129514,7 +114929,7 @@ ${lanes.join("\n")} ScriptElementKind2["linkText"] = "link text"; return ScriptElementKind2; })(ScriptElementKind || {}); - ScriptElementKindModifier = /* @__PURE__ */ ((ScriptElementKindModifier2) => { + ScriptElementKindModifier = /* @__PURE__ */(ScriptElementKindModifier2 => { ScriptElementKindModifier2["none"] = ""; ScriptElementKindModifier2["publicMemberModifier"] = "public"; ScriptElementKindModifier2["privateMemberModifier"] = "private"; @@ -129539,7 +114954,7 @@ ${lanes.join("\n")} ScriptElementKindModifier2["cjsModifier"] = ".cjs"; return ScriptElementKindModifier2; })(ScriptElementKindModifier || {}); - ClassificationTypeNames = /* @__PURE__ */ ((ClassificationTypeNames2) => { + ClassificationTypeNames = /* @__PURE__ */(ClassificationTypeNames2 => { ClassificationTypeNames2["comment"] = "comment"; ClassificationTypeNames2["identifier"] = "identifier"; ClassificationTypeNames2["keyword"] = "keyword"; @@ -129566,7 +114981,7 @@ ${lanes.join("\n")} ClassificationTypeNames2["jsxAttributeStringLiteralValue"] = "jsx attribute string literal value"; return ClassificationTypeNames2; })(ClassificationTypeNames || {}); - ClassificationType = /* @__PURE__ */ ((ClassificationType3) => { + ClassificationType = /* @__PURE__ */(ClassificationType3 => { ClassificationType3[ClassificationType3["comment"] = 1] = "comment"; ClassificationType3[ClassificationType3["identifier"] = 2] = "identifier"; ClassificationType3[ClassificationType3["keyword"] = 3] = "keyword"; @@ -129637,6 +115052,7 @@ ${lanes.join("\n")} } else { return 4 /* Namespace */; } + case 266 /* EnumDeclaration */: case 275 /* NamedImports */: case 276 /* ImportSpecifier */: @@ -129648,8 +115064,10 @@ ${lanes.join("\n")} case 312 /* SourceFile */: return 4 /* Namespace */ | 1 /* Value */; } + return 7 /* All */; } + function getMeaningFromLocation(node) { node = getAdjustedReferenceLocation(node); const parent2 = node.parent; @@ -129676,10 +115094,12 @@ ${lanes.join("\n")} return 1 /* Value */; } } + function getMeaningFromRightHandSideOfImportEquals(node) { const name = node.kind === 166 /* QualifiedName */ ? node : isQualifiedName(node.parent) && node.parent.right === node ? node.parent : void 0; return name && name.parent.kind === 271 /* ImportEqualsDeclaration */ ? 7 /* All */ : 4 /* Namespace */; } + function isInRightSideOfInternalImportEqualsDeclaration(node) { while (node.parent.kind === 166 /* QualifiedName */) { node = node.parent; @@ -129713,6 +115133,7 @@ ${lanes.join("\n")} const decl = root.parent.parent.parent; return decl.kind === 263 /* ClassDeclaration */ && root.parent.parent.token === 119 /* ImplementsKeyword */ || decl.kind === 264 /* InterfaceDeclaration */ && root.parent.parent.token === 96 /* ExtendsKeyword */; } + return false; } function isTypeReference(node) { @@ -129908,7 +115329,9 @@ ${lanes.join("\n")} case 173 /* MethodSignature */: return "method" /* memberFunctionElement */; case 303 /* PropertyAssignment */: - const { initializer } = node; + const { + initializer + } = node; return isFunctionLike(initializer) ? "method" /* memberFunctionElement */ : "property" /* memberVariableElement */; case 172 /* PropertyDeclaration */: case 171 /* PropertySignature */: @@ -129938,7 +115361,9 @@ ${lanes.join("\n")} return "alias" /* alias */; case 226 /* BinaryExpression */: const kind = getAssignmentDeclarationKind(node); - const { right } = node; + const { + right + } = node; switch (kind) { case 7 /* ObjectDefinePropertyValue */: case 8 /* ObjectDefinePropertyExports */: @@ -129957,11 +115382,13 @@ ${lanes.join("\n")} return isFunctionExpression(right) ? "method" /* memberFunctionElement */ : "property" /* memberVariableElement */; case 6 /* Prototype */: return "local class" /* localClassElement */; - default: { - assertType(kind); - return "" /* unknown */; - } + default: + { + assertType(kind); + return "" /* unknown */; + } } + case 80 /* Identifier */: return isImportClause(node.parent) ? "alias" /* alias */ : "" /* unknown */; case 277 /* ExportAssignment */: @@ -129970,10 +115397,12 @@ ${lanes.join("\n")} default: return "" /* unknown */; } + function getKindOfVariableDeclaration(v) { return isVarConst(v) ? "const" /* constElement */ : isLet(v) ? "let" /* letElement */ : "var" /* variableElement */; } } + function isThis(node) { switch (node.kind) { case 110 /* ThisKeyword */: @@ -130156,35 +115585,36 @@ ${lanes.join("\n")} return !!findChildOfKind(n, kind, sourceFile); } function findChildOfKind(n, kind, sourceFile) { - return find(n.getChildren(sourceFile), (c) => c.kind === kind); + return find(n.getChildren(sourceFile), c => c.kind === kind); } function findContainingList(node) { - const syntaxList = find(node.parent.getChildren(), (c) => isSyntaxList(c) && rangeContainsRange(c, node)); + const syntaxList = find(node.parent.getChildren(), c => isSyntaxList(c) && rangeContainsRange(c, node)); Debug.assert(!syntaxList || contains(syntaxList.getChildren(), node)); return syntaxList; } function isDefaultModifier2(node) { return node.kind === 90 /* DefaultKeyword */; } + function isClassKeyword(node) { return node.kind === 86 /* ClassKeyword */; } + function isFunctionKeyword(node) { return node.kind === 100 /* FunctionKeyword */; } + function getAdjustedLocationForClass(node) { if (isNamedDeclaration(node)) { return node.name; } 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) { @@ -130193,18 +115623,16 @@ ${lanes.join("\n")} } 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) { let lastTypeNode; - findAncestor(node, (a) => { + findAncestor(node, a => { if (isTypeNode(a)) { lastTypeNode = a; } @@ -130213,11 +115641,9 @@ ${lanes.join("\n")} 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); } @@ -130284,7 +115710,9 @@ ${lanes.join("\n")} } } function getAdjustedLocation(node, forRename) { - const { parent: parent2 } = node; + const { + parent: parent2 + } = node; if (isModifier(node) && (forRename || node.kind !== 90 /* DefaultKeyword */) ? canHaveModifiers(parent2) && contains(parent2.modifiers, node) : node.kind === 86 /* ClassKeyword */ ? isClassDeclaration(parent2) || isClassExpression(node) : node.kind === 100 /* FunctionKeyword */ ? isFunctionDeclaration(parent2) || isFunctionExpression(node) : node.kind === 120 /* InterfaceKeyword */ ? isInterfaceDeclaration(parent2) : node.kind === 94 /* EnumKeyword */ ? isEnumDeclaration(parent2) : node.kind === 156 /* TypeKeyword */ ? isTypeAliasDeclaration(parent2) : node.kind === 145 /* NamespaceKeyword */ || node.kind === 144 /* ModuleKeyword */ ? isModuleDeclaration(parent2) : node.kind === 102 /* ImportKeyword */ ? isImportEqualsDeclaration(parent2) : node.kind === 139 /* GetKeyword */ ? isGetAccessorDeclaration(parent2) : node.kind === 153 /* SetKeyword */ && isSetAccessorDeclaration(parent2)) { const location = getAdjustedLocationForDeclaration(parent2, forRename); if (location) { @@ -130387,96 +115815,78 @@ ${lanes.join("\n")} return node; } function getAdjustedReferenceLocation(node) { - return getAdjustedLocation( - node, - /*forRename*/ - false - ); + return getAdjustedLocation(node, /*forRename*/ + false); } function getAdjustedRenameLocation(node) { - return getAdjustedLocation( - node, - /*forRename*/ - true - ); + return getAdjustedLocation(node, /*forRename*/ + true); } function getTouchingPropertyName(sourceFile, position) { - return getTouchingToken(sourceFile, position, (n) => isPropertyNameLiteral(n) || isKeyword(n.kind) || isPrivateIdentifier(n)); + return getTouchingToken(sourceFile, position, n => isPropertyNameLiteral(n) || isKeyword(n.kind) || isPrivateIdentifier(n)); } function getTouchingToken(sourceFile, position, includePrecedingTokenAtEndPosition) { - return getTokenAtPositionWorker( - sourceFile, - position, - /*allowPositionInLeadingTrivia*/ - false, - includePrecedingTokenAtEndPosition, - /*includeEndPosition*/ - false - ); + return getTokenAtPositionWorker(sourceFile, position, /*allowPositionInLeadingTrivia*/ + false, includePrecedingTokenAtEndPosition, /*includeEndPosition*/ + false); } function getTokenAtPosition(sourceFile, position) { - return getTokenAtPositionWorker( - sourceFile, - position, - /*allowPositionInLeadingTrivia*/ - true, - /*includePrecedingTokenAtEndPosition*/ - void 0, - /*includeEndPosition*/ - false - ); + return getTokenAtPositionWorker(sourceFile, position, /*allowPositionInLeadingTrivia*/ + true, /*includePrecedingTokenAtEndPosition*/ + void 0, /*includeEndPosition*/ + false); } function getTokenAtPositionWorker(sourceFile, position, allowPositionInLeadingTrivia, includePrecedingTokenAtEndPosition, includeEndPosition) { let current = sourceFile; let foundToken; - outer: - while (true) { - const children = current.getChildren(sourceFile); - const i = binarySearchKey(children, position, (_, i2) => i2, (middle, _) => { - const end = children[middle].getEnd(); - if (end < position) { - return -1 /* LessThan */; - } - const start = allowPositionInLeadingTrivia ? children[middle].getFullStart() : children[middle].getStart( - sourceFile, - /*includeJsDocComment*/ - true - ); - if (start > position) { - return 1 /* GreaterThan */; - } - if (nodeContainsPosition(children[middle], start, end)) { - if (children[middle - 1]) { - if (nodeContainsPosition(children[middle - 1])) { - return 1 /* GreaterThan */; - } - } - return 0 /* EqualTo */; - } - if (includePrecedingTokenAtEndPosition && start === position && children[middle - 1] && children[middle - 1].getEnd() === position && nodeContainsPosition(children[middle - 1])) { - return 1 /* GreaterThan */; - } + outer: while (true) { + const children = current.getChildren(sourceFile); + const i = binarySearchKey(children, position, (_, i2) => i2, (middle, _) => { + const end = children[middle].getEnd(); + if (end < position) { return -1 /* LessThan */; - }); - if (foundToken) { - return foundToken; } - if (i >= 0 && children[i]) { - current = children[i]; - continue outer; + + const start = allowPositionInLeadingTrivia ? children[middle].getFullStart() : children[middle].getStart(sourceFile, /*includeJsDocComment*/ + true); + if (start > position) { + return 1 /* GreaterThan */; } - return current; + + if (nodeContainsPosition(children[middle], start, end)) { + if (children[middle - 1]) { + if (nodeContainsPosition(children[middle - 1])) { + return 1 /* GreaterThan */; + } + } + + return 0 /* EqualTo */; + } + + if (includePrecedingTokenAtEndPosition && start === position && children[middle - 1] && children[middle - 1].getEnd() === position && nodeContainsPosition(children[middle - 1])) { + return 1 /* GreaterThan */; + } + + return -1 /* LessThan */; + }); + + if (foundToken) { + return foundToken; } + if (i >= 0 && children[i]) { + current = children[i]; + continue outer; + } + return current; + } function nodeContainsPosition(node, start, end) { - end ?? (end = node.getEnd()); + var _end, _start2; + (_end = end) !== null && _end !== void 0 ? _end : end = node.getEnd(); if (end < position) { return false; } - start ?? (start = allowPositionInLeadingTrivia ? node.getFullStart() : node.getStart( - sourceFile, - /*includeJsDocComment*/ - true - )); + (_start2 = start) !== null && _start2 !== void 0 ? _start2 : start = allowPositionInLeadingTrivia ? node.getFullStart() : node.getStart(sourceFile, /*includeJsDocComment*/ + true); if (start > position) { return false; } @@ -130496,8 +115906,7 @@ ${lanes.join("\n")} 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; @@ -130515,12 +115924,12 @@ ${lanes.join("\n")} if (isToken(n) && n.pos === previousToken.end) { return n; } - return firstDefined(n.getChildren(sourceFile), (child) => { - const shouldDiveInChildNode = ( - // previous token is enclosed somewhere in the child - child.pos <= previousToken.pos && child.end > previousToken.end || // previous token ends exactly at the beginning of child - child.pos === previousToken.end - ); + return firstDefined(n.getChildren(sourceFile), child => { + const shouldDiveInChildNode = + // previous token is enclosed somewhere in the child + child.pos <= previousToken.pos && child.end > previousToken.end || + // previous token ends exactly at the beginning of child + child.pos === previousToken.end; return shouldDiveInChildNode && nodeHasTokens(child, sourceFile) ? find2(child) : void 0; }); } @@ -130539,28 +115948,24 @@ ${lanes.join("\n")} if (!children[middle - 1] || position >= children[middle - 1].end) { return 0 /* EqualTo */; } + return 1 /* GreaterThan */; } + return -1 /* LessThan */; }); + if (i >= 0 && children[i]) { const child = children[i]; if (position < child.end) { - const start = child.getStart( - sourceFile, - /*includeJsDoc*/ - !excludeJsdoc - ); - const lookInPreviousChild = start >= position || // cursor in the leading trivia + const start = child.getStart(sourceFile, /*includeJsDoc*/ + !excludeJsdoc); + const lookInPreviousChild = start >= position || + // cursor in the leading trivia !nodeHasTokens(child, sourceFile) || isWhiteSpaceOnlyJsxText(child); if (lookInPreviousChild) { - const candidate2 = findRightmostChildNodeWithTokens( - children, - /*exclusiveStartPosition*/ - i, - sourceFile, - n.kind - ); + const candidate2 = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ + i, sourceFile, n.kind); if (candidate2) { if (!excludeJsdoc && isJSDocCommentContainingNode(candidate2) && candidate2.getChildren(sourceFile).length) { return find2(candidate2); @@ -130574,13 +115979,8 @@ ${lanes.join("\n")} } } Debug.assert(startNode2 !== void 0 || n.kind === 312 /* SourceFile */ || n.kind === 1 /* EndOfFileToken */ || isJSDocCommentContainingNode(n)); - const candidate = findRightmostChildNodeWithTokens( - children, - /*exclusiveStartPosition*/ - children.length, - sourceFile, - n.kind - ); + const candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ + children.length, sourceFile, n.kind); return candidate && findRightmostToken(candidate, sourceFile); } } @@ -130595,13 +115995,8 @@ ${lanes.join("\n")} if (children.length === 0) { return n; } - const candidate = findRightmostChildNodeWithTokens( - children, - /*exclusiveStartPosition*/ - children.length, - sourceFile, - n.kind - ); + const candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ + children.length, sourceFile, n.kind); return candidate && findRightmostToken(candidate, sourceFile); } function findRightmostChildNodeWithTokens(children, exclusiveStartPosition, sourceFile, parentKind) { @@ -130677,8 +116072,7 @@ ${lanes.join("\n")} 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; @@ -130730,15 +116124,11 @@ ${lanes.join("\n")} function getPossibleGenericSignatures(called, typeArgumentCount, checker) { let type = checker.getTypeAtLocation(called); if (isOptionalChain(called.parent)) { - type = removeOptionality( - type, - isOptionalChainRoot(called.parent), - /*isOptionalChain*/ - true - ); + type = removeOptionality(type, isOptionalChainRoot(called.parent), /*isOptionalChain*/ + true); } const signatures = isNewExpression(called.parent) ? type.getConstructSignatures() : type.getCallSignatures(); - return signatures.filter((candidate) => !!candidate.typeParameters && candidate.typeParameters.length >= typeArgumentCount); + return signatures.filter(candidate => !!candidate.typeParameters && candidate.typeParameters.length >= typeArgumentCount); } function getPossibleTypeArgumentsInfo(tokenIn, sourceFile) { if (sourceFile.text.lastIndexOf("<", tokenIn ? tokenIn.pos : sourceFile.text.length) === -1) { @@ -130754,10 +116144,12 @@ ${lanes.join("\n")} 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 }; + return isDeclarationName(token) ? void 0 : { + called: token, + nTypeArguments + }; } remainingLessThanTokens--; break; @@ -130772,18 +116164,15 @@ ${lanes.join("\n")} 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++; @@ -130814,13 +116203,8 @@ ${lanes.join("\n")} return void 0; } function isInComment(sourceFile, position, tokenAtPosition) { - return ts_formatting_exports.getRangeOfEnclosingComment( - sourceFile, - position, - /*precedingToken*/ - void 0, - tokenAtPosition - ); + return ts_formatting_exports.getRangeOfEnclosingComment(sourceFile, position, /*precedingToken*/ + void 0, tokenAtPosition); } function hasDocComment(sourceFile, position) { const token = getTokenAtPosition(sourceFile, position); @@ -130832,26 +116216,18 @@ ${lanes.join("\n")} 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) { if (node.kind === 183 /* TypeReference */ || node.kind === 213 /* CallExpression */) { return node.typeArguments; @@ -130864,6 +116240,7 @@ ${lanes.join("\n")} function isComment(kind) { return kind === 2 /* SingleLineCommentTrivia */ || kind === 3 /* MultiLineCommentTrivia */; } + function isStringOrRegularExpressionOrTemplateLiteral(kind) { if (kind === 11 /* StringLiteral */ || kind === 14 /* RegularExpressionLiteral */ || isTemplateLiteralKind(kind)) { return true; @@ -130877,11 +116254,14 @@ ${lanes.join("\n")} if (!type.isIntersection()) { return false; } - const { types, checker } = type; + const { + types, + checker + } = type; return types.length === 2 && (areIntersectedTypesAvoidingStringReduction(checker, types[0], types[1]) || areIntersectedTypesAvoidingStringReduction(checker, types[1], types[0])); } function isInsideTemplateLiteral(node, position, sourceFile) { - return isTemplateLiteralKind(node.kind) && (node.getStart(sourceFile) < position && position < node.end) || !!node.isUnterminated && position === node.end; + return isTemplateLiteralKind(node.kind) && node.getStart(sourceFile) < position && position < node.end || !!node.isUnterminated && position === node.end; } function isAccessibilityModifier(kind) { switch (kind) { @@ -130912,33 +116292,20 @@ ${lanes.join("\n")} return false; } function isInReferenceComment(sourceFile, position) { - return isInReferenceCommentWorker( - sourceFile, - position, - /*shouldBeReference*/ - true - ); + return isInReferenceCommentWorker(sourceFile, position, /*shouldBeReference*/ + true); } function isInNonReferenceComment(sourceFile, position) { - return isInReferenceCommentWorker( - sourceFile, - position, - /*shouldBeReference*/ - false - ); + return isInReferenceCommentWorker(sourceFile, position, /*shouldBeReference*/ + false); } function isInReferenceCommentWorker(sourceFile, position, shouldBeReference) { - const range = isInComment( - sourceFile, - position, - /*tokenAtPosition*/ - void 0 - ); + const range = isInComment(sourceFile, position, /*tokenAtPosition*/ + void 0); 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 */: @@ -130951,8 +116318,7 @@ ${lanes.join("\n")} return createTextSpanFromBounds(node.getStart(sourceFile), (endNode2 || node).getEnd()); } function createTextSpanFromStringLiteralLikeContent(node) { - if (node.isUnterminated) - return void 0; + if (node.isUnterminated) return void 0; return createTextSpanFromBounds(node.getStart() + 1, node.getEnd() - 1); } function createTextRangeFromNode(node, sourceFile) { @@ -130968,7 +116334,10 @@ ${lanes.join("\n")} return createTextChange(createTextSpan(start, length2), newText); } function createTextChange(span, newText) { - return { span, newText }; + return { + span, + newText + }; } function isTypeKeyword(kind) { return contains(typeKeywords, kind); @@ -130976,15 +116345,17 @@ ${lanes.join("\n")} function isTypeKeywordToken(node) { return node.kind === 156 /* TypeKeyword */; } + function isTypeKeywordTokenOrIdentifier(node) { return isTypeKeywordToken(node) || isIdentifier(node) && node.text === "type"; } function isExternalModuleSymbol(moduleSymbol) { return !!(moduleSymbol.flags & 1536 /* Module */) && moduleSymbol.name.charCodeAt(0) === 34 /* doubleQuote */; } + function nodeSeenTracker() { const seen = []; - return (node) => { + return node => { const id = getNodeId(node); return !seen[id] && (seen[id] = true); }; @@ -131006,17 +116377,17 @@ ${lanes.join("\n")} return name.kind === 167 /* ComputedPropertyName */ ? isStringOrNumericLiteralLike(name.expression) ? name.expression.text : void 0 : isPrivateIdentifier(name) ? idText(name) : getTextOfIdentifierOrLiteral(name); } function programContainsModules(program) { - return program.getSourceFiles().some((s) => !s.isDeclarationFile && !program.isSourceFileFromExternalLibrary(s) && !!(s.externalModuleIndicator || s.commonJsModuleIndicator)); + return program.getSourceFiles().some(s => !s.isDeclarationFile && !program.isSourceFileFromExternalLibrary(s) && !!(s.externalModuleIndicator || s.commonJsModuleIndicator)); } function programContainsEsModules(program) { - return program.getSourceFiles().some((s) => !s.isDeclarationFile && !program.isSourceFileFromExternalLibrary(s) && !!s.externalModuleIndicator); + return program.getSourceFiles().some(s => !s.isDeclarationFile && !program.isSourceFileFromExternalLibrary(s) && !!s.externalModuleIndicator); } function compilerOptionsIndicateEsModules(compilerOptions) { return !!compilerOptions.module || getEmitScriptTarget(compilerOptions) >= 2 /* ES2015 */ || !!compilerOptions.noEmit; } function createModuleSpecifierResolutionHost(program, host) { return { - fileExists: (fileName) => program.fileExists(fileName), + fileExists: fileName => program.fileExists(fileName), getCurrentDirectory: () => host.getCurrentDirectory(), readFile: maybeBind(host, host.readFile), useCaseSensitiveFileNames: maybeBind(host, host.useCaseSensitiveFileNames), @@ -131028,8 +116399,8 @@ ${lanes.join("\n")} }, getGlobalTypingsCacheLocation: maybeBind(host, host.getGlobalTypingsCacheLocation), redirectTargetsMap: program.redirectTargetsMap, - getProjectReferenceRedirect: (fileName) => program.getProjectReferenceRedirect(fileName), - isSourceOfProjectReferenceRedirect: (fileName) => program.isSourceOfProjectReferenceRedirect(fileName), + getProjectReferenceRedirect: fileName => program.getProjectReferenceRedirect(fileName), + isSourceOfProjectReferenceRedirect: fileName => program.isSourceOfProjectReferenceRedirect(fileName), getNearestAncestorDirectoryWithPackageJson: maybeBind(host, host.getNearestAncestorDirectoryWithPackageJson), getFileIncludeReasons: () => program.getFileIncludeReasons() }; @@ -131043,33 +116414,32 @@ ${lanes.join("\n")} 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*/ - void 0, - defaultImport || namedImports ? factory.createImportClause(!!isTypeOnly, defaultImport, namedImports && namedImports.length ? factory.createNamedImports(namedImports) : void 0) : void 0, - typeof moduleSpecifier === "string" ? makeStringLiteral(moduleSpecifier, quotePreference) : moduleSpecifier, - /*attributes*/ - void 0 - ); + return factory.createImportDeclaration( /*modifiers*/ + void 0, defaultImport || namedImports ? factory.createImportClause(!!isTypeOnly, defaultImport, namedImports && namedImports.length ? factory.createNamedImports(namedImports) : void 0) : void 0, typeof moduleSpecifier === "string" ? makeStringLiteral(moduleSpecifier, quotePreference) : moduleSpecifier, /*attributes*/ + void 0); } function makeStringLiteral(text, quotePreference) { return factory.createStringLiteral(text, quotePreference === 0 /* Single */); } + function quotePreferenceFromString(str, sourceFile) { return isStringDoubleQuoted(str, sourceFile) ? 1 /* Double */ : 0 /* Single */; } + function getQuotePreference(sourceFile, preferences) { if (preferences.quotePreference && preferences.quotePreference !== "auto") { return preferences.quotePreference === "single" ? 0 /* Single */ : 1 /* Double */; } else { - const firstModuleSpecifier = sourceFile.imports && find(sourceFile.imports, (n) => isStringLiteral(n) && !nodeIsSynthesized(n.parent)); + const firstModuleSpecifier = sourceFile.imports && find(sourceFile.imports, n => isStringLiteral(n) && !nodeIsSynthesized(n.parent)); return firstModuleSpecifier ? quotePreferenceFromString(firstModuleSpecifier, sourceFile) : 1 /* Double */; } } + function getQuoteFromPreference(qp) { switch (qp) { case 0 /* Single */: @@ -131088,17 +116458,14 @@ ${lanes.join("\n")} if (symbol.escapedName !== "default" /* Default */) { return symbol.escapedName; } - return firstDefined(symbol.declarations, (decl) => { + return firstDefined(symbol.declarations, decl => { const name = getNameOfDeclaration(decl); return name && name.kind === 80 /* Identifier */ ? name.escapedText : void 0; }); } function isModuleSpecifierLike(node) { - return isStringLiteralLike(node) && (isExternalModuleReference(node.parent) || isImportDeclaration(node.parent) || isRequireCall( - node.parent, - /*requireStringLiteralLikeArgument*/ - false - ) && node.parent.arguments[0] === node || isImportCall(node.parent) && node.parent.arguments[0] === node); + return isStringLiteralLike(node) && (isExternalModuleReference(node.parent) || isImportDeclaration(node.parent) || isRequireCall(node.parent, /*requireStringLiteralLikeArgument*/ + false) && node.parent.arguments[0] === node || isImportCall(node.parent) && node.parent.arguments[0] === node); } function isObjectBindingElementWithoutPropertyName(bindingElement) { return isBindingElement(bindingElement) && isObjectBindingPattern(bindingElement.parent) && isIdentifier(bindingElement.name) && !bindingElement.propertyName; @@ -131108,8 +116475,7 @@ ${lanes.join("\n")} 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; @@ -131121,7 +116487,7 @@ ${lanes.join("\n")} return textSpanContainsPosition(span, node.getStart(file)) && node.getEnd() <= textSpanEnd(span); } function findModifier(node, kind) { - return canHaveModifiers(node) ? find(node.modifiers, (m) => m.kind === kind) : void 0; + return canHaveModifiers(node) ? find(node.modifiers, m => m.kind === kind) : void 0; } function insertImports(changes, sourceFile, imports, blankLineBetween, preferences) { const decl = isArray(imports) ? imports[0] : imports; @@ -131137,15 +116503,11 @@ ${lanes.join("\n")} for (const newImport of sortedNewImports) { const insertionIndex = ts_OrganizeImports_exports.getImportDeclarationInsertionIndex(existingImportStatements, newImport, comparer2); if (insertionIndex === 0) { - const options = existingImportStatements[0] === sourceFile.statements[0] ? { leadingTriviaOption: ts_textChanges_exports.LeadingTriviaOption.Exclude } : {}; - changes.insertNodeBefore( - sourceFile, - existingImportStatements[0], - newImport, - /*blankLineBetween*/ - false, - options - ); + const options = existingImportStatements[0] === sourceFile.statements[0] ? { + leadingTriviaOption: ts_textChanges_exports.LeadingTriviaOption.Exclude + } : {}; + changes.insertNodeBefore(sourceFile, existingImportStatements[0], newImport, /*blankLineBetween*/ + false, options); } else { const prevImport = existingImportStatements[insertionIndex - 1]; changes.insertNodeAfter(sourceFile, prevImport, newImport); @@ -131196,11 +116558,19 @@ ${lanes.join("\n")} return mapsTo && (!fileExists || fileExists(normalizePath(mapsTo.fileName)) ? mapsTo : void 0); } function getMappedDocumentSpan(documentSpan, sourceMapper, fileExists) { - const { fileName, textSpan } = documentSpan; - const newPosition = getMappedLocation({ fileName, pos: textSpan.start }, sourceMapper, fileExists); - if (!newPosition) - return void 0; - const newEndPosition = getMappedLocation({ fileName, pos: textSpan.start + textSpan.length }, sourceMapper, fileExists); + const { + fileName, + textSpan + } = documentSpan; + const newPosition = getMappedLocation({ + fileName, + pos: textSpan.start + }, sourceMapper, fileExists); + 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 { fileName: newPosition.fileName, @@ -131215,21 +116585,22 @@ ${lanes.join("\n")} }; } function getMappedContextSpan(documentSpan, sourceMapper, fileExists) { - const contextSpanStart = documentSpan.contextSpan && getMappedLocation( - { fileName: documentSpan.fileName, pos: documentSpan.contextSpan.start }, - sourceMapper, - fileExists - ); - const contextSpanEnd = documentSpan.contextSpan && getMappedLocation( - { fileName: documentSpan.fileName, pos: documentSpan.contextSpan.start + documentSpan.contextSpan.length }, - sourceMapper, - fileExists - ); - return contextSpanStart && contextSpanEnd ? { start: contextSpanStart.pos, length: contextSpanEnd.pos - contextSpanStart.pos } : void 0; + const contextSpanStart = documentSpan.contextSpan && getMappedLocation({ + fileName: documentSpan.fileName, + pos: documentSpan.contextSpan.start + }, sourceMapper, fileExists); + const contextSpanEnd = documentSpan.contextSpan && getMappedLocation({ + fileName: documentSpan.fileName, + pos: documentSpan.contextSpan.start + documentSpan.contextSpan.length + }, sourceMapper, fileExists); + return contextSpanStart && contextSpanEnd ? { + start: contextSpanStart.pos, + length: contextSpanEnd.pos - contextSpanStart.pos + } : void 0; } function isFirstDeclarationOfSymbolParameter(symbol) { const declaration = symbol.declarations ? firstOrUndefined(symbol.declarations) : void 0; - return !!findAncestor(declaration, (n) => isParameter(n) ? true : isBindingElement(n) || isObjectBindingPattern(n) || isArrayBindingPattern(n) ? false : "quit"); + return !!findAncestor(declaration, n => isParameter(n) ? true : isBindingElement(n) || isObjectBindingPattern(n) || isArrayBindingPattern(n) ? false : "quit"); } function getDisplayPartWriter() { const absoluteMaximumLength = defaultMaximumTruncationLength * 10; @@ -131238,7 +116609,7 @@ ${lanes.join("\n")} let indent3; let length2; resetWriter(); - const unknownWrite = (text) => writeKind(text, 17 /* text */); + const unknownWrite = text => writeKind(text, 17 /* text */); return { displayParts: () => { const finalText = displayParts.length && displayParts[displayParts.length - 1].text; @@ -131246,19 +116617,21 @@ ${lanes.join("\n")} if (!isWhiteSpaceLike(finalText.charCodeAt(finalText.length - 1))) { displayParts.push(displayPart(" ", 16 /* space */)); } + displayParts.push(displayPart("...", 15 /* punctuation */)); } + return displayParts; }, - writeKeyword: (text) => writeKind(text, 5 /* keyword */), - writeOperator: (text) => writeKind(text, 12 /* operator */), - writePunctuation: (text) => writeKind(text, 15 /* punctuation */), - writeTrailingSemicolon: (text) => writeKind(text, 15 /* punctuation */), - writeSpace: (text) => writeKind(text, 16 /* space */), - writeStringLiteral: (text) => writeKind(text, 8 /* stringLiteral */), - writeParameter: (text) => writeKind(text, 13 /* parameterName */), - writeProperty: (text) => writeKind(text, 14 /* propertyName */), - writeLiteral: (text) => writeKind(text, 8 /* stringLiteral */), + writeKeyword: text => writeKind(text, 5 /* keyword */), + writeOperator: text => writeKind(text, 12 /* operator */), + writePunctuation: text => writeKind(text, 15 /* punctuation */), + writeTrailingSemicolon: text => writeKind(text, 15 /* punctuation */), + writeSpace: text => writeKind(text, 16 /* space */), + writeStringLiteral: text => writeKind(text, 8 /* stringLiteral */), + writeParameter: text => writeKind(text, 13 /* parameterName */), + writeProperty: text => writeKind(text, 14 /* propertyName */), + writeLiteral: text => writeKind(text, 8 /* stringLiteral */), writeSymbol, writeLine, write: unknownWrite, @@ -131281,34 +116654,31 @@ ${lanes.join("\n")} clear: resetWriter }; function writeIndent() { - if (length2 > absoluteMaximumLength) - return; + if (length2 > absoluteMaximumLength) return; if (lineStart) { const indentString = getIndentString(indent3); if (indentString) { length2 += indentString.length; displayParts.push(displayPart(indentString, 16 /* space */)); } + lineStart = false; } } 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; @@ -131327,56 +116697,54 @@ ${lanes.join("\n")} 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 */; } } + function displayPart(text, kind) { - return { text, kind: SymbolDisplayPartKind[kind] }; + return { + text, + kind: SymbolDisplayPartKind[kind] + }; } function spacePart() { return displayPart(" ", 16 /* space */); } + function keywordPart(kind) { return displayPart(tokenToString(kind), 5 /* keyword */); } + function punctuationPart(kind) { return displayPart(tokenToString(kind), 15 /* punctuation */); } + function operatorPart(kind) { return displayPart(tokenToString(kind), 12 /* operator */); } + function parameterNamePart(text) { return displayPart(text, 13 /* parameterName */); } + function propertyNamePart(text) { return displayPart(text, 14 /* propertyName */); } + function textOrKeywordPart(text) { const kind = stringToToken(text); return kind === void 0 ? textPart(text) : keywordPart(kind); @@ -131384,15 +116752,19 @@ ${lanes.join("\n")} function textPart(text) { return displayPart(text, 17 /* text */); } + function typeAliasNamePart(text) { return displayPart(text, 0 /* aliasName */); } + function typeParameterNamePart(text) { return displayPart(text, 18 /* typeParameterName */); } + function linkTextPart(text) { return displayPart(text, 24 /* linkText */); } + function linkNamePart(text, target) { return { text, @@ -131406,6 +116778,7 @@ ${lanes.join("\n")} function linkPart(text) { return displayPart(text, 22 /* link */); } + function buildLinkParts(link, checker) { var _a; const prefix = isJSDocLink(link) ? "link" : isJSDocLinkCode(link) ? "linkcode" : "linkplain"; @@ -131422,8 +116795,7 @@ ${lanes.join("\n")} const decl = (symbol == null ? void 0 : symbol.valueDeclaration) || ((_a = symbol == null ? void 0 : symbol.declarations) == null ? void 0 : _a[0]); if (decl) { parts.push(linkNamePart(name, decl)); - if (text) - parts.push(linkTextPart(text)); + if (text) parts.push(linkTextPart(text)); } else { parts.push(linkTextPart(name + (suffix ? "" : " ") + text)); } @@ -131434,8 +116806,7 @@ ${lanes.join("\n")} 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; @@ -131443,23 +116814,18 @@ ${lanes.join("\n")} 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; @@ -131471,6 +116837,7 @@ ${lanes.join("\n")} function lineBreakPart() { return displayPart("\n", 6 /* lineBreak */); } + function mapToDisplayParts(writeDisplayParts) { try { writeDisplayParts(displayPartWriter); @@ -131480,31 +116847,25 @@ ${lanes.join("\n")} } } function typeToDisplayParts(typechecker, type, enclosingDeclaration, flags = 0 /* None */) { - return mapToDisplayParts((writer) => { + return mapToDisplayParts(writer => { typechecker.writeType(type, enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */ | 16384 /* UseAliasDefinedOutsideCurrentScope */, writer); }); } function symbolToDisplayParts(typeChecker, symbol, enclosingDeclaration, meaning, flags = 0 /* None */) { - return mapToDisplayParts((writer) => { + return mapToDisplayParts(writer => { typeChecker.writeSymbol(symbol, enclosingDeclaration, meaning, flags | 8 /* UseAliasDefinedOutsideCurrentScope */, writer); }); } function signatureToDisplayParts(typechecker, signature, enclosingDeclaration, flags = 0 /* None */) { flags |= 16384 /* UseAliasDefinedOutsideCurrentScope */ | 1024 /* MultilineObjectLiterals */ | 32 /* WriteTypeArgumentsOfSignature */ | 8192 /* OmitParameterModifiers */; - return mapToDisplayParts((writer) => { - typechecker.writeSignature( - signature, - enclosingDeclaration, - flags, - /*kind*/ - void 0, - writer - ); + return mapToDisplayParts(writer => { + typechecker.writeSignature(signature, enclosingDeclaration, flags, /*kind*/ + void 0, writer); }); } function nodeToDisplayParts(node, enclosingDeclaration) { const file = enclosingDeclaration.getSourceFile(); - return mapToDisplayParts((writer) => { + return mapToDisplayParts(writer => { const printer = createPrinterWithRemoveCommentsOmitTrailingSemicolon(); printer.writeNode(4 /* Unspecified */, node, file, writer); }); @@ -131546,8 +116907,7 @@ ${lanes.join("\n")} } function getSynthesizedDeepClone(node, includeTrivia = true) { const clone2 = node && getSynthesizedDeepCloneWorker(node); - if (clone2 && !includeTrivia) - suppressLeadingAndTrailingTrivia(clone2); + if (clone2 && !includeTrivia) suppressLeadingAndTrailingTrivia(clone2); return clone2; } function getSynthesizedDeepCloneWithReplacements(node, includeTrivia, replaceNode) { @@ -131557,23 +116917,14 @@ ${lanes.join("\n")} } else { clone2 = getSynthesizedDeepCloneWorker(node, replaceNode); } - if (clone2 && !includeTrivia) - suppressLeadingAndTrailingTrivia(clone2); + if (clone2 && !includeTrivia) suppressLeadingAndTrailingTrivia(clone2); return clone2; } function getSynthesizedDeepCloneWorker(node, replaceNode) { - const nodeClone = replaceNode ? (n) => getSynthesizedDeepCloneWithReplacements( - n, - /*includeTrivia*/ - true, - replaceNode - ) : getSynthesizedDeepClone; - const nodesClone = replaceNode ? (ns) => ns && getSynthesizedDeepClonesWithReplacements( - ns, - /*includeTrivia*/ - true, - replaceNode - ) : (ns) => ns && getSynthesizedDeepClones(ns); + const nodeClone = replaceNode ? n => getSynthesizedDeepCloneWithReplacements(n, /*includeTrivia*/ + true, replaceNode) : getSynthesizedDeepClone; + const nodesClone = replaceNode ? ns => ns && getSynthesizedDeepClonesWithReplacements(ns, /*includeTrivia*/ + true, replaceNode) : ns => ns && getSynthesizedDeepClones(ns); const visited = visitEachChild(node, nodeClone, nullTransformationContext, nodesClone, nodeClone); if (visited === node) { const clone2 = isStringLiteral(node) ? setOriginalNode(factory.createStringLiteralFromNode(node), node) : isNumericLiteral(node) ? setOriginalNode(factory.createNumericLiteral(node.text, node.numericLiteralFlags), node) : factory.cloneNode(node); @@ -131584,14 +116935,14 @@ ${lanes.join("\n")} } function getSynthesizedDeepClones(nodes, includeTrivia = true) { if (nodes) { - const cloned = factory.createNodeArray(nodes.map((n) => getSynthesizedDeepClone(n, includeTrivia)), nodes.hasTrailingComma); + const cloned = factory.createNodeArray(nodes.map(n => getSynthesizedDeepClone(n, includeTrivia)), nodes.hasTrailingComma); setTextRange(cloned, nodes); return cloned; } return nodes; } function getSynthesizedDeepClonesWithReplacements(nodes, includeTrivia, replaceNode) { - return factory.createNodeArray(nodes.map((n) => getSynthesizedDeepCloneWithReplacements(n, includeTrivia, replaceNode)), nodes.hasTrailingComma); + return factory.createNodeArray(nodes.map(n => getSynthesizedDeepCloneWithReplacements(n, includeTrivia, replaceNode)), nodes.hasTrailingComma); } function suppressLeadingAndTrailingTrivia(node) { suppressLeadingTrivia(node); @@ -131617,19 +116968,17 @@ ${lanes.join("\n")} 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); + return node.forEachChild(child => child); } function getUniqueName(baseName, sourceFile) { let nameText = baseName; @@ -131641,10 +116990,16 @@ ${lanes.join("\n")} function getRenameLocation(edits, renameFilename, name, preferLastLocation) { let delta = 0; let lastPos = -1; - for (const { fileName, textChanges: textChanges2 } of edits) { + for (const { + fileName, + textChanges: textChanges2 + } of edits) { Debug.assert(fileName === renameFilename); for (const change of textChanges2) { - const { span, newText } = change; + const { + span, + newText + } = change; const index = indexInTextChange(newText, escapeString(name)); if (index !== -1) { lastPos = span.start + delta + index; @@ -131680,13 +117035,10 @@ ${lanes.join("\n")} }; } 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) { @@ -131697,10 +117049,15 @@ ${lanes.join("\n")} switch (parent2.kind) { case 214 /* NewExpression */: return checker.getContextualType(parent2, contextFlags); - case 226 /* BinaryExpression */: { - const { left, operatorToken, right } = parent2; - return isEqualityOperatorKind(operatorToken.kind) ? checker.getTypeAtLocation(node === right ? left : right) : checker.getContextualType(node, contextFlags); - } + case 226 /* BinaryExpression */: + { + const { + left, + operatorToken, + right + } = parent2; + return isEqualityOperatorKind(operatorToken.kind) ? checker.getTypeAtLocation(node === right ? left : right) : checker.getContextualType(node, contextFlags); + } case 296 /* CaseClause */: return getSwitchedType(parent2, checker); default: @@ -131746,13 +117103,8 @@ ${lanes.join("\n")} const notAccessible = () => typeIsAccessible = false; const res = checker.typeToTypeNode(type, enclosingScope, 1 /* NoTruncation */, { trackSymbol: (symbol, declaration, meaning) => { - typeIsAccessible = typeIsAccessible && checker.isSymbolAccessible( - symbol, - declaration, - meaning, - /*shouldComputeAliasToMarkVisible*/ - false - ).accessibility === 0 /* Accessible */; + typeIsAccessible = typeIsAccessible && checker.isSymbolAccessible(symbol, declaration, meaning, /*shouldComputeAliasToMarkVisible*/ + false).accessibility === 0 /* Accessible */; return !typeIsAccessible; }, reportInaccessibleThisError: notAccessible, @@ -131765,15 +117117,19 @@ ${lanes.join("\n")} function syntaxRequiresTrailingCommaOrSemicolonOrASI(kind) { return kind === 179 /* CallSignature */ || kind === 180 /* ConstructSignature */ || kind === 181 /* IndexSignature */ || kind === 171 /* PropertySignature */ || kind === 173 /* MethodSignature */; } + function syntaxRequiresTrailingFunctionBlockOrSemicolonOrASI(kind) { return kind === 262 /* FunctionDeclaration */ || kind === 176 /* Constructor */ || kind === 174 /* MethodDeclaration */ || kind === 177 /* GetAccessor */ || kind === 178 /* SetAccessor */; } + function syntaxRequiresTrailingModuleBlockOrSemicolonOrASI(kind) { return kind === 267 /* ModuleDeclaration */; } + function syntaxRequiresTrailingSemicolonOrASI(kind) { return kind === 243 /* VariableStatement */ || kind === 244 /* ExpressionStatement */ || kind === 246 /* DoStatement */ || kind === 251 /* ContinueStatement */ || kind === 252 /* BreakStatement */ || kind === 253 /* ReturnStatement */ || kind === 257 /* ThrowStatement */ || kind === 259 /* DebuggerStatement */ || kind === 172 /* PropertyDeclaration */ || kind === 265 /* TypeAliasDeclaration */ || kind === 272 /* ImportDeclaration */ || kind === 271 /* ImportEqualsDeclaration */ || kind === 278 /* ExportDeclaration */ || kind === 270 /* NamespaceExportDeclaration */ || kind === 277 /* ExportAssignment */; } + function nodeIsASICandidate(node, sourceFile) { const lastToken = node.getLastToken(sourceFile); if (lastToken && lastToken.kind === 27 /* SemicolonToken */) { @@ -131799,7 +117155,7 @@ ${lanes.join("\n")} if (node.kind === 246 /* DoStatement */) { return true; } - const topNode = findAncestor(node, (ancestor) => !ancestor.parent); + const topNode = findAncestor(node, ancestor => !ancestor.parent); const nextToken = findNextToken(node, topNode, sourceFile); if (!nextToken || nextToken.kind === 20 /* CloseBraceToken */) { return true; @@ -131809,7 +117165,7 @@ ${lanes.join("\n")} return startLine !== endLine; } function positionIsASICandidate(pos, context, sourceFile) { - const contextAncestor = findAncestor(context, (ancestor) => { + const contextAncestor = findAncestor(context, ancestor => { if (ancestor.end !== pos) { return "quit"; } @@ -131875,7 +117231,7 @@ ${lanes.join("\n")} } function findPackageJsons(startDirectory, host, stopDirectory) { const paths = []; - forEachAncestorDirectory(startDirectory, (ancestor) => { + forEachAncestorDirectory(startDirectory, ancestor => { if (ancestor === stopDirectory) { return true; } @@ -131888,10 +117244,9 @@ ${lanes.join("\n")} } function findPackageJson(directory, host) { let packageJson; - forEachAncestorDirectory(directory, (ancestor) => { - if (ancestor === "node_modules") - return true; - packageJson = findConfigFile(ancestor, (f) => tryFileExists(host, f), "package.json"); + forEachAncestorDirectory(directory, ancestor => { + if (ancestor === "node_modules") return true; + packageJson = findConfigFile(ancestor, f => tryFileExists(host, f), "package.json"); if (packageJson) { return true; } @@ -131903,7 +117258,7 @@ ${lanes.join("\n")} return []; } const packageJsons = []; - forEachAncestorDirectory(getDirectoryPath(fileName), (ancestor) => { + forEachAncestorDirectory(getDirectoryPath(fileName), ancestor => { const packageJsonFileName = combinePaths(ancestor, "package.json"); if (host.fileExists(packageJsonFileName)) { const info = createPackageJsonInfo(packageJsonFileName, host); @@ -131928,19 +117283,14 @@ ${lanes.join("\n")} if (!dependencies) { continue; } - const dependencyMap = /* @__PURE__ */ new Map(); + const dependencyMap = /* @__PURE__ */new Map(); for (const packageName in dependencies) { dependencyMap.set(packageName, dependencies[packageName]); } info[key] = dependencyMap; } } - const dependencyGroups = [ - [1 /* Dependencies */, info.dependencies], - [2 /* DevDependencies */, info.devDependencies], - [8 /* OptionalDependencies */, info.optionalDependencies], - [4 /* PeerDependencies */, info.peerDependencies] - ]; + const dependencyGroups = [[1 /* Dependencies */, info.dependencies], [2 /* DevDependencies */, info.devDependencies], [8 /* OptionalDependencies */, info.optionalDependencies], [4 /* PeerDependencies */, info.peerDependencies]]; return { ...info, parseable: !!content, @@ -131962,7 +117312,7 @@ ${lanes.join("\n")} } } function createPackageJsonImportFilter(fromFile, preferences, host) { - const packageJsons = (host.getPackageJsonsVisibleToFile && host.getPackageJsonsVisibleToFile(fromFile.fileName) || getPackageJsonsVisibleToFile(fromFile.fileName, host)).filter((p) => p.parseable); + const packageJsons = (host.getPackageJsonsVisibleToFile && host.getPackageJsonsVisibleToFile(fromFile.fileName) || getPackageJsonsVisibleToFile(fromFile.fileName, host)).filter(p => p.parseable); let usesNodeCoreModules; let ambientModuleCache; let sourceFileCache; @@ -131985,7 +117335,7 @@ ${lanes.join("\n")} return true; } if (!ambientModuleCache) { - ambientModuleCache = /* @__PURE__ */ new Map(); + ambientModuleCache = /* @__PURE__ */new Map(); } else { const cached = ambientModuleCache.get(moduleSymbol); if (cached !== void 0) { @@ -132012,7 +117362,7 @@ ${lanes.join("\n")} return true; } if (!sourceFileCache) { - sourceFileCache = /* @__PURE__ */ new Map(); + sourceFileCache = /* @__PURE__ */new Map(); } else { const cached = sourceFileCache.get(sourceFile); if (cached !== void 0) { @@ -132052,13 +117402,7 @@ ${lanes.join("\n")} if (!importedFileName.includes("node_modules")) { return void 0; } - const specifier = ts_moduleSpecifiers_exports.getNodeModulesPackageName( - host.getCompilationSettings(), - fromFile, - importedFileName, - moduleSpecifierResolutionHost, - preferences - ); + const specifier = ts_moduleSpecifiers_exports.getNodeModulesPackageName(host.getCompilationSettings(), fromFile, importedFileName, moduleSpecifierResolutionHost, preferences); if (!specifier) { return void 0; } @@ -132082,7 +117426,9 @@ ${lanes.join("\n")} } } function consumesNodeCoreModules(sourceFile) { - return some(sourceFile.imports, ({ text }) => ts_JsTyping_exports.nodeCoreModules.has(text)); + return some(sourceFile.imports, ({ + text + }) => ts_JsTyping_exports.nodeCoreModules.has(text)); } function isInsideNodeModules(fileOrDirectory) { return contains(getPathComponents(fileOrDirectory), "node_modules"); @@ -132101,7 +117447,7 @@ ${lanes.join("\n")} } function getDiagnosticsWithinSpan(span, sortedFileDiagnostics) { var _a; - let index = binarySearchKey(sortedFileDiagnostics, span.start, (diag2) => diag2.start, compareValues); + let index = binarySearchKey(sortedFileDiagnostics, span.start, diag2 => diag2.start, compareValues); if (index < 0) { index = ~index; } @@ -132122,12 +117468,15 @@ ${lanes.join("\n")} } return result; } - function getRefactorContextSpan({ startPosition, endPosition }) { + function getRefactorContextSpan({ + startPosition, + endPosition + }) { return createTextSpanFromBounds(startPosition, endPosition === void 0 ? startPosition : endPosition); } function getFixableErrorSpanExpression(sourceFile, span) { const token = getTokenAtPosition(sourceFile, span.start); - const expression = findAncestor(token, (node) => { + const expression = findAncestor(token, node => { if (node.getStart(sourceFile) < span.start || node.getEnd() > textSpanEnd(span)) { return "quit"; } @@ -132144,22 +117493,12 @@ ${lanes.join("\n")} function getNamesForExportedSymbol(symbol, scriptTarget) { if (needsNameFromDeclaration(symbol)) { const fromDeclaration = getDefaultLikeExportNameFromDeclaration(symbol); - if (fromDeclaration) - return fromDeclaration; - const fileNameCase = ts_codefix_exports.moduleSymbolToValidIdentifier( - getSymbolParentOrFail(symbol), - scriptTarget, - /*forceCapitalize*/ - false - ); - const capitalized = ts_codefix_exports.moduleSymbolToValidIdentifier( - getSymbolParentOrFail(symbol), - scriptTarget, - /*forceCapitalize*/ - true - ); - if (fileNameCase === capitalized) - return fileNameCase; + if (fromDeclaration) return fromDeclaration; + const fileNameCase = ts_codefix_exports.moduleSymbolToValidIdentifier(getSymbolParentOrFail(symbol), scriptTarget, /*forceCapitalize*/ + false); + const capitalized = ts_codefix_exports.moduleSymbolToValidIdentifier(getSymbolParentOrFail(symbol), scriptTarget, /*forceCapitalize*/ + true); + if (fileNameCase === capitalized) return fileNameCase; return [fileNameCase, capitalized]; } return symbol.name; @@ -132173,8 +117512,9 @@ ${lanes.join("\n")} function needsNameFromDeclaration(symbol) { return !(symbol.flags & 33554432 /* Transient */) && (symbol.escapedName === "export=" /* ExportEquals */ || symbol.escapedName === "default" /* Default */); } + function getDefaultLikeExportNameFromDeclaration(symbol) { - return firstDefined(symbol.declarations, (d) => { + return firstDefined(symbol.declarations, d => { var _a, _b, _c; if (isExportAssignment(d)) { return (_a = tryCast(skipOuterExpressions(d.expression), isIdentifier)) == null ? void 0 : _a.text; @@ -132187,15 +117527,14 @@ ${lanes.join("\n")} } function getSymbolParentOrFail(symbol) { var _a; - return Debug.checkDefined( - symbol.parent, - `Symbol parent was undefined. Flags: ${Debug.formatSymbolFlags(symbol.flags)}. Declarations: ${(_a = symbol.declarations) == null ? void 0 : _a.map((d) => { - const kind = Debug.formatSyntaxKind(d.kind); - const inJS = isInJSFile(d); - const { expression } = d; - return (inJS ? "[JS]" : "") + kind + (expression ? ` (expression: ${Debug.formatSyntaxKind(expression.kind)})` : ""); - }).join(", ")}.` - ); + return Debug.checkDefined(symbol.parent, `Symbol parent was undefined. Flags: ${Debug.formatSymbolFlags(symbol.flags)}. Declarations: ${(_a = symbol.declarations) == null ? void 0 : _a.map(d => { + const kind = Debug.formatSyntaxKind(d.kind); + const inJS = isInJSFile(d); + const { + expression + } = d; + return (inJS ? "[JS]" : "") + kind + (expression ? ` (expression: ${Debug.formatSyntaxKind(expression.kind)})` : ""); + }).join(", ")}.`); } function stringContainsAt(haystack, needle, startIndex) { const needleLength = needle.length; @@ -132203,14 +117542,14 @@ ${lanes.join("\n")} 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; } function startsWithUnderscore(name) { return name.charCodeAt(0) === 95 /* _ */; } + function isGlobalDeclaration(declaration) { return !isNonGlobalDeclaration(declaration); } @@ -132219,26 +117558,30 @@ ${lanes.join("\n")} if (!sourceFile.externalModuleIndicator && !sourceFile.commonJsModuleIndicator) { return false; } - return isInJSFile(declaration) || !findAncestor(declaration, (d) => isModuleDeclaration(d) && isGlobalScopeAugmentation(d)); + return isInJSFile(declaration) || !findAncestor(declaration, d => isModuleDeclaration(d) && isGlobalScopeAugmentation(d)); } function isDeprecatedDeclaration(decl) { return !!(getCombinedNodeFlagsAlwaysIncludeJSDoc(decl) & 65536 /* Deprecated */); } + function shouldUseUriStyleNodeCoreModules(file, program) { - const decisionFromFile = firstDefined(file.imports, (node) => { + const decisionFromFile = firstDefined(file.imports, node => { if (ts_JsTyping_exports.nodeCoreModules.has(node.text)) { return startsWith(node.text, "node:"); } }); - return decisionFromFile ?? program.usesUriStyleNodeCoreModules; + return decisionFromFile !== null && decisionFromFile !== void 0 ? decisionFromFile : program.usesUriStyleNodeCoreModules; } function getNewLineKind(newLineCharacter) { return newLineCharacter === "\n" ? 1 /* LineFeed */ : 0 /* CarriageReturnLineFeed */; } + function diagnosticToString(diag2) { return isArray(diag2) ? formatStringFromArgs(getLocaleSpecificMessage(diag2[0]), diag2.slice(1)) : getLocaleSpecificMessage(diag2); } - function getFormatCodeSettingsForWriting({ options }, sourceFile) { + function getFormatCodeSettingsForWriting({ + options + }, sourceFile) { const shouldAutoDetectSemicolonPreference = !options.semicolons || options.semicolons === "ignore" /* Ignore */; const shouldRemoveSemicolons = options.semicolons === "remove" /* Remove */ || shouldAutoDetectSemicolonPreference && !probablyUsesSemicolons(sourceFile); return { @@ -132246,16 +117589,18 @@ ${lanes.join("\n")} semicolons: shouldRemoveSemicolons ? "remove" /* Remove */ : "ignore" /* Ignore */ }; } + function jsxModeNeedsExplicitImport(jsx) { return jsx === 2 /* React */ || jsx === 3 /* ReactNative */; } + function isSourceFileFromLibrary(program, node) { return program.isSourceFileFromExternalLibrary(node) || program.isSourceFileDefaultLibrary(node); } function newCaseClauseTracker(checker, clauses) { - const existingStrings = /* @__PURE__ */ new Set(); - const existingNumbers = /* @__PURE__ */ new Set(); - const existingBigInts = /* @__PURE__ */ new Set(); + const existingStrings = /* @__PURE__ */new Set(); + const existingNumbers = /* @__PURE__ */new Set(); + const existingBigInts = /* @__PURE__ */new Set(); for (const clause of clauses) { if (!isDefaultClause(clause)) { const expression = skipParentheses(clause.expression); @@ -132345,13 +117690,11 @@ ${lanes.join("\n")} var init_utilities4 = __esm({ "src/services/utilities.ts"() { "use strict"; + init_ts4(); - scanner = createScanner( - 99 /* Latest */, - /*skipTrivia*/ - true - ); - SemanticMeaning = /* @__PURE__ */ ((SemanticMeaning3) => { + scanner = createScanner(99 /* Latest */, /*skipTrivia*/ + true); + SemanticMeaning = /* @__PURE__ */(SemanticMeaning3 => { SemanticMeaning3[SemanticMeaning3["None"] = 0] = "None"; SemanticMeaning3[SemanticMeaning3["Value"] = 1] = "Value"; SemanticMeaning3[SemanticMeaning3["Type"] = 2] = "Type"; @@ -132360,29 +117703,9 @@ ${lanes.join("\n")} return SemanticMeaning3; })(SemanticMeaning || {}); tripleSlashDirectivePrefixRegex = /^\/\/\/\s* { + typeKeywords = [133 /* AnyKeyword */, 131 /* AssertsKeyword */, 163 /* BigIntKeyword */, 136 /* BooleanKeyword */, 97 /* FalseKeyword */, 140 /* InferKeyword */, 143 /* KeyOfKeyword */, 146 /* NeverKeyword */, 106 /* NullKeyword */, 150 /* NumberKeyword */, 151 /* ObjectKeyword */, 148 /* ReadonlyKeyword */, 154 /* StringKeyword */, 155 /* SymbolKeyword */, 114 /* TypeOfKeyword */, 112 /* TrueKeyword */, 116 /* VoidKeyword */, 157 /* UndefinedKeyword */, 158 /* UniqueKeyword */, 159 /* UnknownKeyword */]; + + QuotePreference = /* @__PURE__ */(QuotePreference7 => { QuotePreference7[QuotePreference7["Single"] = 0] = "Single"; QuotePreference7[QuotePreference7["Double"] = 1] = "Double"; return QuotePreference7; @@ -132390,12 +117713,7 @@ ${lanes.join("\n")} displayPartWriter = getDisplayPartWriter(); lineFeed2 = "\n"; ANONYMOUS = "anonymous function"; - syntaxMayBeASICandidate = or( - syntaxRequiresTrailingCommaOrSemicolonOrASI, - syntaxRequiresTrailingFunctionBlockOrSemicolonOrASI, - syntaxRequiresTrailingModuleBlockOrSemicolonOrASI, - syntaxRequiresTrailingSemicolonOrASI - ); + syntaxMayBeASICandidate = or(syntaxRequiresTrailingCommaOrSemicolonOrASI, syntaxRequiresTrailingFunctionBlockOrSemicolonOrASI, syntaxRequiresTrailingModuleBlockOrSemicolonOrASI, syntaxRequiresTrailingSemicolonOrASI); } }); @@ -132403,11 +117721,11 @@ ${lanes.join("\n")} function createCacheableExportInfoMap(host) { let exportInfoId = 1; const exportInfo = createMultiMap(); - const symbols = /* @__PURE__ */ new Map(); - const packages = /* @__PURE__ */ new Map(); + const symbols = /* @__PURE__ */new Map(); + const packages = /* @__PURE__ */new Map(); let usableByFileName; const cache = { - isUsableByFile: (importingFile) => importingFile === usableByFileName, + isUsableByFile: importingFile => importingFile === usableByFileName, isEmpty: () => !exportInfo.size, clear: () => { exportInfo.clear(); @@ -132423,7 +117741,11 @@ ${lanes.join("\n")} if (moduleFile) { const nodeModulesPathParts = getNodeModulePathParts(moduleFile.fileName); if (nodeModulesPathParts) { - const { topLevelNodeModulesIndex, topLevelPackageNameIndex, packageRootIndex } = nodeModulesPathParts; + const { + topLevelNodeModulesIndex, + topLevelPackageNameIndex, + packageRootIndex + } = nodeModulesPathParts; packageName = unmangleScopedPackageName(getPackageNameFromTypesPackageName(moduleFile.fileName.substring(topLevelPackageNameIndex + 1, packageRootIndex))); if (startsWith(importingFile, moduleFile.path.substring(0, topLevelNodeModulesIndex))) { const prevDeepestNodeModulesPath = packages.get(packageName); @@ -132441,11 +117763,8 @@ ${lanes.join("\n")} } const isDefault = exportKind === 1 /* Default */; const namedSymbol = isDefault && getLocalSymbolForExportDefault(symbol) || symbol; - const names = exportKind === 0 /* Named */ || isExternalModuleSymbol(namedSymbol) ? unescapeLeadingUnderscores(symbolTableKey) : getNamesForExportedSymbol( - namedSymbol, - /*scriptTarget*/ - void 0 - ); + const names = exportKind === 0 /* Named */ || isExternalModuleSymbol(namedSymbol) ? unescapeLeadingUnderscores(symbolTableKey) : getNamesForExportedSymbol(namedSymbol, /*scriptTarget*/ + void 0); const symbolName2 = typeof names === "string" ? names : names[0]; const capitalizedSymbolName = typeof names === "string" ? void 0 : names[1]; const moduleName = stripQuotes(moduleSymbol.name); @@ -132453,8 +117772,7 @@ ${lanes.join("\n")} 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, @@ -132472,24 +117790,24 @@ ${lanes.join("\n")} }); }, 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 { + symbolName: symbolName2, + ambientModuleName + } = parseKey(key2); const name = preferCapitalized && info[0].capitalizedSymbolName || symbolName2; if (matches(name, info[0].targetFlags)) { const rehydrated = info.map(rehydrateCachedInfo); 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; } } }); @@ -132501,9 +117819,11 @@ ${lanes.join("\n")} if (fileIsGlobalOnly(oldSourceFile) && fileIsGlobalOnly(newSourceFile)) { return false; } - if (usableByFileName && usableByFileName !== newSourceFile.path || // If ATA is enabled, auto-imports uses existing imports to guess whether you want auto-imports from node. + if (usableByFileName && usableByFileName !== newSourceFile.path || + // If ATA is enabled, auto-imports uses existing imports to guess whether you want auto-imports from node. // Adding or removing imports from node could change the outcome of that guess, so could change the suggestions list. - typeAcquisitionEnabled && consumesNodeCoreModules(oldSourceFile) !== consumesNodeCoreModules(newSourceFile) || // Module agumentation and ambient module changes can add or remove exports available to be auto-imported. + typeAcquisitionEnabled && consumesNodeCoreModules(oldSourceFile) !== consumesNodeCoreModules(newSourceFile) || + // Module agumentation and ambient module changes can add or remove exports available to be auto-imported. // Changes elsewhere in the file can change the *type* of an export in a module augmentation, // but type info is gathered in getCompletionEntryDetails, which doesn't use the cache. !arrayIsEqualTo(oldSourceFile.moduleAugmentations, newSourceFile.moduleAugmentations) || !ambientModuleDeclarationsAreEqual(oldSourceFile, newSourceFile)) { @@ -132515,13 +117835,20 @@ ${lanes.join("\n")} } }; if (Debug.isDebugging) { - Object.defineProperty(cache, "__cache", { value: exportInfo }); + Object.defineProperty(cache, "__cache", { + value: exportInfo + }); } return cache; function rehydrateCachedInfo(info) { - if (info.symbol && info.moduleSymbol) - return info; - const { id, exportKind, targetFlags, isFromPackageJson, moduleFileName } = 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) { return { @@ -132534,13 +117861,8 @@ ${lanes.join("\n")} }; } const checker = (isFromPackageJson ? host.getPackageJsonAutoImportProvider() : host.getCurrentProgram()).getTypeChecker(); - const moduleSymbol = info.moduleSymbol || cachedModuleSymbol || Debug.checkDefined( - info.moduleFile ? checker.getMergedSymbol(info.moduleFile.symbol) : checker.tryFindAmbientModule(info.moduleName) - ); - const symbol = info.symbol || cachedSymbol || Debug.checkDefined( - exportKind === 2 /* ExportEquals */ ? checker.resolveExternalModuleSymbol(moduleSymbol) : checker.tryGetMemberInModuleExportsAndProperties(unescapeLeadingUnderscores(info.symbolTableKey), moduleSymbol), - `Could not find symbol '${info.symbolName}' by key '${info.symbolTableKey}' in module ${moduleSymbol.name}` - ); + const moduleSymbol = info.moduleSymbol || cachedModuleSymbol || Debug.checkDefined(info.moduleFile ? checker.getMergedSymbol(info.moduleFile.symbol) : checker.tryFindAmbientModule(info.moduleName)); + const symbol = info.symbol || cachedSymbol || Debug.checkDefined(exportKind === 2 /* ExportEquals */ ? checker.resolveExternalModuleSymbol(moduleSymbol) : checker.tryGetMemberInModuleExportsAndProperties(unescapeLeadingUnderscores(info.symbolTableKey), moduleSymbol), `Could not find symbol '${info.symbolName}' by key '${info.symbolTableKey}' in module ${moduleSymbol.name}`); symbols.set(id, [symbol, moduleSymbol]); return { symbol, @@ -132563,7 +117885,10 @@ ${lanes.join("\n")} const symbolName2 = data.substring(0, symbolNameLength); const moduleKey = data.substring(symbolNameLength + 1); const ambientModuleName = moduleKey === "" ? void 0 : moduleKey; - return { symbolName: symbolName2, ambientModuleName }; + return { + symbolName: symbolName2, + ambientModuleName + }; } function fileIsGlobalOnly(file) { return !file.commonJsModuleIndicator && !file.externalModuleIndicator && !file.moduleAugmentations && !file.ambientModuleNames; @@ -132575,7 +117900,7 @@ ${lanes.join("\n")} let oldFileStatementIndex = -1; let newFileStatementIndex = -1; for (const ambientModuleName of newSourceFile.ambientModuleNames) { - const isMatchingModuleDeclaration = (node) => isNonGlobalAmbientModule(node) && node.name.text === ambientModuleName; + const isMatchingModuleDeclaration = node => isNonGlobalAmbientModule(node) && node.name.text === ambientModuleName; oldFileStatementIndex = findIndex(oldSourceFile.statements, isMatchingModuleDeclaration, oldFileStatementIndex + 1); newFileStatementIndex = findIndex(newSourceFile.statements, isMatchingModuleDeclaration, newFileStatementIndex + 1); if (oldSourceFile.statements[oldFileStatementIndex] !== newSourceFile.statements[newFileStatementIndex]) { @@ -132585,36 +117910,27 @@ ${lanes.join("\n")} 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; } const getCanonicalFileName = hostGetCanonicalFileName(moduleSpecifierResolutionHost); const globalTypingsCache = (_a = moduleSpecifierResolutionHost.getGlobalTypingsCacheLocation) == null ? void 0 : _a.call(moduleSpecifierResolutionHost); - const hasImportablePath = !!ts_moduleSpecifiers_exports.forEachFileNameOfModule( - from.fileName, - to.fileName, - moduleSpecifierResolutionHost, - /*preferSymlinks*/ - false, - (toPath3) => { - const toFile = program.getSourceFile(toPath3); - return (toFile === to || !toFile) && isImportablePath(from.fileName, toPath3, getCanonicalFileName, globalTypingsCache); - } - ); + const hasImportablePath = !!ts_moduleSpecifiers_exports.forEachFileNameOfModule(from.fileName, to.fileName, moduleSpecifierResolutionHost, /*preferSymlinks*/ + false, toPath3 => { + const toFile = program.getSourceFile(toPath3); + return (toFile === to || !toFile) && isImportablePath(from.fileName, toPath3, getCanonicalFileName, globalTypingsCache); + }); if (packageJsonFilter) { const isAutoImportable = hasImportablePath && packageJsonFilter.allowsImportingSourceFile(to, moduleSpecifierResolutionHost); moduleSpecifierCache == null ? void 0 : moduleSpecifierCache.setBlockedByPackageJsonDependencies(from.path, to.path, preferences, {}, !isAutoImportable); @@ -132623,44 +117939,29 @@ ${lanes.join("\n")} return hasImportablePath; } function isImportablePath(fromPath, toPath3, getCanonicalFileName, globalCachePath) { - const toNodeModules = forEachAncestorDirectory(toPath3, (ancestor) => getBaseFileName(ancestor) === "node_modules" ? ancestor : void 0); + const toNodeModules = forEachAncestorDirectory(toPath3, ancestor => getBaseFileName(ancestor) === "node_modules" ? ancestor : void 0); const toNodeModulesParent = toNodeModules && getDirectoryPath(getCanonicalFileName(toNodeModules)); return toNodeModulesParent === void 0 || startsWith(getCanonicalFileName(fromPath), toNodeModulesParent) || !!globalCachePath && startsWith(getCanonicalFileName(globalCachePath), toNodeModulesParent); } function forEachExternalModuleToImportFrom(program, host, preferences, useAutoImportProvider, cb) { var _a, _b; const useCaseSensitiveFileNames2 = hostUsesCaseSensitiveFileNames(host); - const excludePatterns = preferences.autoImportFileExcludePatterns && mapDefined(preferences.autoImportFileExcludePatterns, (spec) => { + const excludePatterns = preferences.autoImportFileExcludePatterns && mapDefined(preferences.autoImportFileExcludePatterns, spec => { const pattern = getPatternFromSpec(spec, "", "exclude"); return pattern ? getRegexFromPattern(pattern, useCaseSensitiveFileNames2) : void 0; }); - forEachExternalModule(program.getTypeChecker(), program.getSourceFiles(), excludePatterns, (module2, file) => cb( - module2, - file, - program, - /*isFromPackageJson*/ - false - )); + forEachExternalModule(program.getTypeChecker(), program.getSourceFiles(), excludePatterns, (module2, file) => cb(module2, file, program, /*isFromPackageJson*/ + false)); const autoImportProvider = useAutoImportProvider && ((_a = host.getPackageJsonAutoImportProvider) == null ? void 0 : _a.call(host)); if (autoImportProvider) { const start = timestamp(); const checker = program.getTypeChecker(); forEachExternalModule(autoImportProvider.getTypeChecker(), autoImportProvider.getSourceFiles(), excludePatterns, (module2, file) => { - if (file && !program.getSourceFile(file.fileName) || !file && !checker.resolveName( - module2.name, - /*location*/ - void 0, - 1536 /* Module */, - /*excludeGlobals*/ - false - )) { - cb( - module2, - file, - autoImportProvider, - /*isFromPackageJson*/ - true - ); + if (file && !program.getSourceFile(file.fileName) || !file && !checker.resolveName(module2.name, /*location*/ + void 0, 1536 /* Module */, /*excludeGlobals*/ + false)) { + cb(module2, file, autoImportProvider, /*isFromPackageJson*/ + true); } }); (_b = host.log) == null ? void 0 : _b.call(host, `forEachExternalModuleToImportFrom autoImportProvider: ${timestamp() - start}`); @@ -132668,14 +117969,11 @@ ${lanes.join("\n")} } function forEachExternalModule(checker, allSourceFiles, excludePatterns, cb) { var _a; - const isExcluded = excludePatterns && ((fileName) => excludePatterns.some((p) => p.test(fileName))); + const isExcluded = excludePatterns && (fileName => excludePatterns.some(p => p.test(fileName))); for (const ambient of checker.getAmbientModules()) { - if (!ambient.name.includes("*") && !(excludePatterns && ((_a = ambient.declarations) == null ? void 0 : _a.every((d) => isExcluded(d.getSourceFile().fileName))))) { - cb( - ambient, - /*sourceFile*/ - void 0 - ); + if (!ambient.name.includes("*") && !(excludePatterns && ((_a = ambient.declarations) == null ? void 0 : _a.every(d => isExcluded(d.getSourceFile().fileName))))) { + cb(ambient, /*sourceFile*/ + void 0); } } for (const sourceFile of allSourceFiles) { @@ -132707,46 +118005,21 @@ ${lanes.join("\n")} const compilerOptions = program.getCompilerOptions(); let moduleCount = 0; try { - forEachExternalModuleToImportFrom( - program, - host, - preferences, - /*useAutoImportProvider*/ - true, - (moduleSymbol, moduleFile, program2, isFromPackageJson) => { - 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); - if (defaultInfo && isImportableSymbol(defaultInfo.symbol, checker)) { - cache.add( - importingFile.path, - defaultInfo.symbol, - defaultInfo.exportKind === 1 /* Default */ ? "default" /* Default */ : "export=" /* ExportEquals */, - moduleSymbol, - moduleFile, - defaultInfo.exportKind, - isFromPackageJson, - checker - ); - } - checker.forEachExportAndPropertyOfModule(moduleSymbol, (exported, key) => { - if (exported !== (defaultInfo == null ? void 0 : defaultInfo.symbol) && isImportableSymbol(exported, checker) && addToSeen(seenExports, key)) { - cache.add( - importingFile.path, - exported, - key, - moduleSymbol, - moduleFile, - 0 /* Named */, - isFromPackageJson, - checker - ); - } - }); + forEachExternalModuleToImportFrom(program, host, preferences, /*useAutoImportProvider*/ + true, (moduleSymbol, moduleFile, program2, isFromPackageJson) => { + 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); + if (defaultInfo && isImportableSymbol(defaultInfo.symbol, checker)) { + cache.add(importingFile.path, defaultInfo.symbol, defaultInfo.exportKind === 1 /* Default */ ? "default" /* Default */ : "export=" /* ExportEquals */, moduleSymbol, moduleFile, defaultInfo.exportKind, isFromPackageJson, checker); } - ); + checker.forEachExportAndPropertyOfModule(moduleSymbol, (exported, key) => { + if (exported !== (defaultInfo == null ? void 0 : defaultInfo.symbol) && isImportableSymbol(exported, checker) && addToSeen(seenExports, key)) { + cache.add(importingFile.path, exported, key, moduleSymbol, moduleFile, 0 /* Named */, isFromPackageJson, checker); + } + }); + }); } catch (err) { cache.clear(); throw err; @@ -132756,30 +118029,45 @@ ${lanes.join("\n")} } function getDefaultLikeExportInfo(moduleSymbol, checker, compilerOptions) { const exported = getDefaultLikeExportWorker(moduleSymbol, checker); - if (!exported) - return void 0; - const { symbol, exportKind } = exported; + if (!exported) return void 0; + const { + symbol, + exportKind + } = exported; const info = getDefaultExportInfoWorker(symbol, checker, compilerOptions); - return info && { symbol, exportKind, ...info }; + return info && { + symbol, + exportKind, + ...info + }; } 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 */ }; + if (exportEquals !== moduleSymbol) return { + symbol: exportEquals, + exportKind: 2 /* ExportEquals */ + }; const defaultExport = checker.tryGetMemberInModuleExports("default" /* Default */, moduleSymbol); - if (defaultExport) - return { symbol: defaultExport, exportKind: 1 /* Default */ }; + 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 }; + if (localSymbol) return { + resolvedSymbol: localSymbol, + name: localSymbol.name + }; const name = getNameForExportDefault(defaultExport); - if (name !== void 0) - return { resolvedSymbol: defaultExport, name }; + if (name !== void 0) return { + resolvedSymbol: defaultExport, + name + }; if (defaultExport.flags & 2097152 /* Alias */) { const aliased = checker.getImmediateAliasedSymbol(defaultExport); if (aliased && aliased.parent) { @@ -132787,12 +118075,18 @@ ${lanes.join("\n")} } } if (defaultExport.escapedName !== "default" /* Default */ && defaultExport.escapedName !== "export=" /* ExportEquals */) { - return { resolvedSymbol: defaultExport, name: defaultExport.getName() }; + return { + resolvedSymbol: defaultExport, + name: defaultExport.getName() + }; } - return { resolvedSymbol: defaultExport, name: getNameForExportedSymbol(defaultExport, compilerOptions.target) }; + return { + resolvedSymbol: defaultExport, + name: getNameForExportedSymbol(defaultExport, compilerOptions.target) + }; } function getNameForExportDefault(symbol) { - return symbol.declarations && firstDefined(symbol.declarations, (declaration) => { + return symbol.declarations && firstDefined(symbol.declarations, declaration => { var _a; if (isExportAssignment(declaration)) { return (_a = tryCast(skipOuterExpressions(declaration.expression), isIdentifier)) == null ? void 0 : _a.text; @@ -132806,15 +118100,16 @@ ${lanes.join("\n")} var init_exportInfoMap = __esm({ "src/services/exportInfoMap.ts"() { "use strict"; + init_ts4(); - ImportKind = /* @__PURE__ */ ((ImportKind2) => { + ImportKind = /* @__PURE__ */(ImportKind2 => { ImportKind2[ImportKind2["Named"] = 0] = "Named"; ImportKind2[ImportKind2["Default"] = 1] = "Default"; ImportKind2[ImportKind2["Namespace"] = 2] = "Namespace"; ImportKind2[ImportKind2["CommonJS"] = 3] = "CommonJS"; return ImportKind2; })(ImportKind || {}); - ExportKind = /* @__PURE__ */ ((ExportKind3) => { + ExportKind = /* @__PURE__ */(ExportKind3 => { ExportKind3[ExportKind3["Named"] = 0] = "Named"; ExportKind3[ExportKind3["Default"] = 1] = "Default"; ExportKind3[ExportKind3["ExportEquals"] = 2] = "ExportEquals"; @@ -132826,11 +118121,8 @@ ${lanes.join("\n")} // src/services/classifier.ts function createClassifier() { - const scanner2 = createScanner( - 99 /* Latest */, - /*skipTrivia*/ - false - ); + const scanner2 = createScanner(99 /* Latest */, /*skipTrivia*/ + false); function getClassificationsForLine(text, lexState, syntacticClassifierAbsent) { return convertClassificationsToResult(getEncodedLexicalClassifications(text, lexState, syntacticClassifierAbsent), text); } @@ -132838,12 +118130,16 @@ ${lanes.join("\n")} let token = 0 /* Unknown */; let lastNonTriviaToken = 0 /* Unknown */; const templateStack = []; - const { prefix, pushTemplate } = getPrefixFromLexState(lexState); + const { + prefix, + pushTemplate + } = getPrefixFromLexState(lexState); text = prefix + text; const offset = prefix.length; if (pushTemplate) { templateStack.push(16 /* TemplateHead */); } + scanner2.setText(text); let endOfLineState = 0 /* None */; const spans = []; @@ -132870,6 +118166,7 @@ ${lanes.join("\n")} if (!noRegexTable[lastNonTriviaToken] && scanner2.reScanSlashToken() === 14 /* RegularExpressionLiteral */) { token = 14 /* RegularExpressionLiteral */; } + break; case 30 /* LessThanToken */: if (lastNonTriviaToken === 80 /* Identifier */) { @@ -132889,6 +118186,7 @@ ${lanes.join("\n")} if (angleBracketStack > 0 && !syntacticClassifierAbsent) { token = 80 /* Identifier */; } + break; case 16 /* TemplateHead */: templateStack.push(token); @@ -132902,10 +118200,8 @@ ${lanes.join("\n")} if (templateStack.length > 0) { const lastTemplateStackToken = lastOrUndefined(templateStack); if (lastTemplateStackToken === 16 /* TemplateHead */) { - token = scanner2.reScanTemplateToken( - /*isTaggedTemplate*/ - false - ); + token = scanner2.reScanTemplateToken( /*isTaggedTemplate*/ + false); if (token === 18 /* TemplateTail */) { templateStack.pop(); } else { @@ -132928,25 +118224,32 @@ ${lanes.join("\n")} } } } - return { endOfLineState, spans }; + + return { + endOfLineState, + spans + }; } - return { getClassificationsForLine, getEncodedLexicalClassifications }; + return { + getClassificationsForLine, + getEncodedLexicalClassifications + }; } function getNewEndOfLineState(scanner2, token, lastOnTemplateStack) { switch (token) { - case 11 /* StringLiteral */: { - 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++; + case 11 /* StringLiteral */: + { + 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; + return tokenText.charCodeAt(0) === 34 /* doubleQuote */ ? 3 /* InDoubleQuoteStringLiteral */ : 2 /* InSingleQuoteStringLiteral */; } - if ((numBackslashes & 1) === 0) - return void 0; - return tokenText.charCodeAt(0) === 34 /* doubleQuote */ ? 3 /* InDoubleQuoteStringLiteral */ : 2 /* InSingleQuoteStringLiteral */; - } + case 3 /* MultiLineCommentTrivia */: return scanner2.isUnterminated() ? 1 /* InMultiLineCommentTrivia */ : void 0; default: @@ -132989,17 +118292,31 @@ ${lanes.join("\n")} if (lastEnd >= 0) { const whitespaceLength2 = start - lastEnd; if (whitespaceLength2 > 0) { - entries.push({ length: whitespaceLength2, classification: 4 /* Whitespace */ }); + entries.push({ + length: whitespaceLength2, + classification: 4 /* Whitespace */ + }); } } - entries.push({ length: length2, classification: convertClassification(type) }); + + entries.push({ + length: length2, + classification: convertClassification(type) + }); lastEnd = start + length2; } const whitespaceLength = text.length - lastEnd; if (whitespaceLength > 0) { - entries.push({ length: whitespaceLength, classification: 4 /* Whitespace */ }); + entries.push({ + length: whitespaceLength, + classification: 4 /* Whitespace */ + }); } - return { entries, finalLexState: classifications.endOfLineState }; + + return { + entries, + finalLexState: classifications.endOfLineState + }; } function convertClassification(type) { switch (type) { @@ -133051,19 +118368,35 @@ ${lanes.join("\n")} function getPrefixFromLexState(lexState) { switch (lexState) { case 3 /* InDoubleQuoteStringLiteral */: - return { prefix: '"\\\n' }; + return { + prefix: '"\\\n' + }; case 2 /* InSingleQuoteStringLiteral */: - return { prefix: "'\\\n" }; + return { + prefix: "'\\\n" + }; case 1 /* InMultiLineCommentTrivia */: - return { prefix: "/*\n" }; + return { + prefix: "/*\n" + }; case 4 /* InTemplateHeadOrNoSubstitutionTemplate */: - return { prefix: "`\n" }; + return { + prefix: "`\n" + }; case 5 /* InTemplateMiddleOrTail */: - return { prefix: "}\n", pushTemplate: true }; + return { + prefix: "}\n", + pushTemplate: true + }; case 6 /* InTemplateSubstitutionPosition */: - return { prefix: "", pushTemplate: true }; + return { + prefix: "", + pushTemplate: true + }; case 0 /* None */: - return { prefix: "" }; + return { + prefix: "" + }; default: return Debug.assertNever(lexState); } @@ -133138,6 +118471,7 @@ ${lanes.join("\n")} } else if (token >= 19 /* FirstPunctuation */ && token <= 79 /* LastPunctuation */) { return 10 /* punctuation */; } + switch (token) { case 9 /* NumericLiteral */: return 4 /* numericLiteral */; @@ -133159,9 +118493,11 @@ ${lanes.join("\n")} if (isTemplateLiteralKind(token)) { return 6 /* stringLiteral */; } + return 2 /* identifier */; } } + function getSemanticClassifications(typeChecker, cancellationToken, sourceFile, classifiableNames, span) { return convertClassificationsToSpans(getEncodedSemanticClassifications(typeChecker, cancellationToken, sourceFile, classifiableNames, span)); } @@ -133193,7 +118529,10 @@ ${lanes.join("\n")} } node.forEachChild(cb); }); - return { spans, endOfLineState: 0 /* None */ }; + return { + spans, + endOfLineState: 0 /* None */ + }; function pushClassification(start, end, type) { const length2 = end - start; Debug.assert(length2 > 0, `Classification had non-positive length of ${length2}`); @@ -133223,8 +118562,9 @@ ${lanes.join("\n")} } } function hasValueSideModule(symbol) { - return some(symbol.declarations, (declaration) => isModuleDeclaration(declaration) && getModuleInstanceState(declaration) === 1 /* Instantiated */); + return some(symbol.declarations, declaration => isModuleDeclaration(declaration) && getModuleInstanceState(declaration) === 1 /* Instantiated */); } + function getClassificationTypeName(type) { switch (type) { case 1 /* comment */: @@ -133297,23 +118637,16 @@ ${lanes.join("\n")} function getEncodedSyntacticClassifications(cancellationToken, sourceFile, span) { const spanStart = span.start; const spanLength = span.length; - const triviaScanner = createScanner( - 99 /* Latest */, - /*skipTrivia*/ - false, - sourceFile.languageVariant, - sourceFile.text - ); - const mergeConflictScanner = createScanner( - 99 /* Latest */, - /*skipTrivia*/ - false, - sourceFile.languageVariant, - sourceFile.text - ); + const triviaScanner = createScanner(99 /* Latest */, /*skipTrivia*/ + false, sourceFile.languageVariant, sourceFile.text); + const mergeConflictScanner = createScanner(99 /* Latest */, /*skipTrivia*/ + false, sourceFile.languageVariant, sourceFile.text); const result = []; processElement(sourceFile); - return { spans: result, endOfLineState: 0 /* None */ }; + return { + spans: result, + endOfLineState: 0 /* None */ + }; function pushClassification(start, length2, type) { result.push(start); result.push(length2); @@ -133376,6 +118709,7 @@ ${lanes.join("\n")} function pushCommentRange(start, width) { pushClassification(start, width, 1 /* comment */); } + function classifyJSDocComment(docComment) { var _a, _b, _c, _d, _e, _f, _g, _h; let pos = docComment.pos; @@ -133580,21 +118914,25 @@ ${lanes.join("\n")} if (token.parent.tagName === token) { return 19 /* jsxOpenTagName */; } + break; case 287 /* JsxClosingElement */: if (token.parent.tagName === token) { return 20 /* jsxCloseTagName */; } + break; case 285 /* JsxSelfClosingElement */: if (token.parent.tagName === token) { return 21 /* jsxSelfClosingTagName */; } + break; case 291 /* JsxAttribute */: if (token.parent.name === token) { return 22 /* jsxAttribute */; } + break; } return void 0; @@ -133603,11 +118941,13 @@ ${lanes.join("\n")} if (isKeyword(tokenKind)) { return 3 /* keyword */; } + if (tokenKind === 30 /* LessThanToken */ || tokenKind === 32 /* GreaterThanToken */) { if (token && getTypeArgumentOrTypeParameterList(token.parent)) { return 10 /* punctuation */; } } + if (isPunctuation(tokenKind)) { if (token) { const parent2 = token.parent; @@ -133616,10 +118956,12 @@ ${lanes.join("\n")} return 5 /* operator */; } } + if (parent2.kind === 226 /* BinaryExpression */ || parent2.kind === 224 /* PrefixUnaryExpression */ || parent2.kind === 225 /* PostfixUnaryExpression */ || parent2.kind === 227 /* ConditionalExpression */) { return 5 /* operator */; } } + return 10 /* punctuation */; } else if (tokenKind === 9 /* NumericLiteral */) { return 4 /* numericLiteral */; @@ -133640,40 +118982,48 @@ ${lanes.join("\n")} if (token.parent.name === token) { return 11 /* className */; } + return; case 168 /* TypeParameter */: if (token.parent.name === token) { return 15 /* typeParameterName */; } + return; case 264 /* InterfaceDeclaration */: if (token.parent.name === token) { return 13 /* interfaceName */; } + return; case 266 /* EnumDeclaration */: if (token.parent.name === token) { return 12 /* enumName */; } + return; case 267 /* ModuleDeclaration */: if (token.parent.name === token) { return 14 /* moduleName */; } + return; case 169 /* Parameter */: if (token.parent.name === token) { return isThisIdentifier(token) ? 3 /* keyword */ : 17 /* parameterName */; } + return; } if (isConstTypeReference(token.parent)) { return 3 /* keyword */; } } + return 2 /* identifier */; } } + function processElement(element) { if (!element) { return; @@ -133692,26 +119042,9 @@ ${lanes.join("\n")} var init_classifier = __esm({ "src/services/classifier.ts"() { "use strict"; + init_ts4(); - noRegexTable = arrayToNumericMap( - [ - 80 /* Identifier */, - 11 /* StringLiteral */, - 9 /* NumericLiteral */, - 10 /* BigIntLiteral */, - 14 /* RegularExpressionLiteral */, - 110 /* ThisKeyword */, - 46 /* PlusPlusToken */, - 47 /* MinusMinusToken */, - 22 /* CloseParenToken */, - 24 /* CloseBracketToken */, - 20 /* CloseBraceToken */, - 112 /* TrueKeyword */, - 97 /* FalseKeyword */ - ], - (token) => token, - () => true - ); + noRegexTable = arrayToNumericMap([80 /* Identifier */, 11 /* StringLiteral */, 9 /* NumericLiteral */, 10 /* BigIntLiteral */, 14 /* RegularExpressionLiteral */, 110 /* ThisKeyword */, 46 /* PlusPlusToken */, 47 /* MinusMinusToken */, 22 /* CloseParenToken */, 24 /* CloseBracketToken */, 20 /* CloseBraceToken */, 112 /* TrueKeyword */, 97 /* FalseKeyword */], token => token, () => true); } }); @@ -133720,14 +119053,23 @@ ${lanes.join("\n")} var init_documentHighlights = __esm({ "src/services/documentHighlights.ts"() { "use strict"; + init_ts4(); - ((DocumentHighlights3) => { + (DocumentHighlights3 => { function getDocumentHighlights(program, cancellationToken, sourceFile, position, sourceFilesToSearch) { const node = getTouchingPropertyName(sourceFile, position); if (node.parent && (isJsxOpeningElement(node.parent) && node.parent.tagName === node || isJsxClosingElement(node.parent))) { - const { openingElement, closingElement } = node.parent.parent; - const highlightSpans = [openingElement, closingElement].map(({ tagName }) => getHighlightSpanForNode(tagName, sourceFile)); - return [{ fileName: sourceFile.fileName, highlightSpans }]; + const { + openingElement, + closingElement + } = node.parent.parent; + const highlightSpans = [openingElement, closingElement].map(({ + tagName + }) => getHighlightSpanForNode(tagName, sourceFile)); + return [{ + fileName: sourceFile.fileName, + highlightSpans + }]; } return getSemanticDocumentHighlights(position, node, program, cancellationToken, sourceFilesToSearch) || getSyntacticDocumentHighlights(node, sourceFile); } @@ -133739,21 +119081,13 @@ ${lanes.join("\n")} kind: "none" /* none */ }; } + function getSemanticDocumentHighlights(position, node, program, cancellationToken, sourceFilesToSearch) { - const sourceFilesSet = new Set(sourceFilesToSearch.map((f) => f.fileName)); - const referenceEntries = ts_FindAllReferences_exports.getReferenceEntriesForNode( - position, - node, - program, - sourceFilesToSearch, - cancellationToken, - /*options*/ - void 0, - sourceFilesSet - ); - if (!referenceEntries) - return void 0; - const map2 = arrayToMultiMap(referenceEntries.map(ts_FindAllReferences_exports.toHighlightSpan), (e) => e.fileName, (e) => e.span); + const sourceFilesSet = new Set(sourceFilesToSearch.map(f => f.fileName)); + const referenceEntries = ts_FindAllReferences_exports.getReferenceEntriesForNode(position, node, program, sourceFilesToSearch, cancellationToken, /*options*/ + void 0, sourceFilesSet); + 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]) => { if (!sourceFilesSet.has(fileName)) { @@ -133761,16 +119095,22 @@ ${lanes.join("\n")} return void 0; } const redirectTarget = program.getSourceFile(fileName); - const redirect = find(sourceFilesToSearch, (f) => !!f.redirectInfo && f.redirectInfo.redirectTarget === redirectTarget); + const redirect = find(sourceFilesToSearch, f => !!f.redirectInfo && f.redirectInfo.redirectTarget === redirectTarget); fileName = redirect.fileName; Debug.assert(sourceFilesSet.has(fileName)); } - return { fileName, highlightSpans }; + return { + fileName, + highlightSpans + }; })); } function getSyntacticDocumentHighlights(node, sourceFile) { const highlightSpans = getHighlightSpans(node, sourceFile); - return highlightSpans && [{ fileName: sourceFile.fileName, highlightSpans }]; + return highlightSpans && [{ + fileName: sourceFile.fileName, + highlightSpans + }]; } function getHighlightSpans(node, sourceFile) { switch (node.kind) { @@ -133789,23 +119129,21 @@ ${lanes.join("\n")} case 109 /* SwitchKeyword */: return useParent(node.parent, isSwitchStatement, getSwitchCaseDefaultOccurrences); case 84 /* CaseKeyword */: - case 90 /* DefaultKeyword */: { - if (isDefaultClause(node.parent) || isCaseClause(node.parent)) { - return useParent(node.parent.parent.parent, isSwitchStatement, getSwitchCaseDefaultOccurrences); + case 90 /* DefaultKeyword */: + { + if (isDefaultClause(node.parent) || isCaseClause(node.parent)) { + return useParent(node.parent.parent.parent, isSwitchStatement, getSwitchCaseDefaultOccurrences); + } + return void 0; } - return void 0; - } case 83 /* BreakKeyword */: case 88 /* ContinueKeyword */: return useParent(node.parent, isBreakOrContinueStatement, getBreakOrContinueStatementOccurrences); case 99 /* ForKeyword */: case 117 /* WhileKeyword */: case 92 /* DoKeyword */: - return useParent(node.parent, (n) => isIterationStatement( - n, - /*lookInLabeledStatements*/ - true - ), getLoopBreakContinueOccurrences); + return useParent(node.parent, n => isIterationStatement(n, /*lookInLabeledStatements*/ + true), getLoopBreakContinueOccurrences); case 137 /* ConstructorKeyword */: return getFromAllDeclarations(isConstructorDeclaration, [137 /* ConstructorKeyword */]); case 139 /* GetKeyword */: @@ -133823,26 +119161,23 @@ ${lanes.join("\n")} return isModifierKind(node.kind) && (isDeclaration(node.parent) || isVariableStatement(node.parent)) ? highlightSpans(getModifierOccurrences(node.kind, node.parent)) : void 0; } function getFromAllDeclarations(nodeTest, keywords) { - return useParent(node.parent, nodeTest, (decl) => { + return useParent(node.parent, nodeTest, decl => { var _a; - return mapDefined((_a = tryCast(decl, canHaveSymbol)) == null ? void 0 : _a.symbol.declarations, (d) => nodeTest(d) ? find(d.getChildren(sourceFile), (c) => contains(keywords, c.kind)) : void 0); + return mapDefined((_a = tryCast(decl, canHaveSymbol)) == null ? void 0 : _a.symbol.declarations, d => nodeTest(d) ? find(d.getChildren(sourceFile), c => contains(keywords, c.kind)) : void 0); }); } function useParent(node2, nodeTest, getNodes4) { return nodeTest(node2) ? highlightSpans(getNodes4(node2, sourceFile)) : void 0; } function highlightSpans(nodes) { - return nodes && nodes.map((node2) => getHighlightSpanForNode(node2, sourceFile)); + return nodes && nodes.map(node2 => getHighlightSpanForNode(node2, sourceFile)); } } function aggregateOwnedThrowStatements(node) { if (isThrowStatement(node)) { return [node]; } else if (isTryStatement(node)) { - return concatenate( - node.catchClause ? aggregateOwnedThrowStatements(node.catchClause) : node.tryBlock && aggregateOwnedThrowStatements(node.tryBlock), - node.finallyBlock && aggregateOwnedThrowStatements(node.finallyBlock) - ); + return concatenate(node.catchClause ? aggregateOwnedThrowStatements(node.catchClause) : node.tryBlock && aggregateOwnedThrowStatements(node.tryBlock), node.finallyBlock && aggregateOwnedThrowStatements(node.finallyBlock)); } return isFunctionLike(node) ? void 0 : flatMapChildren(node, aggregateOwnedThrowStatements); } @@ -133865,7 +119200,7 @@ ${lanes.join("\n")} } function flatMapChildren(node, cb) { const result = []; - node.forEachChild((child) => { + node.forEachChild(child => { const value = cb(child); if (value !== void 0) { result.push(...toArray(value)); @@ -133878,7 +119213,7 @@ ${lanes.join("\n")} return !!actualOwner && actualOwner === owner; } function getBreakOrContinueOwner(statement) { - return findAncestor(statement, (node) => { + return findAncestor(statement, node => { switch (node.kind) { case 255 /* SwitchStatement */: if (statement.kind === 251 /* ContinueStatement */) { @@ -133896,7 +119231,7 @@ ${lanes.join("\n")} }); } function getModifierOccurrences(modifier, declaration) { - return mapDefined(getNodesToSearchForModifier(declaration, modifierToFlag(modifier)), (node) => findModifier(node, modifier)); + return mapDefined(getNodesToSearchForModifier(declaration, modifierToFlag(modifier)), node => findModifier(node, modifier)); } function getNodesToSearchForModifier(declaration, modifierFlag) { const container = declaration.parent; @@ -133914,7 +119249,7 @@ ${lanes.join("\n")} case 176 /* Constructor */: case 174 /* MethodDeclaration */: case 262 /* FunctionDeclaration */: - return [...container.parameters, ...isClassLike(container.parent) ? container.parent.members : []]; + return [...container.parameters, ...(isClassLike(container.parent) ? container.parent.members : [])]; case 263 /* ClassDeclaration */: case 231 /* ClassExpression */: case 264 /* InterfaceDeclaration */: @@ -133954,11 +119289,12 @@ ${lanes.join("\n")} } } } - forEach(aggregateAllBreakAndContinueStatements(loopNode.statement), (statement) => { + forEach(aggregateAllBreakAndContinueStatements(loopNode.statement), statement => { if (ownsBreakOrContinueStatement(loopNode, statement)) { pushKeywordIf(keywords, statement.getFirstToken(), 83 /* BreakKeyword */, 88 /* ContinueKeyword */); } }); + return keywords; } function getBreakOrContinueStatementOccurrences(breakOrContinueStatement) { @@ -133980,14 +119316,15 @@ ${lanes.join("\n")} function getSwitchCaseDefaultOccurrences(switchStatement) { const keywords = []; pushKeywordIf(keywords, switchStatement.getFirstToken(), 109 /* SwitchKeyword */); - forEach(switchStatement.caseBlock.clauses, (clause) => { + forEach(switchStatement.caseBlock.clauses, clause => { pushKeywordIf(keywords, clause.getFirstToken(), 84 /* CaseKeyword */, 90 /* DefaultKeyword */); - forEach(aggregateAllBreakAndContinueStatements(clause), (statement) => { + forEach(aggregateAllBreakAndContinueStatements(clause), statement => { if (ownsBreakOrContinueStatement(switchStatement, statement)) { pushKeywordIf(keywords, statement.getFirstToken(), 83 /* BreakKeyword */); } }); }); + return keywords; } function getTryCatchFinallyOccurrences(tryStatement, sourceFile) { @@ -133996,10 +119333,12 @@ ${lanes.join("\n")} if (tryStatement.catchClause) { pushKeywordIf(keywords, tryStatement.catchClause.getFirstToken(), 85 /* CatchKeyword */); } + if (tryStatement.finallyBlock) { const finallyKeyword = findChildOfKind(tryStatement, 98 /* FinallyKeyword */, sourceFile); pushKeywordIf(keywords, finallyKeyword, 98 /* FinallyKeyword */); } + return keywords; } function getThrowOccurrences(throwStatement, sourceFile) { @@ -134008,11 +119347,11 @@ ${lanes.join("\n")} return void 0; } const keywords = []; - forEach(aggregateOwnedThrowStatements(owner), (throwStatement2) => { + forEach(aggregateOwnedThrowStatements(owner), throwStatement2 => { keywords.push(findChildOfKind(throwStatement2, 111 /* ThrowKeyword */, sourceFile)); }); if (isFunctionBlock(owner)) { - forEachReturnStatement(owner, (returnStatement) => { + forEachReturnStatement(owner, returnStatement => { keywords.push(findChildOfKind(returnStatement, 107 /* ReturnKeyword */, sourceFile)); }); } @@ -134024,10 +119363,10 @@ ${lanes.join("\n")} return void 0; } const keywords = []; - forEachReturnStatement(cast(func.body, isBlock), (returnStatement2) => { + forEachReturnStatement(cast(func.body, isBlock), returnStatement2 => { keywords.push(findChildOfKind(returnStatement2, 107 /* ReturnKeyword */, sourceFile)); }); - forEach(aggregateOwnedThrowStatements(func.body), (throwStatement) => { + forEach(aggregateOwnedThrowStatements(func.body), throwStatement => { keywords.push(findChildOfKind(throwStatement, 111 /* ThrowKeyword */, sourceFile)); }); return keywords; @@ -134039,17 +119378,19 @@ ${lanes.join("\n")} } const keywords = []; if (func.modifiers) { - func.modifiers.forEach((modifier) => { + func.modifiers.forEach(modifier => { pushKeywordIf(keywords, modifier, 134 /* AsyncKeyword */); }); } - forEachChild(func, (child) => { - traverseWithoutCrossingFunction(child, (node2) => { + + forEachChild(func, child => { + traverseWithoutCrossingFunction(child, node2 => { if (isAwaitExpression(node2)) { pushKeywordIf(keywords, node2.getFirstToken(), 135 /* AwaitKeyword */); } }); }); + return keywords; } function getYieldOccurrences(node) { @@ -134058,19 +119399,20 @@ ${lanes.join("\n")} return void 0; } const keywords = []; - forEachChild(func, (child) => { - traverseWithoutCrossingFunction(child, (node2) => { + forEachChild(func, child => { + traverseWithoutCrossingFunction(child, node2 => { if (isYieldExpression(node2)) { pushKeywordIf(keywords, node2.getFirstToken(), 127 /* YieldKeyword */); } }); }); + return keywords; } function traverseWithoutCrossingFunction(node, cb) { cb(node); if (!isFunctionLike(node) && !isClassLike(node) && !isInterfaceDeclaration(node) && !isModuleDeclaration(node) && !isTypeAliasDeclaration(node) && !isTypeNode(node)) { - forEachChild(node, (child) => traverseWithoutCrossingFunction(child, cb)); + forEachChild(node, child => traverseWithoutCrossingFunction(child, cb)); } } function getIfElseOccurrences(ifStatement, sourceFile) { @@ -134093,6 +119435,7 @@ ${lanes.join("\n")} textSpan: createTextSpanFromBounds(elseKeyword.getStart(), ifKeyword.end), kind: "reference" /* reference */ }); + i++; continue; } @@ -134122,7 +119465,7 @@ ${lanes.join("\n")} return keywords; } function isLabeledBy(node, labelName) { - return !!findAncestor(node.parent, (owner) => !isLabeledStatement(owner) ? "quit" : owner.label.escapedText === labelName); + return !!findAncestor(node.parent, owner => !isLabeledStatement(owner) ? "quit" : owner.label.escapedText === labelName); } })(DocumentHighlights || (DocumentHighlights = {})); } @@ -134136,10 +119479,10 @@ ${lanes.join("\n")} return createDocumentRegistryInternal(useCaseSensitiveFileNames2, currentDirectory, jsDocParsingMode); } function createDocumentRegistryInternal(useCaseSensitiveFileNames2, currentDirectory = "", jsDocParsingMode, externalCache) { - const buckets = /* @__PURE__ */ new Map(); + const buckets = /* @__PURE__ */new Map(); const getCanonicalFileName = createGetCanonicalFileName(!!useCaseSensitiveFileNames2); function reportStats() { - const bucketInfoArray = arrayFrom(buckets.keys()).filter((name) => name && name.charAt(0) === "_").map((name) => { + const bucketInfoArray = arrayFrom(buckets.keys()).filter(name => name && name.charAt(0) === "_").map(name => { const entries = buckets.get(name); const sourceFiles = []; entries.forEach((entry, name2) => { @@ -134150,7 +119493,11 @@ ${lanes.join("\n")} refCount: entry.languageServiceRefCount }); } else { - entry.forEach((value, scriptKind) => sourceFiles.push({ name: name2, scriptKind, refCount: value.languageServiceRefCount })); + entry.forEach((value, scriptKind) => sourceFiles.push({ + name: name2, + scriptKind, + refCount: value.languageServiceRefCount + })); } }); sourceFiles.sort((x, y) => y.refCount - x.refCount); @@ -134173,18 +119520,8 @@ ${lanes.join("\n")} return acquireDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version2, scriptKind, languageVersionOrOptions); } function acquireDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version2, scriptKind, languageVersionOrOptions) { - return acquireOrUpdateDocument( - fileName, - path, - compilationSettings, - key, - scriptSnapshot, - version2, - /*acquiring*/ - true, - scriptKind, - languageVersionOrOptions - ); + return acquireOrUpdateDocument(fileName, path, compilationSettings, key, scriptSnapshot, version2, /*acquiring*/ + true, scriptKind, languageVersionOrOptions); } function updateDocument(fileName, compilationSettings, scriptSnapshot, version2, scriptKind, languageVersionOrOptions) { const path = toPath(fileName, currentDirectory, getCanonicalFileName); @@ -134192,18 +119529,8 @@ ${lanes.join("\n")} return updateDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version2, scriptKind, languageVersionOrOptions); } function updateDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version2, scriptKind, languageVersionOrOptions) { - return acquireOrUpdateDocument( - fileName, - path, - getCompilationSettings(compilationSettings), - key, - scriptSnapshot, - version2, - /*acquiring*/ - false, - scriptKind, - languageVersionOrOptions - ); + return acquireOrUpdateDocument(fileName, path, getCompilationSettings(compilationSettings), key, scriptSnapshot, version2, /*acquiring*/ + false, scriptKind, languageVersionOrOptions); } function getDocumentRegistryEntry(bucketEntry, scriptKind) { const entry = isDocumentRegistryEntry(bucketEntry) ? bucketEntry : bucketEntry.get(Debug.checkDefined(scriptKind, "If there are more than one scriptKind's for same document the scriptKind should be provided")); @@ -134226,14 +119553,21 @@ ${lanes.join("\n")} Debug.assertEqual(jsDocParsingMode, sourceFileOptions.jsDocParsingMode); const oldBucketCount = buckets.size; const keyWithMode = getDocumentRegistryBucketKeyWithMode(key, sourceFileOptions.impliedNodeFormat); - const bucket = getOrUpdate(buckets, keyWithMode, () => /* @__PURE__ */ new Map()); + const bucket = getOrUpdate(buckets, keyWithMode, () => /* @__PURE__ */new Map()); if (tracing) { if (buckets.size > oldBucketCount) { - tracing.instant(tracing.Phase.Session, "createdDocumentRegistryBucket", { configFilePath: compilationSettings.configFilePath, key: keyWithMode }); + tracing.instant(tracing.Phase.Session, "createdDocumentRegistryBucket", { + configFilePath: compilationSettings.configFilePath, + key: keyWithMode + }); } const otherBucketKey = !isDeclarationFileName(path) && forEachEntry(buckets, (bucket2, bucketKey) => bucketKey !== keyWithMode && bucket2.has(path) && bucketKey); if (otherBucketKey) { - tracing.instant(tracing.Phase.Session, "documentRegistryBucketOverlap", { path, key1: otherBucketKey, key2: keyWithMode }); + tracing.instant(tracing.Phase.Session, "documentRegistryBucketOverlap", { + path, + key1: otherBucketKey, + key2: keyWithMode + }); } } const bucketEntry = bucket.get(path); @@ -134250,15 +119584,8 @@ ${lanes.join("\n")} } } if (!entry) { - const sourceFile = createLanguageServiceSourceFile( - fileName, - scriptSnapshot, - sourceFileOptions, - version2, - /*setNodeParents*/ - false, - scriptKind - ); + const sourceFile = createLanguageServiceSourceFile(fileName, scriptSnapshot, sourceFileOptions, version2, /*setNodeParents*/ + false, scriptKind); if (externalCache) { externalCache.setDocument(keyWithMode, path, sourceFile); } @@ -134284,7 +119611,7 @@ ${lanes.join("\n")} if (!bucketEntry) { bucket.set(path, entry); } else if (isDocumentRegistryEntry(bucketEntry)) { - const scriptKindMap = /* @__PURE__ */ new Map(); + const scriptKindMap = /* @__PURE__ */new Map(); scriptKindMap.set(bucketEntry.sourceFile.scriptKind, bucketEntry); scriptKindMap.set(scriptKind, entry); bucket.set(path, scriptKindMap); @@ -134337,6 +119664,7 @@ ${lanes.join("\n")} var init_documentRegistry = __esm({ "src/services/documentRegistry.ts"() { "use strict"; + init_ts4(); } }); @@ -134347,21 +119675,27 @@ ${lanes.join("\n")} const getCanonicalFileName = createGetCanonicalFileName(useCaseSensitiveFileNames2); const oldToNew = getPathUpdater(oldFileOrDirPath, newFileOrDirPath, getCanonicalFileName, sourceMapper); const newToOld = getPathUpdater(newFileOrDirPath, oldFileOrDirPath, getCanonicalFileName, sourceMapper); - return ts_textChanges_exports.ChangeTracker.with({ host, formatContext, preferences }, (changeTracker) => { + return ts_textChanges_exports.ChangeTracker.with({ + host, + formatContext, + preferences + }, changeTracker => { updateTsconfigFiles(program, changeTracker, oldToNew, oldFileOrDirPath, newFileOrDirPath, host.getCurrentDirectory(), useCaseSensitiveFileNames2); updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName); }); } function getPathUpdater(oldFileOrDirPath, newFileOrDirPath, getCanonicalFileName, sourceMapper) { const canonicalOldPath = getCanonicalFileName(oldFileOrDirPath); - return (path) => { - const originalPath = sourceMapper && sourceMapper.tryGetSourcePosition({ fileName: path, pos: 0 }); + return path => { + const originalPath = sourceMapper && sourceMapper.tryGetSourcePosition({ + fileName: path, + pos: 0 + }); const updatedPath = getUpdatedPath(originalPath ? originalPath.fileName : path); 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; } @@ -134371,37 +119705,30 @@ ${lanes.join("\n")} return combinePathsSafe(getDirectoryPath(a1), rel); } function updateTsconfigFiles(program, changeTracker, oldToNew, oldFileOrDirPath, newFileOrDirPath, currentDirectory, useCaseSensitiveFileNames2) { - const { configFile } = program.getCompilerOptions(); - if (!configFile) - return; + const { + configFile + } = program.getCompilerOptions(); + 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)) + case "exclude": + { + const foundExactMatch = updatePaths(property); + if (foundExactMatch || propertyName !== "include" || !isArrayLiteralExpression(property.initializer)) return; + const includes = mapDefined(property.initializer.elements, e => isStringLiteral(e) ? e.text : void 0); + if (includes.length === 0) return; + const matchers = getFileMatcherPatterns(configDir, /*excludes*/ + [], includes, useCaseSensitiveFileNames2, currentDirectory); + if (getRegexFromPattern(Debug.checkDefined(matchers.includeFilePattern), useCaseSensitiveFileNames2).test(oldFileOrDirPath) && !getRegexFromPattern(Debug.checkDefined(matchers.includeFilePattern), useCaseSensitiveFileNames2).test(newFileOrDirPath)) { + changeTracker.insertNodeAfter(configFile, last(property.initializer.elements), factory.createStringLiteral(relativePath(newFileOrDirPath))); + } return; - const includes = mapDefined(property.initializer.elements, (e) => isStringLiteral(e) ? e.text : void 0); - if (includes.length === 0) - return; - const matchers = getFileMatcherPatterns( - configDir, - /*excludes*/ - [], - includes, - useCaseSensitiveFileNames2, - currentDirectory - ); - if (getRegexFromPattern(Debug.checkDefined(matchers.includeFilePattern), useCaseSensitiveFileNames2).test(oldFileOrDirPath) && !getRegexFromPattern(Debug.checkDefined(matchers.includeFilePattern), useCaseSensitiveFileNames2).test(newFileOrDirPath)) { - changeTracker.insertNodeAfter(configFile, last(property.initializer.elements), factory.createStringLiteral(relativePath(newFileOrDirPath))); } - return; - } case "compilerOptions": forEachProperty(property.initializer, (property2, propertyName2) => { const option = getOptionFromName(propertyName2); @@ -134409,9 +119736,8 @@ ${lanes.join("\n")} if (option && (option.isFilePath || option.type === "list" && option.element.isFilePath)) { updatePaths(property2); } else if (propertyName2 === "paths") { - forEachProperty(property2.initializer, (pathsProperty) => { - if (!isArrayLiteralExpression(pathsProperty.initializer)) - return; + forEachProperty(property2.initializer, pathsProperty => { + if (!isArrayLiteralExpression(pathsProperty.initializer)) return; for (const e of pathsProperty.initializer.elements) { tryUpdateString(e); } @@ -134430,8 +119756,7 @@ ${lanes.join("\n")} 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) { @@ -134441,34 +119766,28 @@ ${lanes.join("\n")} return false; } function relativePath(path) { - return getRelativePathFromDirectory( - configDir, - path, - /*ignoreCase*/ - !useCaseSensitiveFileNames2 - ); + return getRelativePathFromDirectory(configDir, path, /*ignoreCase*/ + !useCaseSensitiveFileNames2); } } function updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName) { const allFiles = program.getSourceFiles(); for (const sourceFile of allFiles) { const newFromOld = oldToNew(sourceFile.fileName); - const newImportFromPath = newFromOld ?? sourceFile.fileName; + const newImportFromPath = newFromOld !== null && newFromOld !== void 0 ? newFromOld : sourceFile.fileName; const newImportFromDirectory = getDirectoryPath(newImportFromPath); const oldFromNew = newToOld(sourceFile.fileName); const oldImportFromPath = oldFromNew || sourceFile.fileName; const oldImportFromDirectory = getDirectoryPath(oldImportFromPath); const importingSourceFileMoved = newFromOld !== void 0 || oldFromNew !== void 0; - updateImportsWorker(sourceFile, changeTracker, (referenceText) => { - if (!pathIsRelative(referenceText)) - return void 0; + updateImportsWorker(sourceFile, changeTracker, referenceText => { + 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) => { + }, 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, getCanonicalFileName(newImportFromPath), toImport.newFileName, createModuleSpecifierResolutionHost(program, host), importLiteral.text) : void 0; }); @@ -134484,7 +119803,13 @@ ${lanes.join("\n")} if (importedModuleSymbol) { const oldFileName = find(importedModuleSymbol.declarations, isSourceFile).fileName; const newFileName = oldToNew(oldFileName); - return newFileName === void 0 ? { newFileName: oldFileName, updated: false } : { newFileName, updated: true }; + return newFileName === void 0 ? { + newFileName: oldFileName, + updated: false + } : { + newFileName, + updated: true + }; } else { const mode = getModeForUsageLocation(importingSourceFile, importLiteral); const resolved = host.resolveModuleNameLiterals || !host.resolveModuleNames ? program.getResolvedModule(importingSourceFile, importLiteral.text, mode) : host.getResolvedModuleWithFailedLookupLocationsFromCache && host.getResolvedModuleWithFailedLookupLocationsFromCache(importLiteral.text, importingSourceFile.fileName, mode); @@ -134492,47 +119817,47 @@ ${lanes.join("\n")} } } 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; - return resolved.resolvedModule && { newFileName: resolved.resolvedModule.resolvedFileName, updated: false }; + if (result) return result; + return resolved.resolvedModule && { + newFileName: resolved.resolvedModule.resolvedFileName, + updated: false + }; function tryChangeWithIgnoringPackageJsonExisting(oldFileName) { const newFileName = oldToNew(oldFileName); - return newFileName && find(sourceFiles, (src) => src.fileName === newFileName) ? tryChangeWithIgnoringPackageJson(oldFileName) : void 0; + return newFileName && find(sourceFiles, src => src.fileName === newFileName) ? tryChangeWithIgnoringPackageJson(oldFileName) : void 0; } function tryChangeWithIgnoringPackageJson(oldFileName) { return !endsWith(oldFileName, "/package.json") ? tryChange(oldFileName) : void 0; } function tryChange(oldFileName) { const newFileName = oldToNew(oldFileName); - return newFileName && { newFileName, updated: true }; + return newFileName && { + newFileName, + updated: true + }; } } function updateImportsWorker(sourceFile, changeTracker, updateRef, updateImport2) { 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 = updateImport2(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); @@ -134542,6 +119867,7 @@ ${lanes.join("\n")} var init_getEditsForFileRename = __esm({ "src/services/getEditsForFileRename.ts"() { "use strict"; + init_ts4(); } }); @@ -134554,28 +119880,21 @@ ${lanes.join("\n")} }; } function createPatternMatcher(pattern) { - const stringToWordSpans = /* @__PURE__ */ new Map(); - const dotSeparatedSegments = pattern.trim().split(".").map((p) => createSegment(p.trim())); + const stringToWordSpans = /* @__PURE__ */new Map(); + const dotSeparatedSegments = pattern.trim().split(".").map(p => createSegment(p.trim())); if (dotSeparatedSegments.length === 1 && dotSeparatedSegments[0].totalTextChunk.text === "") { return { - getMatchForLastSegmentOfPattern: () => createPatternMatch( - 2 /* substring */, - /*isCaseSensitive*/ - true - ), - getFullMatch: () => createPatternMatch( - 2 /* substring */, - /*isCaseSensitive*/ - true - ), + getMatchForLastSegmentOfPattern: () => createPatternMatch(2 /* substring */, /*isCaseSensitive*/ + true), + getFullMatch: () => createPatternMatch(2 /* substring */, /*isCaseSensitive*/ + true), 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), + getMatchForLastSegmentOfPattern: candidate => matchSegment(candidate, last(dotSeparatedSegments), stringToWordSpans), patternContainsDots: dotSeparatedSegments.length > 1 }; } @@ -134603,67 +119922,34 @@ ${lanes.join("\n")} function matchTextChunk(candidate, chunk, stringToWordSpans) { const index = indexOfIgnoringCase(candidate, chunk.textLowerCase); if (index === 0) { - return createPatternMatch( - chunk.text.length === candidate.length ? 0 /* exact */ : 1 /* prefix */, - /*isCaseSensitive:*/ - startsWith(candidate, chunk.text) - ); + return createPatternMatch(chunk.text.length === candidate.length ? 0 /* exact */ : 1 /* prefix */, /*isCaseSensitive:*/ + startsWith(candidate, chunk.text)); } 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( - candidate, - span, - chunk.text, - /*ignoreCase*/ - true - )) { - return createPatternMatch( - 2 /* substring */, - /*isCaseSensitive:*/ - partStartsWith( - candidate, - span, - chunk.text, - /*ignoreCase*/ - false - ) - ); + if (partStartsWith(candidate, span, chunk.text, /*ignoreCase*/ + true)) { + return createPatternMatch(2 /* substring */, /*isCaseSensitive:*/ + partStartsWith(candidate, span, chunk.text, /*ignoreCase*/ + false)); } } if (chunk.text.length < candidate.length && isUpperCaseLetter(candidate.charCodeAt(index))) { - return createPatternMatch( - 2 /* substring */, - /*isCaseSensitive*/ - false - ); + return createPatternMatch(2 /* substring */, /*isCaseSensitive*/ + false); } } else { if (candidate.indexOf(chunk.text) > 0) { - return createPatternMatch( - 2 /* substring */, - /*isCaseSensitive*/ - true - ); + return createPatternMatch(2 /* substring */, /*isCaseSensitive*/ + true); } if (chunk.characterSpans.length > 0) { const candidateParts = getWordSpans(candidate, stringToWordSpans); - const isCaseSensitive = tryCamelCaseMatch( - candidate, - candidateParts, - chunk, - /*ignoreCase*/ - false - ) ? true : tryCamelCaseMatch( - candidate, - candidateParts, - chunk, - /*ignoreCase*/ - true - ) ? false : void 0; + const isCaseSensitive = tryCamelCaseMatch(candidate, candidateParts, chunk, /*ignoreCase*/ + false) ? true : tryCamelCaseMatch(candidate, candidateParts, chunk, /*ignoreCase*/ + true) ? false : void 0; if (isCaseSensitive !== void 0) { return createPatternMatch(3 /* camelCase */, isCaseSensitive); } @@ -134671,10 +119957,9 @@ ${lanes.join("\n")} } } function matchSegment(candidate, segment, stringToWordSpans) { - if (every2(segment.totalTextChunk.text, (ch) => ch !== 32 /* space */ && ch !== 42 /* asterisk */)) { + 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; @@ -134689,8 +119974,11 @@ ${lanes.join("\n")} function compareMatches(a, b) { return a === void 0 ? 1 /* GreaterThan */ : b === void 0 ? -1 /* LessThan */ : compareValues(a.kind, b.kind) || compareBooleans(!a.isCaseSensitive, !b.isCaseSensitive); } - function partStartsWith(candidate, candidateSpan, pattern, ignoreCase, patternSpan = { start: 0, length: pattern.length }) { - return patternSpan.length <= candidateSpan.length && everyInRange(0, patternSpan.length, (i) => equalChars(pattern.charCodeAt(patternSpan.start + i), candidate.charCodeAt(candidateSpan.start + i), ignoreCase)); + function partStartsWith(candidate, candidateSpan, pattern, ignoreCase, patternSpan = { + start: 0, + length: pattern.length + }) { + return patternSpan.length <= candidateSpan.length && everyInRange(0, patternSpan.length, i => equalChars(pattern.charCodeAt(patternSpan.start + i), candidate.charCodeAt(candidateSpan.start + i), ignoreCase)); } function equalChars(ch1, ch2, ignoreCase) { return ignoreCase ? toLowerCase2(ch1) === toLowerCase2(ch2) : ch1 === ch2; @@ -134769,6 +120057,7 @@ ${lanes.join("\n")} if (ch >= 65 /* A */ && ch <= 90 /* Z */) { return 97 /* a */ + (ch - 65 /* A */); } + if (ch < 127 /* maxAsciiCharacter */) { return ch; } @@ -134777,9 +120066,11 @@ ${lanes.join("\n")} function isDigit2(ch) { return ch >= 48 /* _0 */ && ch <= 57 /* _9 */; } + function isWordChar(ch) { return isUpperCaseLetter(ch) || isLowerCaseLetter(ch) || isDigit2(ch) || ch === 95 /* _ */ || ch === 36 /* $ */; } + function breakPatternIntoTextChunks(pattern) { const result = []; let wordStart = 0; @@ -134813,18 +120104,12 @@ ${lanes.join("\n")} }; } function breakIntoCharacterSpans(identifier) { - return breakIntoSpans( - identifier, - /*word*/ - false - ); + return breakIntoSpans(identifier, /*word*/ + false); } function breakIntoWordSpans(identifier) { - return breakIntoSpans( - identifier, - /*word*/ - true - ); + return breakIntoSpans(identifier, /*word*/ + true); } function breakIntoSpans(identifier, word) { const result = []; @@ -134876,7 +120161,7 @@ ${lanes.join("\n")} return false; } function isAllPunctuation(identifier, start, end) { - return every2(identifier, (ch) => charIsPunctuation(ch) && ch !== 95 /* _ */, start, end); + return every2(identifier, ch => charIsPunctuation(ch) && ch !== 95 /* _ */, start, end); } function transitionFromUpperToLower(identifier, index, wordStart) { return index !== wordStart && index + 1 < identifier.length && isUpperCaseLetter(identifier.charCodeAt(index)) && isLowerCaseLetter(identifier.charCodeAt(index + 1)) && every2(identifier, isUpperCaseLetter, wordStart, index); @@ -134895,14 +120180,15 @@ ${lanes.join("\n")} return true; } function every2(s, pred, start = 0, end = s.length) { - return everyInRange(start, end, (i) => pred(s.charCodeAt(i), i)); + return everyInRange(start, end, i => pred(s.charCodeAt(i), i)); } var PatternMatchKind; var init_patternMatcher = __esm({ "src/services/patternMatcher.ts"() { "use strict"; + init_ts4(); - PatternMatchKind = /* @__PURE__ */ ((PatternMatchKind2) => { + PatternMatchKind = /* @__PURE__ */(PatternMatchKind2 => { PatternMatchKind2[PatternMatchKind2["exact"] = 0] = "exact"; PatternMatchKind2[PatternMatchKind2["prefix"] = 1] = "prefix"; PatternMatchKind2[PatternMatchKind2["substring"] = 2] = "substring"; @@ -134916,6 +120202,7 @@ ${lanes.join("\n")} function preProcessFile(sourceText, readImportFiles = true, detectJavaScriptImports = false) { const pragmaContext = { languageVersion: 1 /* ES5 */, + // controls whether the token scanner considers unicode identifiers or not - shouldn't matter, since we're only using it for trivia pragmas: void 0, checkJsDirective: void 0, @@ -134945,13 +120232,20 @@ ${lanes.join("\n")} function getFileReference() { const fileName = scanner.getTokenValue(); const pos = scanner.getTokenStart(); - return { fileName, pos, end: pos + fileName.length }; + return { + fileName, + pos, + end: pos + fileName.length + }; } function recordAmbientExternalModule() { if (!ambientExternalModules) { ambientExternalModules = []; } - ambientExternalModules.push({ ref: getFileReference(), depth: braceNesting }); + ambientExternalModules.push({ + ref: getFileReference(), + depth: braceNesting + }); } function recordModuleName() { importedFiles.push(getFileReference()); @@ -135011,10 +120305,8 @@ ${lanes.join("\n")} return true; } } else if (token === 64 /* EqualsToken */) { - if (tryConsumeRequireCall( - /*skipCurrentToken*/ - true - )) { + if (tryConsumeRequireCall( /*skipCurrentToken*/ + true)) { return true; } } else if (token === 28 /* CommaToken */) { @@ -135067,6 +120359,7 @@ ${lanes.join("\n")} const token2 = scanner.scan(); return token2 === 42 /* AsteriskToken */ || token2 === 19 /* OpenBraceToken */; }); + if (skipTypeKeyword) { token = nextToken(); } @@ -135107,10 +120400,8 @@ ${lanes.join("\n")} if (token === 80 /* Identifier */ || isKeyword(token)) { token = nextToken(); if (token === 64 /* EqualsToken */) { - if (tryConsumeRequireCall( - /*skipCurrentToken*/ - true - )) { + if (tryConsumeRequireCall( /*skipCurrentToken*/ + true)) { return true; } } @@ -135173,47 +120464,41 @@ ${lanes.join("\n")} } if (scanner.getToken() === 16 /* TemplateHead */) { const stack = [scanner.getToken()]; - loop: - while (length(stack)) { - const token = scanner.scan(); - switch (token) { - case 1 /* EndOfFileToken */: - break loop; - case 102 /* ImportKeyword */: - tryConsumeImport(); - break; - case 16 /* TemplateHead */: + loop: while (length(stack)) { + const token = scanner.scan(); + switch (token) { + case 1 /* EndOfFileToken */: + break loop; + case 102 /* ImportKeyword */: + tryConsumeImport(); + break; + case 16 /* TemplateHead */: + stack.push(token); + break; + case 19 /* OpenBraceToken */: + if (length(stack)) { stack.push(token); - break; - case 19 /* OpenBraceToken */: - if (length(stack)) { - stack.push(token); - } - break; - case 20 /* CloseBraceToken */: - if (length(stack)) { - if (lastOrUndefined(stack) === 16 /* TemplateHead */) { - if (scanner.reScanTemplateToken( - /*isTaggedTemplate*/ - false - ) === 18 /* TemplateTail */) { - stack.pop(); - } - } else { + } + break; + case 20 /* CloseBraceToken */: + if (length(stack)) { + if (lastOrUndefined(stack) === 16 /* TemplateHead */) { + if (scanner.reScanTemplateToken( /*isTaggedTemplate*/ + false) === 18 /* TemplateTail */) { stack.pop(); } + } else { + stack.pop(); } - break; - } + } + break; } + } nextToken(); } - if (tryConsumeDeclare() || tryConsumeImport() || tryConsumeExport() || detectJavaScriptImports && (tryConsumeRequireCall( - /*skipCurrentToken*/ - false, - /*allowTemplateLiterals*/ - true - ) || tryConsumeDefine())) { + if (tryConsumeDeclare() || tryConsumeImport() || tryConsumeExport() || detectJavaScriptImports && (tryConsumeRequireCall( /*skipCurrentToken*/ + false, /*allowTemplateLiterals*/ + true) || tryConsumeDefine())) { continue; } else { nextToken(); @@ -135232,7 +120517,14 @@ ${lanes.join("\n")} importedFiles.push(decl.ref); } } - return { referencedFiles: pragmaContext.referencedFiles, typeReferenceDirectives: pragmaContext.typeReferenceDirectives, libReferenceDirectives: pragmaContext.libReferenceDirectives, importedFiles, isLibFile: !!pragmaContext.hasNoDefaultLib, ambientExternalModules: void 0 }; + return { + referencedFiles: pragmaContext.referencedFiles, + typeReferenceDirectives: pragmaContext.typeReferenceDirectives, + libReferenceDirectives: pragmaContext.libReferenceDirectives, + importedFiles, + isLibFile: !!pragmaContext.hasNoDefaultLib, + ambientExternalModules: void 0 + }; } else { let ambientModuleNames; if (ambientExternalModules) { @@ -135247,12 +120539,20 @@ ${lanes.join("\n")} } } } - return { referencedFiles: pragmaContext.referencedFiles, typeReferenceDirectives: pragmaContext.typeReferenceDirectives, libReferenceDirectives: pragmaContext.libReferenceDirectives, importedFiles, isLibFile: !!pragmaContext.hasNoDefaultLib, ambientExternalModules: ambientModuleNames }; + return { + referencedFiles: pragmaContext.referencedFiles, + typeReferenceDirectives: pragmaContext.typeReferenceDirectives, + libReferenceDirectives: pragmaContext.libReferenceDirectives, + importedFiles, + isLibFile: !!pragmaContext.hasNoDefaultLib, + ambientExternalModules: ambientModuleNames + }; } } var init_preProcess = __esm({ "src/services/preProcess.ts"() { "use strict"; + init_ts4(); } }); @@ -135261,47 +120561,46 @@ ${lanes.join("\n")} function getSourceMapper(host) { const getCanonicalFileName = createGetCanonicalFileName(host.useCaseSensitiveFileNames()); const currentDirectory = host.getCurrentDirectory(); - const sourceFileLike = /* @__PURE__ */ new Map(); - const documentPositionMappers = /* @__PURE__ */ new Map(); - return { tryGetSourcePosition, tryGetGeneratedPosition, toLineColumnOffset, clearCache }; + const sourceFileLike = /* @__PURE__ */new Map(); + const documentPositionMappers = /* @__PURE__ */new Map(); + return { + tryGetSourcePosition, + tryGetGeneratedPosition, + toLineColumnOffset, + clearCache + }; function toPath3(fileName) { return toPath(fileName, currentDirectory, getCanonicalFileName); } 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); } else if (host.readFile) { const file = getSourceFileLike(generatedFileName); - mapper = file && getDocumentPositionMapper( - { getSourceFileLike, getCanonicalFileName, log: (s) => host.log(s) }, - generatedFileName, - getLineInfo(file.text, getLineStarts(file)), - (f) => !host.fileExists || host.fileExists(f) ? host.readFile(f) : void 0 - ); + mapper = file && getDocumentPositionMapper({ + getSourceFileLike, + getCanonicalFileName, + log: s => host.log(s) + }, generatedFileName, getLineInfo(file.text, getLineStarts(file)), f => !host.fileExists || host.fileExists(f) ? host.readFile(f) : void 0); } documentPositionMappers.set(path, mapper || identitySourceMapConsumer); 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; @@ -135309,15 +120608,13 @@ ${lanes.join("\n")} const options = program.getCompilerOptions(); const outPath = outFile(options); 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; @@ -135325,8 +120622,7 @@ ${lanes.join("\n")} 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(path)) { sourceFileLike.set(path, false); return void 0; @@ -135383,8 +120679,7 @@ ${lanes.join("\n")} 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) { @@ -135400,6 +120695,7 @@ ${lanes.join("\n")} var init_sourcemaps = __esm({ "src/services/sourcemaps.ts"() { "use strict"; + init_ts4(); base64UrlRegExp = /^data:(?:application\/json(?:;charset=[uU][tT][fF]-8);base64,([A-Za-z0-9+/=]+)$)?/; } @@ -135422,8 +120718,7 @@ ${lanes.join("\n")} for (const moduleSpecifier of sourceFile.imports) { const importNode = importFromModuleSpecifier(moduleSpecifier); const name = importNameForConvertToDefaultImport(importNode); - if (!name) - continue; + if (!name) continue; const module2 = (_a = program.getResolvedModule(sourceFile, moduleSpecifier.text, getModeForUsageLocation(sourceFile, moduleSpecifier))) == 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) { @@ -135442,11 +120737,8 @@ ${lanes.join("\n")} } else { if (isVariableStatement(node) && node.parent === sourceFile && node.declarationList.flags & 2 /* Const */ && node.declarationList.declarations.length === 1) { const init = node.declarationList.declarations[0].initializer; - if (init && isRequireCall( - init, - /*requireStringLiteralLikeArgument*/ - true - )) { + if (init && isRequireCall(init, /*requireStringLiteralLikeArgument*/ + true)) { diags.push(createDiagnosticForNode(init, Diagnostics.require_call_may_be_converted_to_an_import)); } } @@ -135465,25 +120757,22 @@ ${lanes.join("\n")} } } function containsTopLevelCommonjs(sourceFile) { - return sourceFile.statements.some((statement) => { + return sourceFile.statements.some(statement => { switch (statement.kind) { case 243 /* VariableStatement */: - return statement.declarationList.declarations.some((decl) => !!decl.initializer && isRequireCall( - propertyAccessLeftHandSide(decl.initializer), - /*requireStringLiteralLikeArgument*/ - true - )); - case 244 /* ExpressionStatement */: { - const { expression } = statement; - if (!isBinaryExpression(expression)) - return isRequireCall( - expression, - /*requireStringLiteralLikeArgument*/ - true - ); - const kind = getAssignmentDeclarationKind(expression); - return kind === 1 /* ExportsProperty */ || kind === 2 /* ModuleExports */; - } + return statement.declarationList.declarations.some(decl => !!decl.initializer && isRequireCall(propertyAccessLeftHandSide(decl.initializer), /*requireStringLiteralLikeArgument*/ + true)); + case 244 /* ExpressionStatement */: + { + const { + expression + } = statement; + if (!isBinaryExpression(expression)) return isRequireCall(expression, /*requireStringLiteralLikeArgument*/ + true); + const kind = getAssignmentDeclarationKind(expression); + return kind === 1 /* ExportsProperty */ || kind === 2 /* ModuleExports */; + } + default: return false; } @@ -135495,7 +120784,10 @@ ${lanes.join("\n")} function importNameForConvertToDefaultImport(node) { switch (node.kind) { case 272 /* ImportDeclaration */: - const { importClause, moduleSpecifier } = node; + const { + importClause, + moduleSpecifier + } = node; return importClause && !importClause.name && importClause.namedBindings && importClause.namedBindings.kind === 274 /* NamespaceImport */ && isStringLiteral(moduleSpecifier) ? importClause.namedBindings.name : void 0; case 271 /* ImportEqualsDeclaration */: return node.name; @@ -135505,10 +120797,7 @@ ${lanes.join("\n")} } function addConvertToAsyncFunctionDiagnostics(node, checker, diags) { if (isConvertibleFunction(node, checker) && !visitedNestedConvertibleFunctions.has(getKeyFromNode(node))) { - diags.push(createDiagnosticForNode( - !node.name && isVariableDeclaration(node.parent) && isIdentifier(node.parent.name) ? node.parent.name : node, - Diagnostics.This_may_be_converted_to_an_async_function - )); + diags.push(createDiagnosticForNode(!node.name && isVariableDeclaration(node.parent) && isIdentifier(node.parent.name) ? node.parent.name : node, Diagnostics.This_may_be_converted_to_an_async_function)); } } function isConvertibleFunction(node, checker) { @@ -135523,19 +120812,19 @@ ${lanes.join("\n")} return isBinaryExpression(commonJsModuleIndicator) ? commonJsModuleIndicator.left : commonJsModuleIndicator; } function hasReturnStatementWithPromiseHandler(body, checker) { - return !!forEachReturnStatement(body, (statement) => isReturnStatementWithFixablePromiseHandler(statement, checker)); + return !!forEachReturnStatement(body, statement => isReturnStatementWithFixablePromiseHandler(statement, checker)); } function isReturnStatementWithFixablePromiseHandler(node, checker) { return isReturnStatement(node) && !!node.expression && isFixablePromiseHandler(node.expression, checker); } function isFixablePromiseHandler(node, checker) { - if (!isPromiseHandler(node) || !hasSupportedNumberOfArguments(node) || !node.arguments.every((arg) => isFixablePromiseArgument(arg, checker))) { + if (!isPromiseHandler(node) || !hasSupportedNumberOfArguments(node) || !node.arguments.every(arg => isFixablePromiseArgument(arg, checker))) { return false; } let currentNode = node.expression.expression; while (isPromiseHandler(currentNode) || isPropertyAccessExpression(currentNode)) { if (isCallExpression(currentNode)) { - if (!hasSupportedNumberOfArguments(currentNode) || !currentNode.arguments.every((arg) => isFixablePromiseArgument(arg, checker))) { + if (!hasSupportedNumberOfArguments(currentNode) || !currentNode.arguments.every(arg => isFixablePromiseArgument(arg, checker))) { return false; } currentNode = currentNode.expression.expression; @@ -135551,11 +120840,9 @@ ${lanes.join("\n")} 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; - return maxArguments === 1 || some(node.arguments, (arg) => { + 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"; }); } @@ -135572,13 +120859,14 @@ ${lanes.join("\n")} case 106 /* NullKeyword */: return true; case 80 /* Identifier */: - case 211 /* PropertyAccessExpression */: { - const symbol = checker.getSymbolAtLocation(arg); - if (!symbol) { - return false; + case 211 /* PropertyAccessExpression */: + { + const symbol = checker.getSymbolAtLocation(arg); + if (!symbol) { + return false; + } + return checker.isUndefinedSymbol(symbol) || some(skipAlias(symbol, checker).declarations, d => isFunctionLike(d) || hasInitializer(d) && !!d.initializer && isFunctionLike(d.initializer)); } - return checker.isUndefinedSymbol(symbol) || some(skipAlias(symbol, checker).declarations, (d) => isFunctionLike(d) || hasInitializer(d) && !!d.initializer && isFunctionLike(d.initializer)); - } default: return false; } @@ -135592,11 +120880,8 @@ ${lanes.join("\n")} if (isVariableDeclaration(node.parent) && ((_a = node.symbol.members) == null ? void 0 : _a.size)) { return true; } - const symbol = checker.getSymbolOfExpando( - node, - /*allowDeclaration*/ - false - ); + const symbol = checker.getSymbolOfExpando(node, /*allowDeclaration*/ + false); return !!(symbol && (((_b = symbol.exports) == null ? void 0 : _b.size) || ((_c = symbol.members) == null ? void 0 : _c.size))); } if (isFunctionDeclaration(node)) { @@ -135619,13 +120904,15 @@ ${lanes.join("\n")} var init_suggestionDiagnostics = __esm({ "src/services/suggestionDiagnostics.ts"() { "use strict"; + init_ts4(); - visitedNestedConvertibleFunctions = /* @__PURE__ */ new Map(); + visitedNestedConvertibleFunctions = /* @__PURE__ */new Map(); } }); // src/services/transpile.ts function transpileModule(input, transpileOptions) { + var _transpileOptions$jsD; const diagnostics = []; const options = transpileOptions.compilerOptions ? fixupCompilerOptions(transpileOptions.compilerOptions, diagnostics) : {}; const defaultOptions = getDefaultCompilerOptions2(); @@ -135644,7 +120931,7 @@ ${lanes.join("\n")} options.allowNonTsExtensions = true; const newLine = getNewLineCharacter(options); const compilerHost = { - getSourceFile: (fileName) => fileName === normalizePath(inputFileName) ? sourceFile : void 0, + getSourceFile: fileName => fileName === normalizePath(inputFileName) ? sourceFile : void 0, writeFile: (name, text) => { if (fileExtensionIs(name, ".map")) { Debug.assertEqual(sourceMapText, void 0, "Unexpected multiple source map outputs, file:", name); @@ -135656,31 +120943,23 @@ ${lanes.join("\n")} }, getDefaultLibFileName: () => "lib.d.ts", useCaseSensitiveFileNames: () => false, - getCanonicalFileName: (fileName) => fileName, + getCanonicalFileName: fileName => fileName, getCurrentDirectory: () => "", getNewLine: () => newLine, - fileExists: (fileName) => fileName === inputFileName, + fileExists: fileName => fileName === inputFileName, readFile: () => "", directoryExists: () => true, getDirectories: () => [] }; const inputFileName = transpileOptions.fileName || (transpileOptions.compilerOptions && transpileOptions.compilerOptions.jsx ? "module.tsx" : "module.ts"); - const sourceFile = createSourceFile( - inputFileName, - input, - { - languageVersion: getEmitScriptTarget(options), - impliedNodeFormat: getImpliedNodeFormatForFile( - toPath(inputFileName, "", compilerHost.getCanonicalFileName), - /*packageJsonInfoCache*/ - void 0, - compilerHost, - options - ), - setExternalModuleIndicator: getSetExternalModuleIndicator(options), - jsDocParsingMode: transpileOptions.jsDocParsingMode ?? 0 /* ParseAll */ - } - ); + const sourceFile = createSourceFile(inputFileName, input, { + languageVersion: getEmitScriptTarget(options), + impliedNodeFormat: getImpliedNodeFormatForFile(toPath(inputFileName, "", compilerHost.getCanonicalFileName), /*packageJsonInfoCache*/ + void 0, compilerHost, options), + setExternalModuleIndicator: getSetExternalModuleIndicator(options), + jsDocParsingMode: (_transpileOptions$jsD = transpileOptions.jsDocParsingMode) !== null && _transpileOptions$jsD !== void 0 ? _transpileOptions$jsD : 0 /* ParseAll */ + }); + if (transpileOptions.moduleName) { sourceFile.moduleName = transpileOptions.moduleName; } @@ -135691,41 +120970,37 @@ ${lanes.join("\n")} let sourceMapText; const program = createProgram([inputFileName], options, compilerHost); if (transpileOptions.reportDiagnostics) { - addRange( - /*to*/ - diagnostics, - /*from*/ - program.getSyntacticDiagnostics(sourceFile) - ); - addRange( - /*to*/ - diagnostics, - /*from*/ - program.getOptionsDiagnostics() - ); + addRange( /*to*/ + diagnostics, /*from*/ + program.getSyntacticDiagnostics(sourceFile)); + addRange( /*to*/ + diagnostics, /*from*/ + program.getOptionsDiagnostics()); } - program.emit( - /*targetSourceFile*/ - void 0, - /*writeFile*/ - void 0, - /*cancellationToken*/ - void 0, - /*emitOnlyDtsFiles*/ - void 0, - transpileOptions.transformers - ); - if (outputText === void 0) - return Debug.fail("Output generation failed"); - return { outputText, diagnostics, sourceMapText }; + program.emit( /*targetSourceFile*/ + void 0, /*writeFile*/ + void 0, /*cancellationToken*/ + void 0, /*emitOnlyDtsFiles*/ + void 0, transpileOptions.transformers); + if (outputText === void 0) return Debug.fail("Output generation failed"); + return { + outputText, + diagnostics, + sourceMapText + }; } function transpile(input, compilerOptions, fileName, diagnostics, moduleName) { - const output = transpileModule(input, { compilerOptions, fileName, reportDiagnostics: !!diagnostics, moduleName }); + const output = transpileModule(input, { + compilerOptions, + fileName, + reportDiagnostics: !!diagnostics, + moduleName + }); addRange(diagnostics, output.diagnostics); return output.outputText; } function fixupCompilerOptions(options, diagnostics) { - commandLineOptionsStringToEnum = commandLineOptionsStringToEnum || filter(optionDeclarations, (o) => typeof o.type === "object" && !forEachEntry(o.type, (v) => typeof v !== "number")); + commandLineOptionsStringToEnum = commandLineOptionsStringToEnum || filter(optionDeclarations, o => typeof o.type === "object" && !forEachEntry(o.type, v => typeof v !== "number")); options = cloneCompilerOptions(options); for (const opt of commandLineOptionsStringToEnum) { if (!hasProperty(options, opt.name)) { @@ -135735,7 +121010,7 @@ ${lanes.join("\n")} if (isString(value)) { options[opt.name] = parseCustomTypeOption(opt, value, diagnostics); } else { - if (!forEachEntry(opt.type, (v) => v === value)) { + if (!forEachEntry(opt.type, v => v === value)) { diagnostics.push(createCompilerDiagnosticForInvalidCustomType(opt)); } } @@ -135746,20 +121021,16 @@ ${lanes.join("\n")} var init_transpile = __esm({ "src/services/transpile.ts"() { "use strict"; + init_ts4(); - optionsRedundantWithVerbatimModuleSyntax = /* @__PURE__ */ new Set([ - "isolatedModules", - "preserveValueImports", - "importsNotUsedAsValues" - ]); + optionsRedundantWithVerbatimModuleSyntax = /* @__PURE__ */new Set(["isolatedModules", "preserveValueImports", "importsNotUsedAsValues"]); } }); // 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) { @@ -135786,15 +121057,26 @@ ${lanes.join("\n")} 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) { - rawItems.push({ name, fileName, matchKind: fullMatch.kind, isCaseSensitive: fullMatch.isCaseSensitive, declaration }); + rawItems.push({ + name, + fileName, + matchKind: fullMatch.kind, + isCaseSensitive: fullMatch.isCaseSensitive, + declaration + }); } } else { - rawItems.push({ name, fileName, matchKind: match.kind, isCaseSensitive: match.isCaseSensitive, declaration }); + rawItems.push({ + name, + fileName, + matchKind: match.kind, + isCaseSensitive: match.isCaseSensitive, + declaration + }); } } } @@ -135806,7 +121088,7 @@ ${lanes.join("\n")} case 271 /* ImportEqualsDeclaration */: const importer = checker.getSymbolAtLocation(declaration.name); const imported = checker.getAliasedSymbol(importer); - return importer.escapedName !== imported.escapedName && !((_a = imported.declarations) == null ? void 0 : _a.every((d) => shouldExcludeFile(d.getSourceFile(), excludeLibFiles, singleCurrentFile))); + return importer.escapedName !== imported.escapedName && !((_a = imported.declarations) == null ? void 0 : _a.every(d => shouldExcludeFile(d.getSourceFile(), excludeLibFiles, singleCurrentFile))); default: return true; } @@ -135857,9 +121139,11 @@ ${lanes.join("\n")} containerKind: containerName ? getNodeKind(container) : "" /* unknown */ }; } + var init_navigateTo = __esm({ "src/services/navigateTo.ts"() { "use strict"; + init_ts4(); } }); @@ -135872,6 +121156,7 @@ ${lanes.join("\n")} var init_ts_NavigateTo = __esm({ "src/services/_namespaces/ts.NavigateTo.ts"() { "use strict"; + init_navigateTo(); } }); @@ -135917,7 +121202,14 @@ ${lanes.join("\n")} } function rootNavigationBarNode(sourceFile) { Debug.assert(!parentsStack.length); - const root = { node: sourceFile, name: void 0, additionalNodes: void 0, parent: void 0, children: void 0, indent: 0 }; + const root = { + node: sourceFile, + name: void 0, + additionalNodes: void 0, + parent: void 0, + children: void 0, + indent: 0 + }; parent = root; for (const statement of sourceFile.statements) { addChildrenRecursively(statement); @@ -135941,13 +121233,12 @@ ${lanes.join("\n")} } function addTrackedEs5Class(name) { if (!trackedEs5Classes) { - trackedEs5Classes = /* @__PURE__ */ new Map(); + trackedEs5Classes = /* @__PURE__ */new Map(); } 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 = []; @@ -135955,8 +121246,7 @@ ${lanes.join("\n")} 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); @@ -135998,8 +121288,7 @@ ${lanes.join("\n")} } 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); @@ -136044,7 +121333,9 @@ ${lanes.join("\n")} if (importClause.name) { addLeafNode(importClause.name); } - const { namedBindings } = importClause; + const { + namedBindings + } = importClause; if (namedBindings) { if (namedBindings.kind === 274 /* NamespaceImport */) { addLeafNode(namedBindings); @@ -136059,20 +121350,23 @@ ${lanes.join("\n")} addNodeWithRecursiveChild(node, node.name); break; case 305 /* SpreadAssignment */: - const { expression } = node; + const { + expression + } = node; isIdentifier(expression) ? addLeafNode(node, expression) : addLeafNode(node); break; case 208 /* BindingElement */: case 303 /* PropertyAssignment */: - case 260 /* VariableDeclaration */: { - const child = node; - if (isBindingPattern(child.name)) { - addChildrenRecursively(child.name); - } else { - addNodeWithRecursiveInitializer(child); + case 260 /* VariableDeclaration */: + { + const child = node; + if (isBindingPattern(child.name)) { + addChildrenRecursively(child.name); + } else { + addNodeWithRecursiveInitializer(child); + } + break; } - break; - } case 262 /* FunctionDeclaration */: const nameNode = node.name; if (nameNode && isIdentifier(nameNode)) { @@ -136105,18 +121399,19 @@ ${lanes.join("\n")} case 267 /* ModuleDeclaration */: addNodeWithRecursiveChild(node, getInteriorModule(node).body); break; - case 277 /* ExportAssignment */: { - const expression2 = node.expression; - const child = isObjectLiteralExpression(expression2) || isCallExpression(expression2) ? expression2 : isArrowFunction(expression2) || isFunctionExpression(expression2) ? expression2.body : void 0; - if (child) { - startNode(node); - addChildrenRecursively(child); - endNode(); - } else { - addLeafNode(node); + case 277 /* ExportAssignment */: + { + const expression2 = node.expression; + const child = isObjectLiteralExpression(expression2) || isCallExpression(expression2) ? expression2 : isArrowFunction(expression2) || isFunctionExpression(expression2) ? expression2.body : void 0; + if (child) { + startNode(node); + addChildrenRecursively(child); + endNode(); + } else { + addLeafNode(node); + } + break; } - break; - } case 281 /* ExportSpecifier */: case 271 /* ImportEqualsDeclaration */: case 181 /* IndexSignature */: @@ -136126,86 +121421,90 @@ ${lanes.join("\n")} addLeafNode(node); break; case 213 /* CallExpression */: - case 226 /* BinaryExpression */: { - const special = getAssignmentDeclarationKind(node); - switch (special) { - case 1 /* ExportsProperty */: - case 2 /* ModuleExports */: - addNodeWithRecursiveChild(node, node.right); - return; - case 6 /* Prototype */: - case 3 /* PrototypeProperty */: { - const binaryExpression = node; - const assignmentTarget = binaryExpression.left; - const prototypeAccess = special === 3 /* PrototypeProperty */ ? assignmentTarget.expression : assignmentTarget; - let depth = 0; - let className; - if (isIdentifier(prototypeAccess.expression)) { - addTrackedEs5Class(prototypeAccess.expression.text); - className = prototypeAccess.expression; - } else { - [depth, className] = startNestedNodes(binaryExpression, prototypeAccess.expression); - } - if (special === 6 /* Prototype */) { - if (isObjectLiteralExpression(binaryExpression.right)) { - if (binaryExpression.right.properties.length > 0) { + case 226 /* BinaryExpression */: + { + const special = getAssignmentDeclarationKind(node); + switch (special) { + case 1 /* ExportsProperty */: + case 2 /* ModuleExports */: + addNodeWithRecursiveChild(node, node.right); + return; + case 6 /* Prototype */: + case 3 /* PrototypeProperty */: + { + const binaryExpression = node; + const assignmentTarget = binaryExpression.left; + const prototypeAccess = special === 3 /* PrototypeProperty */ ? assignmentTarget.expression : assignmentTarget; + let depth = 0; + let className; + if (isIdentifier(prototypeAccess.expression)) { + addTrackedEs5Class(prototypeAccess.expression.text); + className = prototypeAccess.expression; + } else { + [depth, className] = startNestedNodes(binaryExpression, prototypeAccess.expression); + } + if (special === 6 /* Prototype */) { + if (isObjectLiteralExpression(binaryExpression.right)) { + if (binaryExpression.right.properties.length > 0) { + startNode(binaryExpression, className); + forEachChild(binaryExpression.right, addChildrenRecursively); + endNode(); + } + } + } else if (isFunctionExpression(binaryExpression.right) || isArrowFunction(binaryExpression.right)) { + addNodeWithRecursiveChild(node, binaryExpression.right, className); + } else { startNode(binaryExpression, className); - forEachChild(binaryExpression.right, addChildrenRecursively); + addNodeWithRecursiveChild(node, binaryExpression.right, assignmentTarget.name); endNode(); } + endNestedNodes(depth); + return; } - } else if (isFunctionExpression(binaryExpression.right) || isArrowFunction(binaryExpression.right)) { - addNodeWithRecursiveChild(node, binaryExpression.right, className); - } else { - startNode(binaryExpression, className); - addNodeWithRecursiveChild(node, binaryExpression.right, assignmentTarget.name); - endNode(); - } - endNestedNodes(depth); - return; - } - case 7 /* ObjectDefinePropertyValue */: - case 9 /* ObjectDefinePrototypeProperty */: { - const defineCall = node; - const className = special === 7 /* ObjectDefinePropertyValue */ ? defineCall.arguments[0] : defineCall.arguments[0].expression; - const memberName = defineCall.arguments[1]; - const [depth, classNameIdentifier] = startNestedNodes(node, className); - startNode(node, classNameIdentifier); - startNode(node, setTextRange(factory.createIdentifier(memberName.text), memberName)); - addChildrenRecursively(node.arguments[2]); - endNode(); - endNode(); - endNestedNodes(depth); - return; - } - case 5 /* Property */: { - const binaryExpression = node; - const assignmentTarget = binaryExpression.left; - const targetFunction = assignmentTarget.expression; - if (isIdentifier(targetFunction) && getElementOrPropertyAccessName(assignmentTarget) !== "prototype" && trackedEs5Classes && trackedEs5Classes.has(targetFunction.text)) { - if (isFunctionExpression(binaryExpression.right) || isArrowFunction(binaryExpression.right)) { - addNodeWithRecursiveChild(node, binaryExpression.right, targetFunction); - } else if (isBindableStaticAccessExpression(assignmentTarget)) { - startNode(binaryExpression, targetFunction); - addNodeWithRecursiveChild(binaryExpression.left, binaryExpression.right, getNameOrArgument(assignmentTarget)); + case 7 /* ObjectDefinePropertyValue */: + case 9 /* ObjectDefinePrototypeProperty */: + { + const defineCall = node; + const className = special === 7 /* ObjectDefinePropertyValue */ ? defineCall.arguments[0] : defineCall.arguments[0].expression; + const memberName = defineCall.arguments[1]; + const [depth, classNameIdentifier] = startNestedNodes(node, className); + startNode(node, classNameIdentifier); + startNode(node, setTextRange(factory.createIdentifier(memberName.text), memberName)); + addChildrenRecursively(node.arguments[2]); endNode(); + endNode(); + endNestedNodes(depth); + return; } - return; - } - break; + case 5 /* Property */: + { + const binaryExpression = node; + const assignmentTarget = binaryExpression.left; + const targetFunction = assignmentTarget.expression; + if (isIdentifier(targetFunction) && getElementOrPropertyAccessName(assignmentTarget) !== "prototype" && trackedEs5Classes && trackedEs5Classes.has(targetFunction.text)) { + if (isFunctionExpression(binaryExpression.right) || isArrowFunction(binaryExpression.right)) { + addNodeWithRecursiveChild(node, binaryExpression.right, targetFunction); + } else if (isBindableStaticAccessExpression(assignmentTarget)) { + startNode(binaryExpression, targetFunction); + addNodeWithRecursiveChild(binaryExpression.left, binaryExpression.right, getNameOrArgument(assignmentTarget)); + endNode(); + } + return; + } + break; + } + case 4 /* ThisProperty */: + case 0 /* None */: + case 8 /* ObjectDefinePropertyExports */: + break; + default: + Debug.assertNever(special); } - case 4 /* ThisProperty */: - case 0 /* None */: - case 8 /* ObjectDefinePropertyExports */: - break; - default: - Debug.assertNever(special); } - } default: if (hasJSDocNodes(node)) { - forEach(node.jsDoc, (jsDoc) => { - forEach(jsDoc.tags, (tag) => { + forEach(node.jsDoc, jsDoc => { + forEach(jsDoc.tags, tag => { if (isJSDocTypeAlias(tag)) { addLeafNode(tag); } @@ -136216,7 +121515,7 @@ ${lanes.join("\n")} } } function mergeChildren(children, node) { - const nameToItems = /* @__PURE__ */ new Map(); + const nameToItems = /* @__PURE__ */new Map(); filterMutate(children, (child, index) => { const declName = child.name || getNameOfDeclaration(child.node); const name = declName && nodeText(declName); @@ -136257,42 +121556,30 @@ ${lanes.join("\n")} if (!isClassDeclaration(a.node) && !isClassDeclaration(b.node) || isPossibleConstructor(a.node) || isPossibleConstructor(b.node)) { const ctorFunction = isPossibleConstructor(a.node) ? a.node : isPossibleConstructor(b.node) ? b.node : void 0; if (ctorFunction !== void 0) { - const ctorNode = setTextRange( - factory.createConstructorDeclaration( - /*modifiers*/ - void 0, - [], - /*body*/ - void 0 - ), - ctorFunction - ); + const ctorNode = setTextRange(factory.createConstructorDeclaration( /*modifiers*/ + void 0, [], /*body*/ + void 0), ctorFunction); const ctor = emptyNavigationBarNode(ctorNode); ctor.indent = a.indent + 1; ctor.children = a.node === ctorFunction ? a.children : b.children; - a.children = a.node === ctorFunction ? concatenate([ctor], b.children || [b]) : concatenate(a.children || [{ ...a }], [ctor]); + a.children = a.node === ctorFunction ? concatenate([ctor], b.children || [b]) : concatenate(a.children || [{ + ...a + }], [ctor]); } else { if (a.children || b.children) { - a.children = concatenate(a.children || [{ ...a }], b.children || [b]); + a.children = concatenate(a.children || [{ + ...a + }], b.children || [b]); if (a.children) { mergeChildren(a.children, a); sortChildren(a.children); } } } - lastANode = a.node = setTextRange( - factory.createClassDeclaration( - /*modifiers*/ - void 0, - a.name || factory.createIdentifier("__class__"), - /*typeParameters*/ - void 0, - /*heritageClauses*/ - void 0, - [] - ), - a.node - ); + lastANode = a.node = setTextRange(factory.createClassDeclaration( /*modifiers*/ + void 0, a.name || factory.createIdentifier("__class__"), /*typeParameters*/ + void 0, /*heritageClauses*/ + void 0, []), a.node); } else { a.children = concatenate(a.children, b.children); if (a.children) { @@ -136301,23 +121588,16 @@ ${lanes.join("\n")} } const bNode = b.node; if (parent2.children[bIndex - 1].node.end === lastANode.end) { - setTextRange(lastANode, { pos: lastANode.pos, end: bNode.end }); + setTextRange(lastANode, { + pos: lastANode.pos, + end: bNode.end + }); } else { - if (!a.additionalNodes) - a.additionalNodes = []; - a.additionalNodes.push(setTextRange( - factory.createClassDeclaration( - /*modifiers*/ - void 0, - a.name || factory.createIdentifier("__class__"), - /*typeParameters*/ - void 0, - /*heritageClauses*/ - void 0, - [] - ), - b.node - )); + if (!a.additionalNodes) a.additionalNodes = []; + a.additionalNodes.push(setTextRange(factory.createClassDeclaration( /*modifiers*/ + void 0, a.name || factory.createIdentifier("__class__"), /*typeParameters*/ + void 0, /*heritageClauses*/ + void 0, []), b.node)); } return true; } @@ -136352,6 +121632,7 @@ ${lanes.join("\n")} function isSynthesized(node) { return !!(node.flags & 16 /* Synthesized */); } + function isOwnChild(n, parent2) { const par = isModuleBlock(n.parent) ? n.parent.parent : n.parent; return par === parent2.node || contains(parent2.additionalNodes, par); @@ -136550,6 +121831,7 @@ ${lanes.join("\n")} function isComputedProperty(member) { return !member.name || member.name.kind === 167 /* ComputedPropertyName */; } + function getNodeSpan(node) { return node.kind === 312 /* SourceFile */ ? createTextSpanFromRange(node) : createTextSpanFromNode(node, curSourceFile); } @@ -136560,7 +121842,9 @@ ${lanes.join("\n")} return getNodeModifiers(node); } function getFunctionOrClassName(node) { - const { parent: parent2 } = node; + const { + parent: parent2 + } = node; if (node.name && getFullWidth(node.name) > 0) { return cleanText(declarationNameToString(node.name)); } else if (isVariableDeclaration(parent2)) { @@ -136580,7 +121864,7 @@ ${lanes.join("\n")} if (name.length > maxLength) { return `${name} callback`; } - const args = cleanText(mapDefined(parent2.arguments, (a) => isStringLiteralLike(a) ? a.getText(curSourceFile) : void 0).join(", ")); + const args = cleanText(mapDefined(parent2.arguments, a => isStringLiteralLike(a) ? a.getText(curSourceFile) : void 0).join(", ")); return `${name}(${args}) callback`; } } @@ -136615,6 +121899,7 @@ ${lanes.join("\n")} var init_navigationBar = __esm({ "src/services/navigationBar.ts"() { "use strict"; + init_ts4(); whiteSpaceRegex = /\s+/g; maxLength = 150; @@ -136645,6 +121930,7 @@ ${lanes.join("\n")} var init_ts_NavigationBar = __esm({ "src/services/_namespaces/ts.NavigationBar.ts"() { "use strict"; + init_navigationBar(); } }); @@ -136654,9 +121940,9 @@ ${lanes.join("\n")} refactors.set(name, refactor); } function getApplicableRefactors(context, includeInteractiveActions) { - return arrayFrom(flatMapIterator(refactors.values(), (refactor) => { + return arrayFrom(flatMapIterator(refactors.values(), refactor => { var _a; - return context.cancellationToken && context.cancellationToken.isCancellationRequested() || !((_a = refactor.kinds) == null ? void 0 : _a.some((kind) => refactorKindBeginsWith(kind, context.kind))) ? void 0 : refactor.getAvailableActions(context, includeInteractiveActions); + return context.cancellationToken && context.cancellationToken.isCancellationRequested() || !((_a = refactor.kinds) == null ? void 0 : _a.some(kind => refactorKindBeginsWith(kind, context.kind))) ? void 0 : refactor.getAvailableActions(context, includeInteractiveActions); })); } function getEditsForRefactor(context, refactorName14, actionName2, interactiveRefactorArguments) { @@ -136667,58 +121953,83 @@ ${lanes.join("\n")} var init_refactorProvider = __esm({ "src/services/refactorProvider.ts"() { "use strict"; + init_ts4(); init_ts_refactor(); - refactors = /* @__PURE__ */ new Map(); + refactors = /* @__PURE__ */new Map(); } }); // src/services/refactors/convertExport.ts function getInfo2(context, considerPartialSpans = true) { - const { file, program } = context; + const { + file, + program + } = context; const span = getRefactorContextSpan(context); const token = getTokenAtPosition(file, span.start); const exportNode = !!(token.parent && getSyntacticModifierFlags(token.parent) & 32 /* Export */) && considerPartialSpans ? token.parent : getParentNodeInSpan(token, file, span); if (!exportNode || !isSourceFile(exportNode.parent) && !(isModuleBlock(exportNode.parent) && isAmbientModule(exportNode.parent.parent))) { - return { error: getLocaleSpecificMessage(Diagnostics.Could_not_find_export_statement) }; + return { + error: getLocaleSpecificMessage(Diagnostics.Could_not_find_export_statement) + }; } const checker = program.getTypeChecker(); const exportingModuleSymbol = getExportingModuleSymbol(exportNode.parent, checker); const flags = getSyntacticModifierFlags(exportNode) || (isExportAssignment(exportNode) && !exportNode.isExportEquals ? 2080 /* ExportDefault */ : 0 /* None */); const wasDefault = !!(flags & 2048 /* Default */); if (!(flags & 32 /* Export */) || !wasDefault && exportingModuleSymbol.exports.has("default" /* Default */)) { - return { error: getLocaleSpecificMessage(Diagnostics.This_file_already_has_a_default_export) }; + return { + error: getLocaleSpecificMessage(Diagnostics.This_file_already_has_a_default_export) + }; } - const noSymbolError = (id) => isIdentifier(id) && checker.getSymbolAtLocation(id) ? void 0 : { error: getLocaleSpecificMessage(Diagnostics.Can_only_convert_named_export) }; + const noSymbolError = id => isIdentifier(id) && checker.getSymbolAtLocation(id) ? void 0 : { + error: getLocaleSpecificMessage(Diagnostics.Can_only_convert_named_export) + }; switch (exportNode.kind) { case 262 /* FunctionDeclaration */: case 263 /* ClassDeclaration */: case 264 /* InterfaceDeclaration */: case 266 /* EnumDeclaration */: case 265 /* TypeAliasDeclaration */: - case 267 /* ModuleDeclaration */: { - const node = exportNode; - if (!node.name) - return void 0; - return noSymbolError(node.name) || { exportNode: node, exportName: node.name, wasDefault, exportingModuleSymbol }; - } - case 243 /* VariableStatement */: { - const vs = exportNode; - if (!(vs.declarationList.flags & 2 /* Const */) || vs.declarationList.declarations.length !== 1) { - return void 0; + case 267 /* ModuleDeclaration */: + { + const node = exportNode; + if (!node.name) return void 0; + return noSymbolError(node.name) || { + exportNode: node, + exportName: node.name, + wasDefault, + exportingModuleSymbol + }; + } + case 243 /* VariableStatement */: + { + const vs = exportNode; + if (!(vs.declarationList.flags & 2 /* Const */) || vs.declarationList.declarations.length !== 1) { + return void 0; + } + const decl = first(vs.declarationList.declarations); + if (!decl.initializer) return void 0; + Debug.assert(!wasDefault, "Can't have a default flag here"); + return noSymbolError(decl.name) || { + exportNode: vs, + exportName: decl.name, + wasDefault, + exportingModuleSymbol + }; + } + case 277 /* ExportAssignment */: + { + const node = exportNode; + if (node.isExportEquals) return void 0; + return noSymbolError(node.expression) || { + exportNode: node, + exportName: node.expression, + wasDefault, + exportingModuleSymbol + }; } - const decl = first(vs.declarationList.declarations); - if (!decl.initializer) - return void 0; - Debug.assert(!wasDefault, "Can't have a default flag here"); - return noSymbolError(decl.name) || { exportNode: vs, exportName: decl.name, wasDefault, exportingModuleSymbol }; - } - case 277 /* ExportAssignment */: { - const node = exportNode; - if (node.isExportEquals) - return void 0; - return noSymbolError(node.expression) || { exportNode: node, exportName: node.expression, wasDefault, exportingModuleSymbol }; - } default: return void 0; } @@ -136727,18 +122038,18 @@ ${lanes.join("\n")} changeExport(exportingSourceFile, info, changes, program.getTypeChecker()); changeImports(program, info, changes, cancellationToken); } - function changeExport(exportingSourceFile, { wasDefault, exportNode, exportName }, changes, checker) { + function changeExport(exportingSourceFile, { + wasDefault, + exportNode, + exportName + }, changes, checker) { if (wasDefault) { if (isExportAssignment(exportNode) && !exportNode.isExportEquals) { const exp = exportNode.expression; const spec = makeExportSpecifier(exp.text, exp.text); - changes.replaceNode(exportingSourceFile, exportNode, factory.createExportDeclaration( - /*modifiers*/ - void 0, - /*isTypeOnly*/ - false, - factory.createNamedExports([spec]) - )); + changes.replaceNode(exportingSourceFile, exportNode, factory.createExportDeclaration( /*modifiers*/ + void 0, /*isTypeOnly*/ + false, factory.createNamedExports([spec]))); } else { changes.delete(exportingSourceFile, Debug.checkDefined(findModifier(exportNode, 90 /* DefaultKeyword */), "Should find a default keyword in modifier list")); } @@ -136767,12 +122078,15 @@ ${lanes.join("\n")} } } } - function changeImports(program, { wasDefault, exportName, exportingModuleSymbol }, changes, cancellationToken) { + function changeImports(program, { + wasDefault, + exportName, + exportingModuleSymbol + }, changes, cancellationToken) { const checker = program.getTypeChecker(); const exportSymbol = Debug.checkDefined(checker.getSymbolAtLocation(exportName), "Export name should resolve to a symbol"); - ts_FindAllReferences_exports.Core.eachExportReference(program.getSourceFiles(), checker, cancellationToken, exportSymbol, exportingModuleSymbol, exportName.text, wasDefault, (ref) => { - if (exportName === ref) - return; + ts_FindAllReferences_exports.Core.eachExportReference(program.getSourceFiles(), checker, cancellationToken, exportSymbol, exportingModuleSymbol, exportName.text, wasDefault, ref => { + if (exportName === ref) return; const importingSourceFile = ref.getSourceFile(); if (wasDefault) { changeDefaultToNamedImport(importingSourceFile, ref, changes, exportName.text); @@ -136782,41 +122096,45 @@ ${lanes.join("\n")} }); } function changeDefaultToNamedImport(importingSourceFile, ref, changes, exportName) { - const { parent: parent2 } = ref; + const { + parent: parent2 + } = ref; switch (parent2.kind) { case 211 /* PropertyAccessExpression */: changes.replaceNode(importingSourceFile, ref, factory.createIdentifier(exportName)); break; case 276 /* ImportSpecifier */: - case 281 /* ExportSpecifier */: { - const spec = parent2; - changes.replaceNode(importingSourceFile, spec, makeImportSpecifier(exportName, spec.name.text)); - break; - } - case 273 /* ImportClause */: { - const clause = parent2; - Debug.assert(clause.name === ref, "Import clause name should match provided ref"); - const spec = makeImportSpecifier(exportName, ref.text); - const { namedBindings } = clause; - if (!namedBindings) { - changes.replaceNode(importingSourceFile, ref, factory.createNamedImports([spec])); - } else if (namedBindings.kind === 274 /* NamespaceImport */) { - changes.deleteRange(importingSourceFile, { pos: ref.getStart(importingSourceFile), end: namedBindings.getStart(importingSourceFile) }); - const quotePreference = isStringLiteral(clause.parent.moduleSpecifier) ? quotePreferenceFromString(clause.parent.moduleSpecifier, importingSourceFile) : 1 /* Double */; - const newImport = makeImport( - /*defaultImport*/ - void 0, - [makeImportSpecifier(exportName, ref.text)], - clause.parent.moduleSpecifier, - quotePreference - ); - changes.insertNodeAfter(importingSourceFile, clause.parent, newImport); - } else { - changes.delete(importingSourceFile, ref); - changes.insertNodeAtEndOfList(importingSourceFile, namedBindings.elements, spec); + case 281 /* ExportSpecifier */: + { + const spec = parent2; + changes.replaceNode(importingSourceFile, spec, makeImportSpecifier(exportName, spec.name.text)); + break; + } + case 273 /* ImportClause */: + { + const clause = parent2; + Debug.assert(clause.name === ref, "Import clause name should match provided ref"); + const spec = makeImportSpecifier(exportName, ref.text); + const { + namedBindings + } = clause; + if (!namedBindings) { + changes.replaceNode(importingSourceFile, ref, factory.createNamedImports([spec])); + } else if (namedBindings.kind === 274 /* NamespaceImport */) { + changes.deleteRange(importingSourceFile, { + pos: ref.getStart(importingSourceFile), + end: namedBindings.getStart(importingSourceFile) + }); + const quotePreference = isStringLiteral(clause.parent.moduleSpecifier) ? quotePreferenceFromString(clause.parent.moduleSpecifier, importingSourceFile) : 1 /* Double */; + const newImport = makeImport( /*defaultImport*/ + void 0, [makeImportSpecifier(exportName, ref.text)], clause.parent.moduleSpecifier, quotePreference); + changes.insertNodeAfter(importingSourceFile, clause.parent, newImport); + } else { + changes.delete(importingSourceFile, ref); + changes.insertNodeAtEndOfList(importingSourceFile, namedBindings.elements, spec); + } + break; } - break; - } case 205 /* ImportType */: const importTypeNode = parent2; changes.replaceNode(importingSourceFile, parent2, factory.createImportTypeNode(importTypeNode.argument, importTypeNode.attributes, factory.createIdentifier(exportName), importTypeNode.typeArguments, importTypeNode.isTypeOf)); @@ -136831,39 +122149,33 @@ ${lanes.join("\n")} case 211 /* PropertyAccessExpression */: changes.replaceNode(importingSourceFile, ref, factory.createIdentifier("default")); break; - case 276 /* ImportSpecifier */: { - const defaultImport = factory.createIdentifier(parent2.name.text); - if (parent2.parent.elements.length === 1) { - changes.replaceNode(importingSourceFile, parent2.parent, defaultImport); - } else { - changes.delete(importingSourceFile, parent2); - changes.insertNodeBefore(importingSourceFile, parent2.parent, defaultImport); + case 276 /* ImportSpecifier */: + { + const defaultImport = factory.createIdentifier(parent2.name.text); + if (parent2.parent.elements.length === 1) { + changes.replaceNode(importingSourceFile, parent2.parent, defaultImport); + } else { + changes.delete(importingSourceFile, parent2); + changes.insertNodeBefore(importingSourceFile, parent2.parent, defaultImport); + } + break; + } + case 281 /* ExportSpecifier */: + { + changes.replaceNode(importingSourceFile, parent2, makeExportSpecifier("default", parent2.name.text)); + break; } - break; - } - case 281 /* ExportSpecifier */: { - changes.replaceNode(importingSourceFile, parent2, makeExportSpecifier("default", parent2.name.text)); - break; - } default: Debug.assertNever(parent2, `Unexpected parent kind ${parent2.kind}`); } } function makeImportSpecifier(propertyName, name) { - return factory.createImportSpecifier( - /*isTypeOnly*/ - false, - propertyName === name ? void 0 : factory.createIdentifier(propertyName), - factory.createIdentifier(name) - ); + return factory.createImportSpecifier( /*isTypeOnly*/ + false, propertyName === name ? void 0 : factory.createIdentifier(propertyName), factory.createIdentifier(name)); } function makeExportSpecifier(propertyName, name) { - return factory.createExportSpecifier( - /*isTypeOnly*/ - false, - propertyName === name ? void 0 : factory.createIdentifier(propertyName), - factory.createIdentifier(name) - ); + return factory.createExportSpecifier( /*isTypeOnly*/ + false, propertyName === name ? void 0 : factory.createIdentifier(propertyName), factory.createIdentifier(name)); } function getExportingModuleSymbol(parent2, checker) { if (isSourceFile(parent2)) { @@ -136879,6 +122191,7 @@ ${lanes.join("\n")} var init_convertExport = __esm({ "src/services/refactors/convertExport.ts"() { "use strict"; + init_ts4(); init_ts_refactor(); refactorName = "Convert export"; @@ -136893,29 +122206,30 @@ ${lanes.join("\n")} kind: "refactor.rewrite.export.default" }; registerRefactor(refactorName, { - kinds: [ - defaultToNamedAction.kind, - namedToDefaultAction.kind - ], + kinds: [defaultToNamedAction.kind, namedToDefaultAction.kind], 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] }]; + return [{ + name: refactorName, + description: action.description, + actions: [action] + }]; } if (context.preferences.provideRefactorNotApplicableReason) { - return [ - { - name: refactorName, - description: getLocaleSpecificMessage(Diagnostics.Convert_default_export_to_named_export), - actions: [ - { ...defaultToNamedAction, notApplicableReason: info.error }, - { ...namedToDefaultAction, notApplicableReason: info.error } - ] - } - ]; + return [{ + name: refactorName, + description: getLocaleSpecificMessage(Diagnostics.Convert_default_export_to_named_export), + actions: [{ + ...defaultToNamedAction, + notApplicableReason: info.error + }, { + ...namedToDefaultAction, + notApplicableReason: info.error + }] + }]; } return emptyArray; }, @@ -136923,8 +122237,12 @@ ${lanes.join("\n")} Debug.assert(actionName2 === defaultToNamedAction.name || actionName2 === namedToDefaultAction.name, "Unexpected action name"); const info = getInfo2(context); Debug.assert(info && !isRefactorErrorInfo(info), "Expected applicable refactor info"); - const edits = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange(context.file, context.program, info, t, context.cancellationToken)); - return { edits, renameFilename: void 0, renameLocation: void 0 }; + const edits = ts_textChanges_exports.ChangeTracker.with(context, t => doChange(context.file, context.program, info, t, context.cancellationToken)); + return { + edits, + renameFilename: void 0, + renameLocation: void 0 + }; } }); } @@ -136932,28 +122250,45 @@ ${lanes.join("\n")} // src/services/refactors/convertImport.ts function getImportConversionInfo(context, considerPartialSpans = true) { - const { file } = context; + const { + file + } = context; const span = getRefactorContextSpan(context); const token = getTokenAtPosition(file, span.start); const importDecl = considerPartialSpans ? findAncestor(token, isImportDeclaration) : getParentNodeInSpan(token, file, span); - if (!importDecl || !isImportDeclaration(importDecl)) - return { error: "Selection is not an import declaration." }; + if (!importDecl || !isImportDeclaration(importDecl)) return { + error: "Selection is not an import declaration." + }; const end = span.start + span.length; const nextToken = findNextToken(importDecl, importDecl.parent, file); - if (nextToken && end > nextToken.getStart()) - return void 0; - const { importClause } = importDecl; + if (nextToken && end > nextToken.getStart()) return void 0; + const { + importClause + } = importDecl; if (!importClause) { - return { error: getLocaleSpecificMessage(Diagnostics.Could_not_find_import_clause) }; + return { + error: getLocaleSpecificMessage(Diagnostics.Could_not_find_import_clause) + }; } if (!importClause.namedBindings) { - return { error: getLocaleSpecificMessage(Diagnostics.Could_not_find_namespace_import_or_named_imports) }; + return { + error: getLocaleSpecificMessage(Diagnostics.Could_not_find_namespace_import_or_named_imports) + }; } if (importClause.namedBindings.kind === 274 /* NamespaceImport */) { - return { convertTo: 0 /* Named */, import: importClause.namedBindings }; + return { + convertTo: 0 /* Named */, + import: importClause.namedBindings + }; } const shouldUseDefault = getShouldUseDefault(context.program, importClause); - return shouldUseDefault ? { convertTo: 1 /* Default */, import: importClause.namedBindings } : { convertTo: 2 /* Namespace */, import: importClause.namedBindings }; + return shouldUseDefault ? { + convertTo: 1 /* Default */, + import: importClause.namedBindings + } : { + convertTo: 2 /* Namespace */, + import: importClause.namedBindings + }; } function getShouldUseDefault(program, importClause) { return getAllowSyntheticDefaultImports(program.getCompilerOptions()) && isExportEqualsModule(importClause.parent.moduleSpecifier, program.getTypeChecker()); @@ -136966,29 +122301,25 @@ ${lanes.join("\n")} doChangeNamedToNamespaceOrDefault(sourceFile, program, changes, info.import, info.convertTo === 1 /* Default */); } } + function doChangeNamespaceToNamed(sourceFile, checker, changes, toConvert, allowSyntheticDefaultImports) { let usedAsNamespaceOrDefault = false; const nodesToReplace = []; - const conflictingNames = /* @__PURE__ */ new Map(); - ts_FindAllReferences_exports.Core.eachSymbolReferenceInFile(toConvert.name, checker, sourceFile, (id) => { + const conflictingNames = /* @__PURE__ */new Map(); + ts_FindAllReferences_exports.Core.eachSymbolReferenceInFile(toConvert.name, checker, sourceFile, id => { if (!isPropertyAccessOrQualifiedName(id.parent)) { usedAsNamespaceOrDefault = true; } else { const exportName = getRightOfPropertyAccessOrQualifiedName(id.parent).text; - if (checker.resolveName( - exportName, - id, - 67108863 /* All */, - /*excludeGlobals*/ - true - )) { + if (checker.resolveName(exportName, id, 67108863 /* All */, /*excludeGlobals*/ + true)) { conflictingNames.set(exportName, true); } Debug.assert(getLeftOfPropertyAccessOrQualifiedName(id.parent) === id, "Parent expression should match id"); nodesToReplace.push(id.parent); } }); - const exportNameToImportName = /* @__PURE__ */ new Map(); + const exportNameToImportName = /* @__PURE__ */new Map(); for (const propertyAccessOrQualifiedName of nodesToReplace) { const exportName = getRightOfPropertyAccessOrQualifiedName(propertyAccessOrQualifiedName).text; let importName = exportNameToImportName.get(exportName); @@ -136999,21 +122330,13 @@ ${lanes.join("\n")} } const importSpecifiers = []; exportNameToImportName.forEach((name, propertyName) => { - importSpecifiers.push(factory.createImportSpecifier( - /*isTypeOnly*/ - false, - name === propertyName ? void 0 : factory.createIdentifier(propertyName), - factory.createIdentifier(name) - )); + importSpecifiers.push(factory.createImportSpecifier( /*isTypeOnly*/ + false, name === propertyName ? void 0 : factory.createIdentifier(propertyName), factory.createIdentifier(name))); }); const importDecl = toConvert.parent.parent; if (usedAsNamespaceOrDefault && !allowSyntheticDefaultImports) { - changes.insertNodeAfter(sourceFile, importDecl, updateImport( - importDecl, - /*defaultImportName*/ - void 0, - importSpecifiers - )); + changes.insertNodeAfter(sourceFile, importDecl, updateImport(importDecl, /*defaultImportName*/ + void 0, importSpecifiers)); } else { changes.replaceNode(sourceFile, importDecl, updateImport(importDecl, usedAsNamespaceOrDefault ? factory.createIdentifier(toConvert.name.text) : void 0, importSpecifiers)); } @@ -137027,9 +122350,11 @@ ${lanes.join("\n")} function doChangeNamedToNamespaceOrDefault(sourceFile, program, changes, toConvert, shouldUseDefault = getShouldUseDefault(program, toConvert.parent)) { const checker = program.getTypeChecker(); const importDecl = toConvert.parent.parent; - const { moduleSpecifier } = importDecl; - const toConvertSymbols = /* @__PURE__ */ new Set(); - toConvert.elements.forEach((namedImport) => { + const { + moduleSpecifier + } = importDecl; + const toConvertSymbols = /* @__PURE__ */new Set(); + toConvert.elements.forEach(namedImport => { const symbol = checker.getSymbolAtLocation(namedImport.name); if (symbol) { toConvertSymbols.add(symbol); @@ -137037,14 +122362,9 @@ ${lanes.join("\n")} }); const preferredName = moduleSpecifier && isStringLiteral(moduleSpecifier) ? ts_codefix_exports.moduleSpecifierToValidIdentifier(moduleSpecifier.text, 99 /* ESNext */) : "module"; function hasNamespaceNameConflict(namedImport) { - return !!ts_FindAllReferences_exports.Core.eachSymbolReferenceInFile(namedImport.name, checker, sourceFile, (id) => { - const symbol = checker.resolveName( - preferredName, - id, - 67108863 /* All */, - /*excludeGlobals*/ - true - ); + return !!ts_FindAllReferences_exports.Core.eachSymbolReferenceInFile(namedImport.name, checker, sourceFile, id => { + const symbol = checker.resolveName(preferredName, id, 67108863 /* All */, /*excludeGlobals*/ + true); if (symbol) { if (toConvertSymbols.has(symbol)) { return isExportSpecifier(id.parent); @@ -137056,10 +122376,10 @@ ${lanes.join("\n")} } const namespaceNameConflicts = toConvert.elements.some(hasNamespaceNameConflict); const namespaceImportName = namespaceNameConflicts ? getUniqueName(preferredName, sourceFile) : preferredName; - const neededNamedImports = /* @__PURE__ */ new Set(); + const neededNamedImports = /* @__PURE__ */new Set(); for (const element of toConvert.elements) { const propertyName = (element.propertyName || element.name).text; - ts_FindAllReferences_exports.Core.eachSymbolReferenceInFile(element.name, checker, sourceFile, (id) => { + ts_FindAllReferences_exports.Core.eachSymbolReferenceInFile(element.name, checker, sourceFile, id => { const access = factory.createPropertyAccessExpression(factory.createIdentifier(namespaceImportName), propertyName); if (isShorthandPropertyAssignment(id.parent)) { changes.replaceNode(sourceFile, id.parent, factory.createPropertyAssignment(id.text, access)); @@ -137070,47 +122390,30 @@ ${lanes.join("\n")} } }); } - changes.replaceNode( - sourceFile, - toConvert, - shouldUseDefault ? factory.createIdentifier(namespaceImportName) : factory.createNamespaceImport(factory.createIdentifier(namespaceImportName)) - ); + changes.replaceNode(sourceFile, toConvert, shouldUseDefault ? factory.createIdentifier(namespaceImportName) : factory.createNamespaceImport(factory.createIdentifier(namespaceImportName))); if (neededNamedImports.size) { - const newNamedImports = arrayFrom(neededNamedImports.values(), (element) => factory.createImportSpecifier(element.isTypeOnly, element.propertyName && factory.createIdentifier(element.propertyName.text), factory.createIdentifier(element.name.text))); - changes.insertNodeAfter(sourceFile, toConvert.parent.parent, updateImport( - importDecl, - /*defaultImportName*/ - void 0, - newNamedImports - )); + const newNamedImports = arrayFrom(neededNamedImports.values(), element => factory.createImportSpecifier(element.isTypeOnly, element.propertyName && factory.createIdentifier(element.propertyName.text), factory.createIdentifier(element.name.text))); + changes.insertNodeAfter(sourceFile, toConvert.parent.parent, updateImport(importDecl, /*defaultImportName*/ + void 0, newNamedImports)); } } function isExportEqualsModule(moduleSpecifier, checker) { const externalModule = checker.resolveExternalModuleName(moduleSpecifier); - if (!externalModule) - return false; + if (!externalModule) return false; const exportEquals = checker.resolveExternalModuleSymbol(externalModule); return externalModule !== exportEquals; } function updateImport(old, defaultImportName, elements) { - return factory.createImportDeclaration( - /*modifiers*/ - void 0, - factory.createImportClause( - /*isTypeOnly*/ - false, - defaultImportName, - elements && elements.length ? factory.createNamedImports(elements) : void 0 - ), - old.moduleSpecifier, - /*attributes*/ - void 0 - ); + return factory.createImportDeclaration( /*modifiers*/ + void 0, factory.createImportClause( /*isTypeOnly*/ + false, defaultImportName, elements && elements.length ? factory.createNamedImports(elements) : void 0), old.moduleSpecifier, /*attributes*/ + void 0); } var refactorName2, actions; var init_convertImport = __esm({ "src/services/refactors/convertImport.ts"() { "use strict"; + init_ts4(); init_ts_refactor(); refactorName2 = "Convert import"; @@ -137132,30 +122435,40 @@ ${lanes.join("\n")} } }; registerRefactor(refactorName2, { - kinds: getOwnValues(actions).map((a) => a.kind), + 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] }]; - } - if (context.preferences.provideRefactorNotApplicableReason) { - return getOwnValues(actions).map((action) => ({ + return [{ name: refactorName2, description: action.description, - actions: [{ ...action, notApplicableReason: info.error }] + actions: [action] + }]; + } + if (context.preferences.provideRefactorNotApplicableReason) { + return getOwnValues(actions).map(action => ({ + name: refactorName2, + description: action.description, + actions: [{ + ...action, + notApplicableReason: info.error + }] })); } return emptyArray; }, getEditsForAction: function getRefactorEditsToConvertBetweenNamedAndNamespacedImports(context, actionName2) { - Debug.assert(some(getOwnValues(actions), (action) => action.name === actionName2), "Unexpected action name"); + Debug.assert(some(getOwnValues(actions), action => action.name === actionName2), "Unexpected action name"); const info = getImportConversionInfo(context); Debug.assert(info && !isRefactorErrorInfo(info), "Expected applicable refactor info"); - const edits = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange2(context.file, context.program, t, info)); - return { edits, renameFilename: void 0, renameLocation: void 0 }; + const edits = ts_textChanges_exports.ChangeTracker.with(context, t => doChange2(context.file, context.program, t, info)); + return { + edits, + renameFilename: void 0, + renameLocation: void 0 + }; } }); } @@ -137163,57 +122476,65 @@ ${lanes.join("\n")} // src/services/refactors/extractType.ts function getRangeToExtract(context, considerEmptySpans = true) { - const { file, startPosition } = context; + const { + file, + startPosition + } = context; const isJS = isSourceFileJS(file); const current = getTokenAtPosition(file, startPosition); const range = createTextRangeFromSpan(getRefactorContextSpan(context)); const cursorRequest = range.pos === range.end && considerEmptySpans; const overlappingRange = nodeOverlapsWithStartEnd(current, file, range.pos, range.end); - const firstType = findAncestor(current, (node) => node.parent && isTypeNode(node) && !rangeContainsSkipTrivia(range, node.parent, file) && (cursorRequest || overlappingRange)); - if (!firstType || !isTypeNode(firstType)) - return { error: getLocaleSpecificMessage(Diagnostics.Selection_is_not_a_valid_type_node) }; + const firstType = findAncestor(current, node => node.parent && isTypeNode(node) && !rangeContainsSkipTrivia(range, node.parent, file) && (cursorRequest || overlappingRange)); + if (!firstType || !isTypeNode(firstType)) return { + error: getLocaleSpecificMessage(Diagnostics.Selection_is_not_a_valid_type_node) + }; const checker = context.program.getTypeChecker(); const enclosingNode = getEnclosingNode(firstType, isJS); - if (enclosingNode === void 0) - return { error: getLocaleSpecificMessage(Diagnostics.No_type_could_be_extracted_from_this_type_node) }; + if (enclosingNode === void 0) return { + error: getLocaleSpecificMessage(Diagnostics.No_type_could_be_extracted_from_this_type_node) + }; const expandedFirstType = getExpandedSelectionNode(firstType, enclosingNode); - if (!isTypeNode(expandedFirstType)) - return { error: getLocaleSpecificMessage(Diagnostics.Selection_is_not_a_valid_type_node) }; + if (!isTypeNode(expandedFirstType)) return { + error: getLocaleSpecificMessage(Diagnostics.Selection_is_not_a_valid_type_node) + }; const typeList = []; if ((isUnionTypeNode(expandedFirstType.parent) || isIntersectionTypeNode(expandedFirstType.parent)) && range.end > firstType.end) { - addRange( - typeList, - expandedFirstType.parent.types.filter((type) => { - return nodeOverlapsWithStartEnd(type, file, range.pos, range.end); - }) - ); + addRange(typeList, expandedFirstType.parent.types.filter(type => { + return nodeOverlapsWithStartEnd(type, file, range.pos, range.end); + })); } const selection = typeList.length > 1 ? typeList : expandedFirstType; const typeParameters = collectTypeParameters(checker, selection, enclosingNode, file); - if (!typeParameters) - return { error: getLocaleSpecificMessage(Diagnostics.No_type_could_be_extracted_from_this_type_node) }; + if (!typeParameters) return { + error: getLocaleSpecificMessage(Diagnostics.No_type_could_be_extracted_from_this_type_node) + }; const typeElements = flattenTypeLiteralNodeReference(checker, selection); - return { isJS, selection, enclosingNode, typeParameters, typeElements }; + return { + isJS, + selection, + enclosingNode, + typeParameters, + typeElements + }; } 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; } if (isIntersectionTypeNode(selection)) { const result = []; - const seen = /* @__PURE__ */ new Map(); + const seen = /* @__PURE__ */new Map(); for (const type of selection.types) { const flattenedTypeMembers = flattenTypeLiteralNodeReference(checker, type); - if (!flattenedTypeMembers || !flattenedTypeMembers.every((type2) => type2.name && addToSeen(seen, getNameFromPropertyName(type2.name)))) { + if (!flattenedTypeMembers || !flattenedTypeMembers.every(type2 => type2.name && addToSeen(seen, getNameFromPropertyName(type2.name)))) { return void 0; } addRange(result, flattenedTypeMembers); @@ -137232,23 +122553,20 @@ ${lanes.join("\n")} function collectTypeParameters(checker, selection, enclosingNode, file) { const result = []; const selectionArray = toArray(selection); - const selectionRange = { pos: selectionArray[0].pos, end: selectionArray[selectionArray.length - 1].end }; + const selectionRange = { + pos: selectionArray[0].pos, + end: selectionArray[selectionArray.length - 1].end + }; for (const t of selectionArray) { - if (visitor(t)) - return void 0; + if (visitor(t)) return void 0; } return result; function visitor(node) { if (isTypeReferenceNode(node)) { if (isIdentifier(node.typeName)) { const typeName = node.typeName; - const symbol = checker.resolveName( - typeName.text, - typeName, - 262144 /* TypeParameter */, - /*excludeGlobals*/ - true - ); + const symbol = checker.resolveName(typeName.text, typeName, 262144 /* TypeParameter */, /*excludeGlobals*/ + true); for (const decl of (symbol == null ? void 0 : symbol.declarations) || emptyArray) { if (isTypeParameterDeclaration(decl) && decl.getSourceFile() === file) { if (decl.name.escapedText === typeName.escapedText && rangeContainsSkipTrivia(decl, selectionRange, file)) { @@ -137262,7 +122580,7 @@ ${lanes.join("\n")} } } } else if (isInferTypeNode(node)) { - const conditionalTypeNode = findAncestor(node, (n) => isConditionalTypeNode(n) && rangeContainsSkipTrivia(n.extendsType, node, file)); + const conditionalTypeNode = findAncestor(node, n => isConditionalTypeNode(n) && rangeContainsSkipTrivia(n.extendsType, node, file)); if (!conditionalTypeNode || !rangeContainsSkipTrivia(selectionRange, conditionalTypeNode, file)) { return true; } @@ -137273,13 +122591,8 @@ ${lanes.join("\n")} } } else if (isTypeQueryNode(node)) { if (isIdentifier(node.exprName)) { - const symbol = checker.resolveName( - node.exprName.text, - node.exprName, - 111551 /* Value */, - /*excludeGlobals*/ - false - ); + const symbol = checker.resolveName(node.exprName.text, node.exprName, 111551 /* Value */, /*excludeGlobals*/ + false); if ((symbol == null ? void 0 : symbol.valueDeclaration) && rangeContainsSkipTrivia(enclosingNode, symbol.valueDeclaration, file) && !rangeContainsSkipTrivia(selectionRange, symbol.valueDeclaration, file)) { return true; } @@ -137292,98 +122605,80 @@ ${lanes.join("\n")} if (file && isTupleTypeNode(node) && getLineAndCharacterOfPosition(file, node.pos).line === getLineAndCharacterOfPosition(file, node.end).line) { setEmitFlags(node, 1 /* SingleLine */); } + return forEachChild(node, visitor); } } function doTypeAliasChange(changes, file, name, info) { - const { enclosingNode, typeParameters } = info; - const { firstTypeNode, lastTypeNode, newTypeNode } = getNodesToEdit(info); - const newTypeDeclaration = factory.createTypeAliasDeclaration( - /*modifiers*/ - void 0, - name, - typeParameters.map((id) => factory.updateTypeParameterDeclaration( - id, - id.modifiers, - id.name, - id.constraint, - /*defaultType*/ - void 0 - )), - newTypeNode - ); - changes.insertNodeBefore( - file, + const { enclosingNode, - ignoreSourceNewlines(newTypeDeclaration), - /*blankLineBetween*/ - true - ); - changes.replaceNodeRange(file, firstTypeNode, lastTypeNode, factory.createTypeReferenceNode(name, typeParameters.map((id) => factory.createTypeReferenceNode( - id.name, - /*typeArguments*/ - void 0 - ))), { leadingTriviaOption: ts_textChanges_exports.LeadingTriviaOption.Exclude, trailingTriviaOption: ts_textChanges_exports.TrailingTriviaOption.ExcludeWhitespace }); + typeParameters + } = info; + const { + firstTypeNode, + lastTypeNode, + newTypeNode + } = getNodesToEdit(info); + const newTypeDeclaration = factory.createTypeAliasDeclaration( /*modifiers*/ + void 0, name, typeParameters.map(id => factory.updateTypeParameterDeclaration(id, id.modifiers, id.name, id.constraint, /*defaultType*/ + void 0)), newTypeNode); + changes.insertNodeBefore(file, enclosingNode, ignoreSourceNewlines(newTypeDeclaration), /*blankLineBetween*/ + true); + changes.replaceNodeRange(file, firstTypeNode, lastTypeNode, factory.createTypeReferenceNode(name, typeParameters.map(id => factory.createTypeReferenceNode(id.name, /*typeArguments*/ + void 0))), { + leadingTriviaOption: ts_textChanges_exports.LeadingTriviaOption.Exclude, + trailingTriviaOption: ts_textChanges_exports.TrailingTriviaOption.ExcludeWhitespace + }); } function doInterfaceChange(changes, file, name, info) { var _a; - const { enclosingNode, typeParameters, typeElements } = info; - const newTypeNode = factory.createInterfaceDeclaration( - /*modifiers*/ - void 0, - name, - typeParameters, - /*heritageClauses*/ - void 0, - typeElements - ); - setTextRange(newTypeNode, (_a = typeElements[0]) == null ? void 0 : _a.parent); - changes.insertNodeBefore( - file, + const { enclosingNode, - ignoreSourceNewlines(newTypeNode), - /*blankLineBetween*/ - true - ); - const { firstTypeNode, lastTypeNode } = getNodesToEdit(info); - changes.replaceNodeRange(file, firstTypeNode, lastTypeNode, factory.createTypeReferenceNode(name, typeParameters.map((id) => factory.createTypeReferenceNode( - id.name, - /*typeArguments*/ - void 0 - ))), { leadingTriviaOption: ts_textChanges_exports.LeadingTriviaOption.Exclude, trailingTriviaOption: ts_textChanges_exports.TrailingTriviaOption.ExcludeWhitespace }); + typeParameters, + typeElements + } = info; + const newTypeNode = factory.createInterfaceDeclaration( /*modifiers*/ + void 0, name, typeParameters, /*heritageClauses*/ + void 0, typeElements); + setTextRange(newTypeNode, (_a = typeElements[0]) == null ? void 0 : _a.parent); + changes.insertNodeBefore(file, enclosingNode, ignoreSourceNewlines(newTypeNode), /*blankLineBetween*/ + true); + const { + firstTypeNode, + lastTypeNode + } = getNodesToEdit(info); + changes.replaceNodeRange(file, firstTypeNode, lastTypeNode, factory.createTypeReferenceNode(name, typeParameters.map(id => factory.createTypeReferenceNode(id.name, /*typeArguments*/ + void 0))), { + leadingTriviaOption: ts_textChanges_exports.LeadingTriviaOption.Exclude, + trailingTriviaOption: ts_textChanges_exports.TrailingTriviaOption.ExcludeWhitespace + }); } function doTypedefChange(changes, context, file, name, info) { var _a; - toArray(info.selection).forEach((typeNode) => { + toArray(info.selection).forEach(typeNode => { setEmitFlags(typeNode, 3072 /* NoComments */ | 4096 /* NoNestedComments */); }); - const { enclosingNode, typeParameters } = info; - const { firstTypeNode, lastTypeNode, newTypeNode } = getNodesToEdit(info); - const node = factory.createJSDocTypedefTag( - factory.createIdentifier("typedef"), - factory.createJSDocTypeExpression(newTypeNode), - factory.createIdentifier(name) - ); + + const { + enclosingNode, + typeParameters + } = info; + const { + firstTypeNode, + lastTypeNode, + newTypeNode + } = getNodesToEdit(info); + const node = factory.createJSDocTypedefTag(factory.createIdentifier("typedef"), factory.createJSDocTypeExpression(newTypeNode), factory.createIdentifier(name)); const templates = []; - forEach(typeParameters, (typeParameter) => { + forEach(typeParameters, typeParameter => { const constraint = getEffectiveConstraintOfTypeParameter(typeParameter); - const parameter = factory.createTypeParameterDeclaration( - /*modifiers*/ - void 0, - typeParameter.name - ); - const template = factory.createJSDocTemplateTag( - factory.createIdentifier("template"), - constraint && cast(constraint, isJSDocTypeExpression), - [parameter] - ); + const parameter = factory.createTypeParameterDeclaration( /*modifiers*/ + void 0, typeParameter.name); + const template = factory.createJSDocTemplateTag(factory.createIdentifier("template"), constraint && cast(constraint, isJSDocTypeExpression), [parameter]); templates.push(template); }); - const jsDoc = factory.createJSDocComment( - /*comment*/ - void 0, - factory.createNodeArray(concatenate(templates, [node])) - ); + const jsDoc = factory.createJSDocComment( /*comment*/ + void 0, factory.createNodeArray(concatenate(templates, [node]))); if (isJSDoc(enclosingNode)) { const pos = enclosingNode.getStart(file); const newLineCharacter = getNewLineOrDefaultFromHost(context.host, (_a = context.formatContext) == null ? void 0 : _a.options); @@ -137391,19 +122686,11 @@ ${lanes.join("\n")} suffix: newLineCharacter + newLineCharacter + file.text.slice(getPrecedingNonSpaceCharacterPosition(file.text, pos - 1), pos) }); } else { - changes.insertNodeBefore( - file, - enclosingNode, - jsDoc, - /*blankLineBetween*/ - true - ); + changes.insertNodeBefore(file, enclosingNode, jsDoc, /*blankLineBetween*/ + true); } - changes.replaceNodeRange(file, firstTypeNode, lastTypeNode, factory.createTypeReferenceNode(name, typeParameters.map((id) => factory.createTypeReferenceNode( - id.name, - /*typeArguments*/ - void 0 - )))); + changes.replaceNodeRange(file, firstTypeNode, lastTypeNode, factory.createTypeReferenceNode(name, typeParameters.map(id => factory.createTypeReferenceNode(id.name, /*typeArguments*/ + void 0)))); } function getNodesToEdit(info) { if (isArray(info.selection)) { @@ -137423,19 +122710,20 @@ ${lanes.join("\n")} return findAncestor(node, isStatement) || (isJS ? findAncestor(node, isJSDoc) : void 0); } function getExpandedSelectionNode(firstType, enclosingNode) { - return findAncestor(firstType, (node) => { - if (node === enclosingNode) - return "quit"; + var _findAncestor; + return (_findAncestor = findAncestor(firstType, node => { + if (node === enclosingNode) return "quit"; if (isUnionTypeNode(node.parent) || isIntersectionTypeNode(node.parent)) { return true; } return false; - }) ?? firstType; + })) !== null && _findAncestor !== void 0 ? _findAncestor : firstType; } var refactorName3, extractToTypeAliasAction, extractToInterfaceAction, extractToTypeDefAction; var init_extractType = __esm({ "src/services/refactors/extractType.ts"() { "use strict"; + init_ts4(); init_ts_refactor(); refactorName3 = "Extract type"; @@ -137455,15 +122743,10 @@ ${lanes.join("\n")} kind: "refactor.extract.typedef" }; registerRefactor(refactorName3, { - kinds: [ - extractToTypeAliasAction.kind, - extractToInterfaceAction.kind, - extractToTypeDefAction.kind - ], + kinds: [extractToTypeAliasAction.kind, extractToInterfaceAction.kind, extractToTypeDefAction.kind], getAvailableActions: function getRefactorActionsToExtractType(context) { const info = getRangeToExtract(context, context.triggerReason === "invoked"); - if (!info) - return emptyArray; + if (!info) return emptyArray; if (!isRefactorErrorInfo(info)) { return [{ name: refactorName3, @@ -137475,21 +122758,28 @@ ${lanes.join("\n")} return [{ name: refactorName3, description: getLocaleSpecificMessage(Diagnostics.Extract_type), - actions: [ - { ...extractToTypeDefAction, notApplicableReason: info.error }, - { ...extractToTypeAliasAction, notApplicableReason: info.error }, - { ...extractToInterfaceAction, notApplicableReason: info.error } - ] + actions: [{ + ...extractToTypeDefAction, + notApplicableReason: info.error + }, { + ...extractToTypeAliasAction, + notApplicableReason: info.error + }, { + ...extractToInterfaceAction, + notApplicableReason: info.error + }] }]; } return emptyArray; }, getEditsForAction: function getRefactorEditsToExtractType(context, actionName2) { - const { file } = context; + const { + file + } = context; const info = getRangeToExtract(context); Debug.assert(info && !isRefactorErrorInfo(info), "Expected to find a range to extract"); const name = getUniqueName("NewType", file); - const edits = ts_textChanges_exports.ChangeTracker.with(context, (changes) => { + const edits = ts_textChanges_exports.ChangeTracker.with(context, changes => { switch (actionName2) { case extractToTypeAliasAction.name: Debug.assert(!info.isJS, "Invalid actionName/JS combo"); @@ -137505,14 +122795,13 @@ ${lanes.join("\n")} } }); const renameFilename = file.fileName; - const renameLocation = getRenameLocation( + const renameLocation = getRenameLocation(edits, renameFilename, name, /*preferLastLocation*/ + false); + return { edits, renameFilename, - name, - /*preferLastLocation*/ - false - ); - return { edits, renameFilename, renameLocation }; + renameLocation + }; } }); } @@ -137523,8 +122812,7 @@ ${lanes.join("\n")} return info.error !== void 0; } function refactorKindBeginsWith(known, requested) { - if (!requested) - return true; + if (!requested) return true; return known.substr(0, requested.length) === requested; } var init_helpers = __esm({ @@ -137544,25 +122832,28 @@ ${lanes.join("\n")} } 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) }; + 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 }; + return references && { + references, + declaration: parent2, + replacement: parent2.initializer + }; } if (tryWithReferenceToken) { - let definition = checker.resolveName( - token.text, - token, - 111551 /* Value */, - /*excludeGlobals*/ - false - ); + 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) }; + return { + error: getLocaleSpecificMessage(Diagnostics.Variables_with_multiple_declarations_cannot_be_inlined) + }; } const declaration = definition.declarations[0]; if (!isInitializedVariable(declaration) || !isVariableDeclarationInVariableStatement(declaration) || !isIdentifier(declaration.name)) { @@ -137572,9 +122863,15 @@ ${lanes.join("\n")} return void 0; } const references = getReferenceNodes(declaration, checker, file); - return references && { references, declaration, replacement: declaration.initializer }; + return references && { + references, + declaration, + replacement: declaration.initializer + }; } - return { error: getLocaleSpecificMessage(Diagnostics.Could_not_find_variable_to_inline) }; + return { + error: getLocaleSpecificMessage(Diagnostics.Could_not_find_variable_to_inline) + }; } function isDeclarationExported(declaration) { const variableStatement = cast(declaration.parent.parent, isVariableStatement); @@ -137582,7 +122879,7 @@ ${lanes.join("\n")} } function getReferenceNodes(declaration, checker, file) { const references = []; - const cannotInline = ts_FindAllReferences_exports.Core.eachSymbolReferenceInFile(declaration.name, checker, file, (ref) => { + const cannotInline = ts_FindAllReferences_exports.Core.eachSymbolReferenceInFile(declaration.name, checker, file, ref => { if (ts_FindAllReferences_exports.isWriteAccessForReference(ref)) { return true; } @@ -137601,7 +122898,9 @@ ${lanes.join("\n")} } function getReplacementExpression(reference, replacement) { replacement = getSynthesizedDeepClone(replacement); - const { parent: parent2 } = reference; + const { + parent: parent2 + } = reference; if (isExpression(parent2) && (getExpressionPrecedence(replacement) < getExpressionPrecedence(parent2) || needsParentheses(parent2))) { return factory.createParenthesizedExpression(replacement); } @@ -137617,6 +122916,7 @@ ${lanes.join("\n")} var init_inlineVariable = __esm({ "src/services/refactors/inlineVariable.ts"() { "use strict"; + init_ts4(); init_ts_refactor(); refactorName4 = "Inline variable"; @@ -137661,25 +122961,30 @@ ${lanes.join("\n")} }, getEditsForAction(context, actionName2) { Debug.assert(actionName2 === refactorName4, "Unexpected refactor invoked"); - const { file, program, startPosition } = context; - const info = getInliningInfo( + const { file, - startPosition, - /*tryWithReferenceToken*/ - true, - program - ); + 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) => { + 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 }; + return { + edits + }; } }); } @@ -137704,14 +123009,8 @@ ${lanes.join("\n")} 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 - ); + insertImports(changes, oldFile, importsFromNewFile, /*blankLineBetween*/ + true, preferences); } deleteUnusedOldImports(oldFile, toMove.all, changes, usage.unusedImportsFromOldFile, checker); deleteMovedStatements(oldFile, toMove.ranges, changes); @@ -137719,39 +123018,28 @@ ${lanes.join("\n")} 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, 4 /* NewLineTrivia */, ...body]; } - return [ - ...prologueDirectives, - ...imports, - ...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)))); + 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) => { + newFileImportsFromOldFile.forEach(symbol => { if (!symbol.declarations) { return; } for (const decl of symbol.declarations) { - if (!isTopLevelDeclaration(decl)) - continue; + if (!isTopLevelDeclaration(decl)) continue; const name = nameOfTopLevelDeclaration(decl); - if (!name) - continue; + if (!name) continue; const top = getTopLevelDeclarationStatement(decl); if (markSeenTop(top)) { addExportToChanges(oldFile, top, name, changes, useEsModuleSyntax); @@ -137770,6 +123058,7 @@ ${lanes.join("\n")} var init_moveToNewFile = __esm({ "src/services/refactors/moveToNewFile.ts"() { "use strict"; + init_ts4(); init_ts_refactor(); refactorName5 = "Move to a new file"; @@ -137784,18 +123073,33 @@ ${lanes.join("\n")} getAvailableActions: function getRefactorActionsToMoveToNewFile(context) { const statements = getStatementsToMove(context); if (context.preferences.allowTextChangesInNewFiles && statements) { - return [{ name: refactorName5, description, actions: [moveToNewFileAction] }]; + return [{ + name: refactorName5, + description, + actions: [moveToNewFileAction] + }]; } if (context.preferences.provideRefactorNotApplicableReason) { - return [{ name: refactorName5, description, actions: [{ ...moveToNewFileAction, notApplicableReason: getLocaleSpecificMessage(Diagnostics.Selection_is_not_a_valid_statement_or_statements) }] }]; + 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, context)); - return { edits, renameFilename: void 0, renameLocation: void 0 }; + const edits = ts_textChanges_exports.ChangeTracker.with(context, t => doChange3(context.file, context.program, statements, t, context.host, context.preferences, context)); + return { + edits, + renameFilename: void 0, + renameLocation: void 0 + }; } }); } @@ -137803,7 +123107,12 @@ ${lanes.join("\n")} // src/services/refactors/moveToFile.ts function error(notApplicableReason) { - return { edits: [], renameFilename: void 0, renameLocation: void 0, notApplicableReason }; + return { + edits: [], + renameFilename: void 0, + renameLocation: void 0, + notApplicableReason + }; } function doChange4(context, oldFile, targetFile, program, toMove, changes, host, preferences) { const checker = program.getTypeChecker(); @@ -137828,14 +123137,8 @@ ${lanes.join("\n")} const quotePreference = getQuotePreference(oldFile, preferences); const importsFromTargetFile = createOldFileImportsFromTargetFile(oldFile, usage.oldFileImportsFromTargetFile, targetFileName, program, host, useEsModuleSyntax, quotePreference); if (importsFromTargetFile) { - insertImports( - changes, - oldFile, - importsFromTargetFile, - /*blankLineBetween*/ - true, - preferences - ); + insertImports(changes, oldFile, importsFromTargetFile, /*blankLineBetween*/ + true, preferences); } deleteUnusedOldImports(oldFile, toMove.all, changes, usage.unusedImportsFromOldFile, checker); deleteMovedStatements(oldFile, toMove.ranges, changes); @@ -137846,40 +123149,21 @@ ${lanes.join("\n")} if (targetFile.statements.length > 0) { moveStatementsToTargetFile(changes, program, body, targetFile, toMove); } else { - changes.insertNodesAtEndOfFile( - targetFile, - body, - /*blankLineBetween*/ - false - ); + changes.insertNodesAtEndOfFile(targetFile, body, /*blankLineBetween*/ + false); } if (imports.length > 0) { - insertImports( - changes, - targetFile, - imports, - /*blankLineBetween*/ - true, - preferences - ); + 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, 4 /* NewLineTrivia */, ...body]; } - return [ - ...prologueDirectives, - ...imports, - ...body - ]; + return [...prologueDirectives, ...imports, ...body]; } function getTargetFileImportsAndAddExportInOldFile(oldFile, targetFile, importsToCopy, targetFileImportsFromOldFile, changes, checker, program, host, useEsModuleSyntax, quotePreference, importAdder) { const copiedOldImports = []; @@ -137889,8 +123173,8 @@ ${lanes.join("\n")} 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)))); + forEachImportInStatement(oldStatement, i => { + append(copiedOldImports, filterImport(i, factory.createStringLiteral(moduleSpecifierFromImport(i).text), name => importsToCopy.has(checker.getSymbolAtLocation(name)))); }); } } @@ -137898,16 +123182,16 @@ ${lanes.join("\n")} } else { const targetSourceFile = program.getSourceFile(targetFile); for (const oldStatement of oldFile.statements) { - forEachImportInStatement(oldStatement, (i) => { + forEachImportInStatement(oldStatement, i => { var _a; const moduleSpecifier = moduleSpecifierFromImport(i); const resolved = program.getResolvedModule(oldFile, moduleSpecifier.text, getModeForUsageLocation(oldFile, moduleSpecifier)); const fileName = (_a = resolved == null ? void 0 : resolved.resolvedModule) == null ? void 0 : _a.resolvedFileName; if (fileName && targetSourceFile) { const newModuleSpecifier = getModuleSpecifier(program.getCompilerOptions(), targetSourceFile, targetSourceFile.path, fileName, createModuleSpecifierResolutionHost(program, host)); - append(copiedOldImports, filterImport(i, makeStringLiteral(newModuleSpecifier, quotePreference), (name) => importsToCopy.has(checker.getSymbolAtLocation(name)))); + 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)))); + append(copiedOldImports, filterImport(i, factory.createStringLiteral(moduleSpecifierFromImport(i).text), name => importsToCopy.has(checker.getSymbolAtLocation(name)))); } }); } @@ -137916,16 +123200,14 @@ ${lanes.join("\n")} let oldFileDefault; const oldFileNamedImports = []; const markSeenTop = nodeSeenTracker(); - targetFileImportsFromOldFile.forEach((symbol) => { + targetFileImportsFromOldFile.forEach(symbol => { if (!symbol.declarations) { return; } for (const decl of symbol.declarations) { - if (!isTopLevelDeclaration(decl)) - continue; + if (!isTopLevelDeclaration(decl)) continue; const name = nameOfTopLevelDeclaration(decl); - if (!name) - continue; + if (!name) continue; const top = getTopLevelDeclarationStatement(decl); if (markSeenTop(top)) { addExportToChanges(oldFile, top, name, changes, useEsModuleSyntax); @@ -137945,38 +123227,37 @@ ${lanes.join("\n")} } 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); - const filesProp = cfgObject && find(cfgObject.properties, (prop) => isPropertyAssignment(prop) && isStringLiteral(prop.name) && prop.name.text === "files"); + const filesProp = cfgObject && find(cfgObject.properties, prop => isPropertyAssignment(prop) && isStringLiteral(prop.name) && prop.name.text === "files"); if (filesProp && isArrayLiteralExpression(filesProp.initializer)) { changes.insertNodeInListAfter(cfg, last(filesProp.initializer.elements), factory.createStringLiteral(newFilePath), filesProp.initializer.elements); } } function deleteMovedStatements(sourceFile, moved, changes) { - for (const { first: first2, afterLast } of moved) { + for (const { + first: first2, + afterLast + } of moved) { changes.deleteNodeRangeExcludingEnd(sourceFile, first2, afterLast); } } function deleteUnusedOldImports(oldFile, toMove, changes, toDelete, checker) { for (const statement of oldFile.statements) { - if (contains(toMove, statement)) - continue; - forEachImportInStatement(statement, (i) => deleteUnusedImports(oldFile, i, changes, (name) => toDelete.has(checker.getSymbolAtLocation(name)))); + if (contains(toMove, statement)) continue; + forEachImportInStatement(statement, i => deleteUnusedImports(oldFile, i, changes, name => toDelete.has(checker.getSymbolAtLocation(name)))); } } 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; - const shouldMove = (name) => { + forEachImportInStatement(statement, importNode => { + if (checker.getSymbolAtLocation(moduleSpecifierFromImport(importNode)) !== oldFile.symbol) return; + const shouldMove = name => { const symbol = isBindingElement(name.parent) ? getPropertySymbolFromBindingElement(checker, name.parent) : skipAlias(checker.getSymbolAtLocation(name), checker); return !!symbol && movedSymbols.has(symbol); }; @@ -137984,11 +123265,9 @@ ${lanes.join("\n")} const pathToTargetFileWithExtension = resolvePath(getDirectoryPath(oldFile.path), targetFileName); const newModuleSpecifier = getModuleSpecifier(program.getCompilerOptions(), sourceFile, sourceFile.path, pathToTargetFileWithExtension, createModuleSpecifierResolutionHost(program, host)); const newImportDeclaration = filterImport(importNode, makeStringLiteral(newModuleSpecifier, quotePreference), shouldMove); - if (newImportDeclaration) - changes.insertNodeAfter(sourceFile, statement, newImportDeclaration); + 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); }); } } @@ -138009,16 +123288,10 @@ ${lanes.join("\n")} const preferredNewNamespaceName = ts_codefix_exports.moduleSpecifierToValidIdentifier(newModuleSpecifier, 99 /* ESNext */); let needUniqueName = false; const toChange = []; - ts_FindAllReferences_exports.Core.eachSymbolReferenceInFile(oldImportId, checker, sourceFile, (ref) => { - if (!isPropertyAccessExpression(ref.parent)) - return; - needUniqueName = needUniqueName || !!checker.resolveName( - preferredNewNamespaceName, - ref, - 67108863 /* All */, - /*excludeGlobals*/ - true - ); + ts_FindAllReferences_exports.Core.eachSymbolReferenceInFile(oldImportId, checker, sourceFile, ref => { + if (!isPropertyAccessExpression(ref.parent)) return; + needUniqueName = needUniqueName || !!checker.resolveName(preferredNewNamespaceName, ref, 67108863 /* All */, /*excludeGlobals*/ + true); if (movedSymbols.has(checker.getSymbolAtLocation(ref.parent.name))) { toChange.push(ref); } @@ -138036,68 +123309,41 @@ ${lanes.join("\n")} const newModuleString = makeStringLiteral(newModuleSpecifier, quotePreference); switch (node.kind) { case 272 /* ImportDeclaration */: - return factory.createImportDeclaration( - /*modifiers*/ - void 0, - factory.createImportClause( - /*isTypeOnly*/ - false, - /*name*/ - void 0, - factory.createNamespaceImport(newNamespaceId) - ), - newModuleString, - /*attributes*/ - void 0 - ); + return factory.createImportDeclaration( /*modifiers*/ + void 0, factory.createImportClause( /*isTypeOnly*/ + false, /*name*/ + void 0, factory.createNamespaceImport(newNamespaceId)), newModuleString, /*attributes*/ + void 0); case 271 /* ImportEqualsDeclaration */: - return factory.createImportEqualsDeclaration( - /*modifiers*/ - void 0, - /*isTypeOnly*/ - false, - newNamespaceId, - factory.createExternalModuleReference(newModuleString) - ); + return factory.createImportEqualsDeclaration( /*modifiers*/ + void 0, /*isTypeOnly*/ + false, newNamespaceId, factory.createExternalModuleReference(newModuleString)); case 260 /* VariableDeclaration */: - return factory.createVariableDeclaration( - newNamespaceId, - /*exclamationToken*/ - void 0, - /*type*/ - void 0, - createRequireCall(newModuleString) - ); + return factory.createVariableDeclaration(newNamespaceId, /*exclamationToken*/ + void 0, /*type*/ + void 0, createRequireCall(newModuleString)); default: return Debug.assertNever(node, `Unexpected node kind ${node.kind}`); } } function createRequireCall(moduleSpecifier) { - return factory.createCallExpression( - factory.createIdentifier("require"), - /*typeArguments*/ - void 0, - [moduleSpecifier] - ); + return factory.createCallExpression(factory.createIdentifier("require"), /*typeArguments*/ + void 0, [moduleSpecifier]); } function moduleSpecifierFromImport(i) { return i.kind === 272 /* ImportDeclaration */ ? i.moduleSpecifier : i.kind === 271 /* ImportEqualsDeclaration */ ? i.moduleReference.expression : i.initializer.arguments[0]; } function forEachImportInStatement(statement, cb) { if (isImportDeclaration(statement)) { - if (isStringLiteral(statement.moduleSpecifier)) - cb(statement); + if (isStringLiteral(statement.moduleSpecifier)) cb(statement); } else if (isImportEqualsDeclaration(statement)) { if (isExternalModuleReference(statement.moduleReference) && isStringLiteralLike(statement.moduleReference.expression)) { cb(statement); } } else if (isVariableStatement(statement)) { for (const decl of statement.declarationList.declarations) { - if (decl.initializer && isRequireCall( - decl.initializer, - /*requireStringLiteralLikeArgument*/ - true - )) { + if (decl.initializer && isRequireCall(decl.initializer, /*requireStringLiteralLikeArgument*/ + true)) { cb(decl); } } @@ -138106,7 +123352,7 @@ ${lanes.join("\n")} function createOldFileImportsFromTargetFile(sourceFile, targetFileNeedExport, targetFileNameWithExtension, program, host, useEs6Imports, quotePreference) { let defaultImport; const imports = []; - targetFileNeedExport.forEach((symbol) => { + targetFileNeedExport.forEach(symbol => { if (symbol.escapedName === "default" /* Default */) { defaultImport = factory.createIdentifier(symbolNameNoDefault(symbol)); } else { @@ -138119,53 +123365,32 @@ ${lanes.join("\n")} const pathToTargetFile = resolvePath(getDirectoryPath(sourceFile.path), targetFileNameWithExtension); const pathToTargetFileWithCorrectExtension = getModuleSpecifier(program.getCompilerOptions(), sourceFile, sourceFile.path, pathToTargetFile, createModuleSpecifierResolutionHost(program, host)); if (useEs6Imports) { - const specifiers = imports.map((i) => factory.createImportSpecifier( - /*isTypeOnly*/ - false, - /*propertyName*/ - void 0, - factory.createIdentifier(i) - )); + 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; + 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 makeVariableStatement(name, type, initializer, flags = 2 /* Const */) { - return factory.createVariableStatement( - /*modifiers*/ - void 0, - factory.createVariableDeclarationList([factory.createVariableDeclaration( - name, - /*exclamationToken*/ - void 0, - type, - initializer - )], flags) - ); + return factory.createVariableStatement( /*modifiers*/ + void 0, factory.createVariableDeclarationList([factory.createVariableDeclaration(name, /*exclamationToken*/ + void 0, type, initializer)], flags)); } function addExports(sourceFile, toMove, needExport, useEs6Exports) { - return flatMap(toMove, (statement) => { - if (isTopLevelDeclarationStatement(statement) && !isExported(sourceFile, statement, useEs6Exports) && forEachTopLevelDeclaration(statement, (d) => { + return flatMap(toMove, statement => { + if (isTopLevelDeclarationStatement(statement) && !isExported(sourceFile, statement, useEs6Exports) && forEachTopLevelDeclaration(statement, d => { var _a; return needExport.has(Debug.checkDefined((_a = tryCast(d, canHaveSymbol)) == null ? void 0 : _a.symbol)); })) { const exports = addExport(getSynthesizedDeepClone(statement), useEs6Exports); - if (exports) - return exports; + if (exports) return exports; } return getSynthesizedDeepClone(statement); }); @@ -138175,7 +123400,7 @@ ${lanes.join("\n")} if (useEs6Exports) { return !isExpressionStatement(decl) && hasSyntacticModifier(decl, 32 /* Export */) || !!(name && sourceFile.symbol && ((_a = sourceFile.symbol.exports) == null ? void 0 : _a.has(name.escapedText))); } - return !!sourceFile.symbol && !!sourceFile.symbol.exports && getNamesToExportInCommonJS(decl).some((name2) => sourceFile.symbol.exports.has(escapeLeadingUnderscores(name2))); + 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) { @@ -138195,11 +123420,13 @@ ${lanes.join("\n")} } } function deleteUnusedImportsInDeclaration(sourceFile, importDecl, changes, isUnused) { - if (!importDecl.importClause) - return; - const { name, namedBindings } = importDecl.importClause; + 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))); + 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 { @@ -138208,36 +123435,25 @@ ${lanes.join("\n")} } if (namedBindings) { if (namedBindingsUnused) { - changes.replaceNode( - sourceFile, - importDecl.importClause, - factory.updateImportClause( - importDecl.importClause, - importDecl.importClause.isTypeOnly, - name, - /*namedBindings*/ - void 0 - ) - ); + 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 (isUnused(element.name)) changes.delete(sourceFile, element); } } } } } function deleteUnusedImportsInVariableDeclaration(sourceFile, varDecl, changes, isUnused) { - const { name } = varDecl; + const { + name + } = varDecl; switch (name.kind) { case 80 /* Identifier */: if (isUnused(name)) { - if (varDecl.initializer && isRequireCall( - varDecl.initializer, - /*requireStringLiteralLikeArgument*/ - true - )) { + 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); @@ -138247,7 +123463,7 @@ ${lanes.join("\n")} case 207 /* ArrayBindingPattern */: break; case 206 /* ObjectBindingPattern */: - if (name.elements.every((e) => isIdentifier(e.name) && isUnused(e.name))) { + 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) { @@ -138296,13 +123512,7 @@ ${lanes.join("\n")} return [decl, ...getNamesToExportInCommonJS(decl).map(createExportAssignment)]; } function createExportAssignment(name) { - return factory.createExpressionStatement( - factory.createBinaryExpression( - factory.createPropertyAccessExpression(factory.createIdentifier("exports"), factory.createIdentifier(name)), - 64 /* EqualsToken */, - factory.createIdentifier(name) - ) - ); + return factory.createExpressionStatement(factory.createBinaryExpression(factory.createPropertyAccessExpression(factory.createIdentifier("exports"), factory.createIdentifier(name)), 64 /* EqualsToken */, factory.createIdentifier(name))); } function getNamesToExportInCommonJS(decl) { switch (decl.kind) { @@ -138310,7 +123520,7 @@ ${lanes.join("\n")} case 263 /* ClassDeclaration */: return [decl.name.text]; case 243 /* VariableStatement */: - return mapDefined(decl.declarationList.declarations, (d) => isIdentifier(d.name) ? d.name.text : void 0); + return mapDefined(decl.declarationList.declarations, d => isIdentifier(d.name) ? d.name.text : void 0); case 267 /* ModuleDeclaration */: case 266 /* EnumDeclaration */: case 265 /* TypeAliasDeclaration */: @@ -138325,27 +123535,23 @@ ${lanes.join("\n")} } function filterImport(i, moduleSpecifier, keep) { switch (i.kind) { - case 272 /* ImportDeclaration */: { - const clause = i.importClause; - if (!clause) - return void 0; - const defaultImport = clause.name && keep(clause.name) ? clause.name : void 0; - const namedBindings = clause.namedBindings && filterNamedBindings(clause.namedBindings, keep); - return defaultImport || namedBindings ? factory.createImportDeclaration( - /*modifiers*/ - void 0, - factory.createImportClause(clause.isTypeOnly, defaultImport, namedBindings), - getSynthesizedDeepClone(moduleSpecifier), - /*attributes*/ - void 0 - ) : void 0; - } + case 272 /* ImportDeclaration */: + { + const clause = i.importClause; + if (!clause) return void 0; + const defaultImport = clause.name && keep(clause.name) ? clause.name : void 0; + const namedBindings = clause.namedBindings && filterNamedBindings(clause.namedBindings, keep); + return defaultImport || namedBindings ? factory.createImportDeclaration( /*modifiers*/ + void 0, factory.createImportClause(clause.isTypeOnly, defaultImport, namedBindings), getSynthesizedDeepClone(moduleSpecifier), /*attributes*/ + void 0) : void 0; + } case 271 /* ImportEqualsDeclaration */: return keep(i.name) ? i : void 0; - case 260 /* VariableDeclaration */: { - const name = filterBindingName(i.name, keep); - return name ? makeVariableStatement(name, i.type, createRequireCall(moduleSpecifier), i.parent.flags) : void 0; - } + case 260 /* VariableDeclaration */: + { + const name = filterBindingName(i.name, keep); + return name ? makeVariableStatement(name, i.type, createRequireCall(moduleSpecifier), i.parent.flags) : void 0; + } default: return Debug.assertNever(i, `Unexpected import kind ${i.kind}`); } @@ -138354,7 +123560,7 @@ ${lanes.join("\n")} if (namedBindings.kind === 274 /* NamespaceImport */) { return keep(namedBindings.name) ? namedBindings : void 0; } else { - const newElements = namedBindings.elements.filter((e) => keep(e.name)); + const newElements = namedBindings.elements.filter(e => keep(e.name)); return newElements.length ? factory.createNamedImports(newElements) : void 0; } } @@ -138364,10 +123570,11 @@ ${lanes.join("\n")} return keep(name) ? name : void 0; case 207 /* ArrayBindingPattern */: return name; - case 206 /* ObjectBindingPattern */: { - const newElements = name.elements.filter((prop) => prop.propertyName || !isIdentifier(prop.name) || keep(prop.name)); - return newElements.length ? factory.createObjectBindingPattern(newElements) : void 0; - } + case 206 /* ObjectBindingPattern */: + { + const newElements = name.elements.filter(prop => prop.propertyName || !isIdentifier(prop.name) || keep(prop.name)); + return newElements.length ? factory.createObjectBindingPattern(newElements) : void 0; + } } } function nameOfTopLevelDeclaration(d) { @@ -138378,23 +123585,18 @@ ${lanes.join("\n")} case 260 /* VariableDeclaration */: return d.parent.parent; case 208 /* BindingElement */: - return getTopLevelDeclarationStatement( - cast(d.parent.parent, (p) => isVariableDeclaration(p) || isBindingElement(p)) - ); + return getTopLevelDeclarationStatement(cast(d.parent.parent, p => isVariableDeclaration(p) || isBindingElement(p))); default: return d; } } function addExportToChanges(sourceFile, decl, name, changes, useEs6Exports) { - if (isExported(sourceFile, decl, useEs6Exports, name)) - return; + if (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, context, host) { @@ -138406,34 +123608,32 @@ ${lanes.join("\n")} const currentDirectory = getDirectoryPath(oldFile.fileName); const extension = extensionFromPath(oldFile.fileName); const newFileName = combinePaths( - // new file is always placed in the same directory as the old file - currentDirectory, - // ensures the filename computed below isn't already taken - makeUniqueFilename( - // infers a name for the new file from the symbols being moved - inferNewFileName(usage.oldFileImportsFromTargetFile, usage.movedSymbols), - extension, - currentDirectory, - host - ) - ) + extension; + // new file is always placed in the same directory as the old file + currentDirectory, + // ensures the filename computed below isn't already taken + makeUniqueFilename( + // infers a name for the new file from the symbols being moved + inferNewFileName(usage.oldFileImportsFromTargetFile, usage.movedSymbols), extension, currentDirectory, host)) + extension; return newFileName; } return ""; } function getRangeToMove(context) { - const { file } = context; + const { + file + } = context; const range = createTextRangeFromSpan(getRefactorContextSpan(context)); - const { statements } = file; - let startNodeIndex = findIndex(statements, (s) => s.end > range.pos); - if (startNodeIndex === -1) - return void 0; + const { + statements + } = file; + let startNodeIndex = findIndex(statements, s => s.end > range.pos); + if (startNodeIndex === -1) return void 0; const startStatement = statements[startNodeIndex]; const overloadRangeToMove = getOverloadRangeToMove(file, startStatement); if (overloadRangeToMove) { startNodeIndex = overloadRangeToMove.start; } - let endNodeIndex = findIndex(statements, (s) => s.end >= range.end, startNodeIndex); + let endNodeIndex = findIndex(statements, s => s.end >= range.end, startNodeIndex); if (endNodeIndex !== -1 && range.end <= statements[endNodeIndex].getStart()) { endNodeIndex--; } @@ -138448,17 +123648,24 @@ ${lanes.join("\n")} } 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; + const { + toMove, + afterLast + } = rangeToMove; getRangesWhere(toMove, isAllowedStatementToMove, (start, afterEndIndex) => { - for (let i = start; i < afterEndIndex; i++) - all.push(toMove[i]); - ranges.push({ first: toMove[start], afterLast }); + 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 }; + return all.length === 0 ? void 0 : { + all, + ranges + }; } function isAllowedStatementToMove(statement) { return !isPureImport(statement) && !isPrologueDirective(statement); @@ -138470,30 +123677,27 @@ ${lanes.join("\n")} case 271 /* ImportEqualsDeclaration */: return !hasSyntacticModifier(node, 32 /* Export */); case 243 /* VariableStatement */: - return node.declarationList.declarations.every((d) => !!d.initializer && isRequireCall( - d.initializer, - /*requireStringLiteralLikeArgument*/ - true - )); + return node.declarationList.declarations.every(d => !!d.initializer && isRequireCall(d.initializer, /*requireStringLiteralLikeArgument*/ + true)); default: return false; } } - function getUsageInfo(oldFile, toMove, checker, existingTargetImports = /* @__PURE__ */ new Set()) { - const movedSymbols = /* @__PURE__ */ new Set(); - const oldImportsNeededByTargetFile = /* @__PURE__ */ new Map(); - const targetFileImportsFromOldFile = /* @__PURE__ */ new Set(); - const containsJsx = find(toMove, (statement) => !!(statement.transformFlags & 2 /* ContainsJsx */)); + function getUsageInfo(oldFile, toMove, checker, existingTargetImports = /* @__PURE__ */new Set()) { + const movedSymbols = /* @__PURE__ */new Set(); + const oldImportsNeededByTargetFile = /* @__PURE__ */new Map(); + const targetFileImportsFromOldFile = /* @__PURE__ */new Set(); + const containsJsx = find(toMove, statement => !!(statement.transformFlags & 2 /* ContainsJsx */)); const jsxNamespaceSymbol = getJsxNamespaceSymbol(containsJsx); if (jsxNamespaceSymbol) { oldImportsNeededByTargetFile.set(jsxNamespaceSymbol, false); } for (const statement of toMove) { - forEachTopLevelDeclaration(statement, (decl) => { + forEachTopLevelDeclaration(statement, decl => { movedSymbols.add(Debug.checkDefined(isExpressionStatement(decl) ? checker.getSymbolAtLocation(decl.expression.left) : decl.symbol, "Need a symbol here")); }); } - const unusedImportsFromOldFile = /* @__PURE__ */ new Set(); + const unusedImportsFromOldFile = /* @__PURE__ */new Set(); for (const statement of toMove) { forEachReference(statement, checker, (symbol, isValidTypeOnlyUseSite) => { if (!symbol.declarations) { @@ -138516,41 +123720,39 @@ ${lanes.join("\n")} for (const unusedImport of oldImportsNeededByTargetFile.keys()) { unusedImportsFromOldFile.add(unusedImport); } - const oldFileImportsFromTargetFile = /* @__PURE__ */ new Set(); + const oldFileImportsFromTargetFile = /* @__PURE__ */new Set(); 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 => { + if (movedSymbols.has(symbol)) oldFileImportsFromTargetFile.add(symbol); unusedImportsFromOldFile.delete(symbol); }); } - return { movedSymbols, targetFileImportsFromOldFile, oldFileImportsFromTargetFile, oldImportsNeededByTargetFile, unusedImportsFromOldFile }; + return { + movedSymbols, + targetFileImportsFromOldFile, + oldFileImportsFromTargetFile, + oldImportsNeededByTargetFile, + unusedImportsFromOldFile + }; function getJsxNamespaceSymbol(containsJsx2) { if (containsJsx2 === void 0) { return void 0; } const jsxNamespace = checker.getJsxNamespace(containsJsx2); - const jsxNamespaceSymbol2 = checker.resolveName( - jsxNamespace, - containsJsx2, - 1920 /* Namespace */, - /*excludeGlobals*/ - true - ); + const jsxNamespaceSymbol2 = checker.resolveName(jsxNamespace, containsJsx2, 1920 /* Namespace */, /*excludeGlobals*/ + true); return !!jsxNamespaceSymbol2 && some(jsxNamespaceSymbol2.declarations, isInImport) ? jsxNamespaceSymbol2 : void 0; } } function makeUniqueFilename(proposedFilename, extension, inDirectory, host) { let newFilename = proposedFilename; - for (let i = 1; ; i++) { + 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}`; } } @@ -138561,8 +123763,7 @@ ${lanes.join("\n")} 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); } @@ -138579,11 +123780,14 @@ ${lanes.join("\n")} case 271 /* ImportEqualsDeclaration */: return cb(statement); case 243 /* VariableStatement */: - return firstDefined(statement.declarationList.declarations, (decl) => forEachTopLevelDeclarationInBindingName(decl.name, cb)); - case 244 /* ExpressionStatement */: { - const { expression } = statement; - return isBinaryExpression(expression) && getAssignmentDeclarationKind(expression) === 1 /* ExportsProperty */ ? cb(statement) : void 0; - } + return firstDefined(statement.declarationList.declarations, decl => forEachTopLevelDeclarationInBindingName(decl.name, cb)); + case 244 /* ExpressionStatement */: + { + const { + expression + } = statement; + return isBinaryExpression(expression) && getAssignmentDeclarationKind(expression) === 1 /* ExportsProperty */ ? cb(statement) : void 0; + } } } function isInImport(decl) { @@ -138602,11 +123806,8 @@ ${lanes.join("\n")} } } function isVariableDeclarationInImport(decl) { - return isSourceFile(decl.parent.parent.parent) && !!decl.initializer && isRequireCall( - decl.initializer, - /*requireStringLiteralLikeArgument*/ - true - ); + return isSourceFile(decl.parent.parent.parent) && !!decl.initializer && isRequireCall(decl.initializer, /*requireStringLiteralLikeArgument*/ + true); } function isTopLevelDeclaration(node) { return isNonVariableTopLevelDeclaration(node) && isSourceFile(node.parent) || isVariableDeclaration(node) && isSourceFile(node.parent.parent.parent); @@ -138617,10 +123818,10 @@ ${lanes.join("\n")} function forEachTopLevelDeclarationInBindingName(name, cb) { switch (name.kind) { case 80 /* Identifier */: - return cb(cast(name.parent, (x) => isVariableDeclaration(x) || isBindingElement(x))); + return cb(cast(name.parent, x => isVariableDeclaration(x) || isBindingElement(x))); case 207 /* ArrayBindingPattern */: case 206 /* ObjectBindingPattern */: - return firstDefined(name.elements, (em) => isOmittedExpression(em) ? void 0 : forEachTopLevelDeclarationInBindingName(em.name, cb)); + return firstDefined(name.elements, em => isOmittedExpression(em) ? void 0 : forEachTopLevelDeclarationInBindingName(em.name, cb)); default: return Debug.assertNever(name, `Unexpected name kind ${name.kind}`); } @@ -138641,19 +123842,19 @@ ${lanes.join("\n")} } function moveStatementsToTargetFile(changes, program, statements, targetFile, toMove) { var _a; - const removedExports = /* @__PURE__ */ new Set(); + const removedExports = /* @__PURE__ */new Set(); const targetExports = (_a = targetFile.symbol) == null ? void 0 : _a.exports; if (targetExports) { const checker = program.getTypeChecker(); - const targetToSourceExports = /* @__PURE__ */ new Map(); + const targetToSourceExports = /* @__PURE__ */new Map(); for (const node of toMove.all) { if (isTopLevelDeclarationStatement(node) && hasSyntacticModifier(node, 32 /* Export */)) { - forEachTopLevelDeclaration(node, (declaration) => { + forEachTopLevelDeclaration(node, declaration => { var _a2; const targetDeclarations = canHaveSymbol(declaration) ? (_a2 = targetExports.get(declaration.symbol.escapedName)) == null ? void 0 : _a2.declarations : void 0; - const exportDeclaration = firstDefined(targetDeclarations, (d) => isExportDeclaration(d) ? d : isExportSpecifier(d) ? tryCast(d.parent.parent, isExportDeclaration) : void 0); + const exportDeclaration = firstDefined(targetDeclarations, d => isExportDeclaration(d) ? d : isExportSpecifier(d) ? tryCast(d.parent.parent, isExportDeclaration) : void 0); if (exportDeclaration && exportDeclaration.moduleSpecifier) { - targetToSourceExports.set(exportDeclaration, (targetToSourceExports.get(exportDeclaration) || /* @__PURE__ */ new Set()).add(declaration)); + targetToSourceExports.set(exportDeclaration, (targetToSourceExports.get(exportDeclaration) || /* @__PURE__ */new Set()).add(declaration)); } }); } @@ -138661,7 +123862,7 @@ ${lanes.join("\n")} for (const [exportDeclaration, topLevelDeclarations] of arrayFrom(targetToSourceExports)) { if (exportDeclaration.exportClause && isNamedExports(exportDeclaration.exportClause) && length(exportDeclaration.exportClause.elements)) { const elements = exportDeclaration.exportClause.elements; - const updatedElements = filter(elements, (elem) => find(skipAlias(elem.symbol, checker).declarations, (d) => isTopLevelDeclaration(d) && topLevelDeclarations.has(d)) === void 0); + const updatedElements = filter(elements, elem => find(skipAlias(elem.symbol, checker).declarations, d => isTopLevelDeclaration(d) && topLevelDeclarations.has(d)) === void 0); if (length(updatedElements) === 0) { changes.deleteNode(targetFile, exportDeclaration); removedExports.add(exportDeclaration); @@ -138673,15 +123874,10 @@ ${lanes.join("\n")} } } } - const lastReExport = findLast(targetFile.statements, (n) => isExportDeclaration(n) && !!n.moduleSpecifier && !removedExports.has(n)); + const lastReExport = findLast(targetFile.statements, n => isExportDeclaration(n) && !!n.moduleSpecifier && !removedExports.has(n)); if (lastReExport) { - changes.insertNodesBefore( - targetFile, - lastReExport, - statements, - /*blankLineBetween*/ - true - ); + changes.insertNodesBefore(targetFile, lastReExport, statements, /*blankLineBetween*/ + true); } else { changes.insertNodesAfter(targetFile, targetFile.statements[targetFile.statements.length - 1], statements); } @@ -138694,15 +123890,19 @@ ${lanes.join("\n")} } const firstDecl = declarations[0]; const lastDecl = declarations[length(declarations) - 1]; - const statementsToMove = mapDefined(declarations, (d) => getSourceFileOfNode(d) === sourceFile && isStatement(d) ? d : void 0); - const end = findIndex(sourceFile.statements, (s) => s.end >= lastDecl.end); - const start = findIndex(sourceFile.statements, (s) => s.end >= firstDecl.end); - return { toMove: statementsToMove, start, end }; + const statementsToMove = mapDefined(declarations, d => getSourceFileOfNode(d) === sourceFile && isStatement(d) ? d : void 0); + const end = findIndex(sourceFile.statements, s => s.end >= lastDecl.end); + const start = findIndex(sourceFile.statements, s => s.end >= firstDecl.end); + return { + toMove: statementsToMove, + start, + end + }; } return void 0; } function getExistingImports(sourceFile, checker) { - const imports = /* @__PURE__ */ new Set(); + const imports = /* @__PURE__ */new Set(); for (const moduleSpecifier of sourceFile.imports) { const declaration = importFromModuleSpecifier(moduleSpecifier); if (isImportDeclaration(declaration) && declaration.importClause && declaration.importClause.namedBindings && isNamedImports(declaration.importClause.namedBindings)) { @@ -138728,6 +123928,7 @@ ${lanes.join("\n")} var init_moveToFile = __esm({ "src/services/refactors/moveToFile.ts"() { "use strict"; + init_moduleSpecifiers(); init_ts4(); init_refactorProvider(); @@ -138746,25 +123947,43 @@ ${lanes.join("\n")} return emptyArray; } if (context.preferences.allowTextChangesInNewFiles && statements) { - return [{ name: refactorNameForMoveToFile, description: description2, actions: [moveToFileAction] }]; + return [{ + name: refactorNameForMoveToFile, + description: description2, + actions: [moveToFileAction] + }]; } 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: description2, + actions: [{ + ...moveToFileAction, + notApplicableReason: getLocaleSpecificMessage(Diagnostics.Selection_is_not_a_valid_statement_or_statements) + }] + }]; } return emptyArray; }, getEditsForAction: function getRefactorEditsToMoveToFile(context, actionName2, interactiveRefactorArguments) { Debug.assert(actionName2 === refactorNameForMoveToFile, "Wrong refactor invoked"); const statements = Debug.checkDefined(getStatementsToMove(context)); - const { host, program } = context; + const { + host, + program + } = context; Debug.assert(interactiveRefactorArguments, "No interactive refactor arguments available"); const targetFile = interactiveRefactorArguments.targetFile; if (hasJSFileExtension(targetFile) || hasTSFileExtension(targetFile)) { if (host.fileExists(targetFile) && program.getSourceFile(targetFile) === void 0) { return error(getLocaleSpecificMessage(Diagnostics.Cannot_move_statements_to_the_selected_file)); } - const edits = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange4(context, context.file, interactiveRefactorArguments.targetFile, context.program, statements, t, context.host, context.preferences)); - return { edits, renameFilename: void 0, renameLocation: void 0 }; + const edits = ts_textChanges_exports.ChangeTracker.with(context, t => doChange4(context, context.file, interactiveRefactorArguments.targetFile, context.program, statements, t, context.host, context.preferences)); + return { + edits, + renameFilename: void 0, + renameLocation: void 0 + }; } return error(getLocaleSpecificMessage(Diagnostics.Cannot_move_to_file_selected_file_is_invalid)); } @@ -138774,10 +123993,13 @@ ${lanes.join("\n")} // src/services/refactors/convertOverloadListToSingleSignature.ts function getRefactorActionsToConvertOverloadsToOneSignature(context) { - const { file, startPosition, program } = 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, @@ -138785,129 +124007,85 @@ ${lanes.join("\n")} }]; } function getRefactorEditsToConvertOverloadsToOneSignature(context) { - const { file, startPosition, program } = 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; switch (lastDeclaration.kind) { - case 173 /* MethodSignature */: { - updated = factory.updateMethodSignature( - lastDeclaration, - lastDeclaration.modifiers, - lastDeclaration.name, - lastDeclaration.questionToken, - lastDeclaration.typeParameters, - getNewParametersForCombinedSignature(signatureDecls), - lastDeclaration.type - ); - break; - } - case 174 /* MethodDeclaration */: { - updated = factory.updateMethodDeclaration( - lastDeclaration, - lastDeclaration.modifiers, - lastDeclaration.asteriskToken, - lastDeclaration.name, - lastDeclaration.questionToken, - lastDeclaration.typeParameters, - getNewParametersForCombinedSignature(signatureDecls), - lastDeclaration.type, - lastDeclaration.body - ); - break; - } - case 179 /* CallSignature */: { - updated = factory.updateCallSignature( - lastDeclaration, - lastDeclaration.typeParameters, - getNewParametersForCombinedSignature(signatureDecls), - lastDeclaration.type - ); - break; - } - case 176 /* Constructor */: { - updated = factory.updateConstructorDeclaration( - lastDeclaration, - lastDeclaration.modifiers, - getNewParametersForCombinedSignature(signatureDecls), - lastDeclaration.body - ); - break; - } - case 180 /* ConstructSignature */: { - updated = factory.updateConstructSignature( - lastDeclaration, - lastDeclaration.typeParameters, - getNewParametersForCombinedSignature(signatureDecls), - lastDeclaration.type - ); - break; - } - case 262 /* FunctionDeclaration */: { - updated = factory.updateFunctionDeclaration( - lastDeclaration, - lastDeclaration.modifiers, - lastDeclaration.asteriskToken, - lastDeclaration.name, - lastDeclaration.typeParameters, - getNewParametersForCombinedSignature(signatureDecls), - lastDeclaration.type, - lastDeclaration.body - ); - break; - } + case 173 /* MethodSignature */: + { + updated = factory.updateMethodSignature(lastDeclaration, lastDeclaration.modifiers, lastDeclaration.name, lastDeclaration.questionToken, lastDeclaration.typeParameters, getNewParametersForCombinedSignature(signatureDecls), lastDeclaration.type); + break; + } + case 174 /* MethodDeclaration */: + { + updated = factory.updateMethodDeclaration(lastDeclaration, lastDeclaration.modifiers, lastDeclaration.asteriskToken, lastDeclaration.name, lastDeclaration.questionToken, lastDeclaration.typeParameters, getNewParametersForCombinedSignature(signatureDecls), lastDeclaration.type, lastDeclaration.body); + break; + } + case 179 /* CallSignature */: + { + updated = factory.updateCallSignature(lastDeclaration, lastDeclaration.typeParameters, getNewParametersForCombinedSignature(signatureDecls), lastDeclaration.type); + break; + } + case 176 /* Constructor */: + { + updated = factory.updateConstructorDeclaration(lastDeclaration, lastDeclaration.modifiers, getNewParametersForCombinedSignature(signatureDecls), lastDeclaration.body); + break; + } + case 180 /* ConstructSignature */: + { + updated = factory.updateConstructSignature(lastDeclaration, lastDeclaration.typeParameters, getNewParametersForCombinedSignature(signatureDecls), lastDeclaration.type); + break; + } + case 262 /* FunctionDeclaration */: + { + updated = factory.updateFunctionDeclaration(lastDeclaration, lastDeclaration.modifiers, lastDeclaration.asteriskToken, lastDeclaration.name, lastDeclaration.typeParameters, getNewParametersForCombinedSignature(signatureDecls), lastDeclaration.type, lastDeclaration.body); + break; + } default: return Debug.failBadSyntaxKind(lastDeclaration, "Unhandled signature kind in overload list conversion refactoring"); } if (updated === lastDeclaration) { return; } - const edits = ts_textChanges_exports.ChangeTracker.with(context, (t) => { + const edits = ts_textChanges_exports.ChangeTracker.with(context, t => { t.replaceNodeRange(file, signatureDecls[0], signatureDecls[signatureDecls.length - 1], updated); }); - return { renameFilename: void 0, renameLocation: void 0, edits }; + return { + renameFilename: void 0, + renameLocation: void 0, + edits + }; function getNewParametersForCombinedSignature(signatureDeclarations) { const lastSig = signatureDeclarations[signatureDeclarations.length - 1]; if (isFunctionLikeDeclaration(lastSig) && lastSig.body) { signatureDeclarations = signatureDeclarations.slice(0, signatureDeclarations.length - 1); } - return factory.createNodeArray([ - factory.createParameterDeclaration( - /*modifiers*/ - void 0, - factory.createToken(26 /* DotDotDotToken */), - "args", - /*questionToken*/ - void 0, - factory.createUnionTypeNode(map(signatureDeclarations, convertSignatureParametersToTuple)) - ) - ]); + return factory.createNodeArray([factory.createParameterDeclaration( /*modifiers*/ + void 0, factory.createToken(26 /* DotDotDotToken */), "args", /*questionToken*/ + void 0, factory.createUnionTypeNode(map(signatureDeclarations, convertSignatureParametersToTuple)))]); } function convertSignatureParametersToTuple(decl) { const members = map(decl.parameters, convertParameterToNamedTupleMember); - return setEmitFlags(factory.createTupleTypeNode(members), some(members, (m) => !!length(getSyntheticLeadingComments(m))) ? 0 /* None */ : 1 /* SingleLine */); + return setEmitFlags(factory.createTupleTypeNode(members), some(members, m => !!length(getSyntheticLeadingComments(m))) ? 0 /* None */ : 1 /* SingleLine */); } + function convertParameterToNamedTupleMember(p) { Debug.assert(isIdentifier(p.name)); - const result = setTextRange( - factory.createNamedTupleMember( - p.dotDotDotToken, - p.name, - p.questionToken, - p.type || factory.createKeywordTypeNode(133 /* AnyKeyword */) - ), - p - ); + const result = setTextRange(factory.createNamedTupleMember(p.dotDotDotToken, p.name, p.questionToken, p.type || factory.createKeywordTypeNode(133 /* AnyKeyword */)), p); const parameterDocComment = p.symbol && p.symbol.getDocumentationComment(checker); if (parameterDocComment) { const newComment = displayPartsToString(parameterDocComment); if (newComment.length) { setSyntheticLeadingComments(result, [{ text: `* -${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} +${newComment.split("\n").map(c => ` * ${c}`).join("\n")} `, kind: 3 /* MultiLineCommentTrivia */, pos: -1, @@ -138950,26 +124128,26 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (length(decls) <= 1) { return; } - if (!every(decls, (d) => getSourceFileOfNode(d) === file)) { + if (!every(decls, d => getSourceFileOfNode(d) === file)) { return; } if (!isConvertableSignatureDeclaration(decls[0])) { return; } const kindOne = decls[0].kind; - if (!every(decls, (d) => d.kind === kindOne)) { + if (!every(decls, d => d.kind === kindOne)) { return; } const signatureDecls = decls; - if (some(signatureDecls, (d) => !!d.typeParameters || some(d.parameters, (p) => !!p.modifiers || !isIdentifier(p.name)))) { + if (some(signatureDecls, d => !!d.typeParameters || some(d.parameters, p => !!p.modifiers || !isIdentifier(p.name)))) { return; } - const signatures = mapDefined(signatureDecls, (d) => checker.getSignatureFromDeclaration(d)); + const signatures = mapDefined(signatureDecls, d => checker.getSignatureFromDeclaration(d)); if (length(signatures) !== length(decls)) { return; } const returnOne = checker.getReturnTypeOfSignature(signatures[0]); - if (!every(signatures, (s) => checker.getReturnTypeOfSignature(s) === returnOne)) { + if (!every(signatures, s => checker.getReturnTypeOfSignature(s) === returnOne)) { return; } return signatureDecls; @@ -138978,6 +124156,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} var init_convertOverloadListToSingleSignature = __esm({ "src/services/refactors/convertOverloadListToSingleSignature.ts"() { "use strict"; + init_ts4(); init_ts_refactor(); refactorName6 = "Convert overload list to single signature"; @@ -138997,86 +124176,74 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} // src/services/refactors/addOrRemoveBracesToArrowFunction.ts function getRefactorActionsToRemoveFunctionBraces(context) { - const { file, startPosition, triggerReason } = 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, description: refactorDescription3, - actions: [ - info.addBraces ? addBracesAction : removeBracesAction - ] + actions: [info.addBraces ? addBracesAction : removeBracesAction] }]; } if (context.preferences.provideRefactorNotApplicableReason) { return [{ name: refactorName7, description: refactorDescription3, - actions: [ - { ...addBracesAction, notApplicableReason: info.error }, - { ...removeBracesAction, notApplicableReason: info.error } - ] + actions: [{ + ...addBracesAction, + notApplicableReason: info.error + }, { + ...removeBracesAction, + notApplicableReason: info.error + }] }]; } return emptyArray; } function getRefactorEditsToRemoveFunctionBraces(context, actionName2) { - const { file, startPosition } = context; + const { + file, + startPosition + } = context; const info = getConvertibleArrowFunctionAtPosition(file, startPosition); Debug.assert(info && !isRefactorErrorInfo(info), "Expected applicable refactor info"); - const { expression, returnStatement, func } = info; + const { + expression, + returnStatement, + func + } = info; let body; if (actionName2 === addBracesAction.name) { const returnStatement2 = factory.createReturnStatement(expression); - body = factory.createBlock( - [returnStatement2], - /*multiLine*/ - true - ); - copyLeadingComments( - expression, - returnStatement2, - file, - 3 /* MultiLineCommentTrivia */, - /*hasTrailingNewLine*/ - true - ); + body = factory.createBlock([returnStatement2], /*multiLine*/ + true); + copyLeadingComments(expression, returnStatement2, file, 3 /* MultiLineCommentTrivia */, /*hasTrailingNewLine*/ + true); } else if (actionName2 === removeBracesAction.name && returnStatement) { const actualExpression = expression || factory.createVoidZero(); body = needsParentheses(actualExpression) ? factory.createParenthesizedExpression(actualExpression) : actualExpression; - copyTrailingAsLeadingComments( - returnStatement, - body, - file, - 3 /* MultiLineCommentTrivia */, - /*hasTrailingNewLine*/ - false - ); - copyLeadingComments( - returnStatement, - body, - file, - 3 /* MultiLineCommentTrivia */, - /*hasTrailingNewLine*/ - false - ); - copyTrailingComments( - returnStatement, - body, - file, - 3 /* MultiLineCommentTrivia */, - /*hasTrailingNewLine*/ - false - ); + copyTrailingAsLeadingComments(returnStatement, body, file, 3 /* MultiLineCommentTrivia */, /*hasTrailingNewLine*/ + false); + copyLeadingComments(returnStatement, body, file, 3 /* MultiLineCommentTrivia */, /*hasTrailingNewLine*/ + false); + copyTrailingComments(returnStatement, body, file, 3 /* MultiLineCommentTrivia */, /*hasTrailingNewLine*/ + false); } else { Debug.fail("invalid action"); } - const edits = ts_textChanges_exports.ChangeTracker.with(context, (t) => { + const edits = ts_textChanges_exports.ChangeTracker.with(context, t => { t.replaceNode(file, func.body, body); }); - return { renameFilename: void 0, renameLocation: void 0, edits }; + return { + renameFilename: void 0, + renameLocation: void 0, + edits + }; } function getConvertibleArrowFunctionAtPosition(file, startPosition, considerFunctionBodies = true, kind) { const node = getTokenAtPosition(file, startPosition); @@ -139095,16 +124262,22 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return void 0; } if (refactorKindBeginsWith(addBracesAction.kind, kind) && isExpression(func.body)) { - return { func, addBraces: true, expression: func.body }; + return { + func, + addBraces: true, + expression: func.body + }; } else if (refactorKindBeginsWith(removeBracesAction.kind, kind) && isBlock(func.body) && func.body.statements.length === 1) { const firstStatement = first(func.body.statements); if (isReturnStatement(firstStatement)) { - const expression = firstStatement.expression && isObjectLiteralExpression(getLeftmostExpression( - firstStatement.expression, - /*stopAtCallExpressions*/ - false - )) ? factory.createParenthesizedExpression(firstStatement.expression) : firstStatement.expression; - return { func, addBraces: false, expression, returnStatement: firstStatement }; + const expression = firstStatement.expression && isObjectLiteralExpression(getLeftmostExpression(firstStatement.expression, /*stopAtCallExpressions*/ + false)) ? factory.createParenthesizedExpression(firstStatement.expression) : firstStatement.expression; + return { + func, + addBraces: false, + expression, + returnStatement: firstStatement + }; } } return void 0; @@ -139113,6 +124286,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} var init_addOrRemoveBracesToArrowFunction = __esm({ "src/services/refactors/addOrRemoveBracesToArrowFunction.ts"() { "use strict"; + init_ts4(); init_ts_refactor(); refactorName7 = "Add or remove braces in an arrow function"; @@ -139140,6 +124314,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} var init_ts_refactor_addOrRemoveBracesToArrowFunction = __esm({ "src/services/_namespaces/ts.refactor.addOrRemoveBracesToArrowFunction.ts"() { "use strict"; + init_convertOverloadListToSingleSignature(); init_addOrRemoveBracesToArrowFunction(); } @@ -139147,17 +124322,27 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} // src/services/refactors/convertArrowFunctionOrFunctionExpression.ts function getRefactorActionsToConvertFunctionExpressions(context) { - const { file, startPosition, program, kind } = context; + const { + file, + startPosition, + program, + kind + } = context; const info = getFunctionInfo(file, startPosition, program); - if (!info) - return emptyArray; - const { selectedVariableDeclaration, func } = info; + if (!info) return emptyArray; + const { + selectedVariableDeclaration, + func + } = info; const possibleActions = []; const errors = []; if (refactorKindBeginsWith(toNamedFunctionAction.kind, kind)) { const error2 = selectedVariableDeclaration || isArrowFunction(func) && isVariableDeclaration(func.parent) ? void 0 : getLocaleSpecificMessage(Diagnostics.Could_not_convert_to_named_function); if (error2) { - errors.push({ ...toNamedFunctionAction, notApplicableReason: error2 }); + errors.push({ + ...toNamedFunctionAction, + notApplicableReason: error2 + }); } else { possibleActions.push(toNamedFunctionAction); } @@ -139165,7 +124350,10 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (refactorKindBeginsWith(toAnonymousFunctionAction.kind, kind)) { const error2 = !selectedVariableDeclaration && isArrowFunction(func) ? void 0 : getLocaleSpecificMessage(Diagnostics.Could_not_convert_to_anonymous_function); if (error2) { - errors.push({ ...toAnonymousFunctionAction, notApplicableReason: error2 }); + errors.push({ + ...toAnonymousFunctionAction, + notApplicableReason: error2 + }); } else { possibleActions.push(toAnonymousFunctionAction); } @@ -139173,7 +124361,10 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (refactorKindBeginsWith(toArrowFunctionAction.kind, kind)) { const error2 = isFunctionExpression(func) ? void 0 : getLocaleSpecificMessage(Diagnostics.Could_not_convert_to_arrow_function); if (error2) { - errors.push({ ...toArrowFunctionAction, notApplicableReason: error2 }); + errors.push({ + ...toArrowFunctionAction, + notApplicableReason: error2 + }); } else { possibleActions.push(toArrowFunctionAction); } @@ -139185,11 +124376,16 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} }]; } function getRefactorEditsToConvertFunctionExpressions(context, actionName2) { - const { file, startPosition, program } = context; + const { + file, + startPosition, + program + } = context; const info = getFunctionInfo(file, startPosition, program); - if (!info) - return void 0; - const { func } = info; + if (!info) return void 0; + const { + func + } = info; const edits = []; switch (actionName2) { case toAnonymousFunctionAction.name: @@ -139197,19 +124393,21 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} 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: return Debug.fail("invalid action"); } - return { renameFilename: void 0, renameLocation: void 0, edits }; + return { + renameFilename: void 0, + renameLocation: void 0, + edits + }; } function containingThis(node) { let containsThis = false; @@ -139229,13 +124427,18 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} const typeChecker = program.getTypeChecker(); const func = tryGetFunctionFromVariableDeclaration(file, typeChecker, token.parent); if (func && !containingThis(func.body) && !typeChecker.containsArgumentsReference(func)) { - return { selectedVariableDeclaration: true, func }; + return { + selectedVariableDeclaration: true, + func + }; } const maybeFunc = getContainingFunction(token); if (maybeFunc && (isFunctionExpression(maybeFunc) || isArrowFunction(maybeFunc)) && !rangeContainsRange(maybeFunc.body, token) && !containingThis(maybeFunc.body) && !typeChecker.containsArgumentsReference(maybeFunc)) { - if (isFunctionExpression(maybeFunc) && isFunctionReferencedInFile(file, typeChecker, maybeFunc)) - return void 0; - return { selectedVariableDeclaration: false, func: maybeFunc }; + if (isFunctionExpression(maybeFunc) && isFunctionReferencedInFile(file, typeChecker, maybeFunc)) return void 0; + return { + selectedVariableDeclaration: false, + func: maybeFunc + }; } return void 0; } @@ -139259,68 +124462,65 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} const file = body.getSourceFile(); setTextRange(returnStatement, body); suppressLeadingAndTrailingTrivia(returnStatement); - copyTrailingAsLeadingComments( - body, - returnStatement, - file, - /*commentKind*/ - void 0, - /*hasTrailingNewLine*/ - true - ); - return factory.createBlock( - [returnStatement], - /*multiLine*/ - true - ); + copyTrailingAsLeadingComments(body, returnStatement, file, /*commentKind*/ + void 0, /*hasTrailingNewLine*/ + true); + return factory.createBlock([returnStatement], /*multiLine*/ + true); } else { return body; } } function getVariableInfo(func) { const variableDeclaration = func.parent; - if (!isVariableDeclaration(variableDeclaration) || !isVariableDeclarationInVariableStatement(variableDeclaration)) - return void 0; + if (!isVariableDeclaration(variableDeclaration) || !isVariableDeclarationInVariableStatement(variableDeclaration)) return void 0; const variableDeclarationList = variableDeclaration.parent; const statement = variableDeclarationList.parent; - if (!isVariableDeclarationList(variableDeclarationList) || !isVariableStatement(statement) || !isIdentifier(variableDeclaration.name)) - return void 0; - return { variableDeclaration, variableDeclarationList, statement, name: variableDeclaration.name }; + if (!isVariableDeclarationList(variableDeclarationList) || !isVariableStatement(statement) || !isIdentifier(variableDeclaration.name)) return void 0; + return { + variableDeclaration, + variableDeclarationList, + statement, + name: variableDeclaration.name + }; } function getEditInfoForConvertToAnonymousFunction(context, func) { - const { file } = context; + const { + file + } = context; const body = convertToBlock(func.body); - const newNode = factory.createFunctionExpression( - func.modifiers, - func.asteriskToken, - /*name*/ - void 0, - func.typeParameters, - func.parameters, - func.type, - body - ); - return ts_textChanges_exports.ChangeTracker.with(context, (t) => t.replaceNode(file, func, newNode)); + const newNode = factory.createFunctionExpression(func.modifiers, func.asteriskToken, /*name*/ + void 0, func.typeParameters, func.parameters, func.type, body); + return ts_textChanges_exports.ChangeTracker.with(context, t => t.replaceNode(file, func, newNode)); } function getEditInfoForConvertToNamedFunction(context, func, variableInfo) { - const { file } = context; + const { + file + } = context; const body = convertToBlock(func.body); - const { variableDeclaration, variableDeclarationList, statement, name } = variableInfo; + const { + variableDeclaration, + variableDeclarationList, + statement, + name + } = variableInfo; suppressLeadingTrivia(statement); const modifiersFlags = getCombinedModifierFlags(variableDeclaration) & 32 /* Export */ | getEffectiveModifierFlags(func); const modifiers = factory.createModifiersFromModifierFlags(modifiersFlags); const newNode = factory.createFunctionDeclaration(length(modifiers) ? modifiers : void 0, func.asteriskToken, name, func.typeParameters, func.parameters, func.type, body); if (variableDeclarationList.declarations.length === 1) { - return ts_textChanges_exports.ChangeTracker.with(context, (t) => t.replaceNode(file, statement, newNode)); + return ts_textChanges_exports.ChangeTracker.with(context, t => t.replaceNode(file, statement, newNode)); } else { - return ts_textChanges_exports.ChangeTracker.with(context, (t) => { + return ts_textChanges_exports.ChangeTracker.with(context, t => { t.delete(file, variableDeclaration); t.insertNodeAfter(file, statement, newNode); }); } } function getEditInfoForConvertToArrowFunction(context, func) { - const { file } = context; + const { + file + } = context; const statements = func.body.statements; const head = statements[0]; let body; @@ -139332,10 +124532,10 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} body = func.body; } const newNode = factory.createArrowFunction(func.modifiers, func.typeParameters, func.parameters, func.type, factory.createToken(39 /* EqualsGreaterThanToken */), body); - return ts_textChanges_exports.ChangeTracker.with(context, (t) => t.replaceNode(file, func, newNode)); + return ts_textChanges_exports.ChangeTracker.with(context, t => t.replaceNode(file, func, newNode)); } function canBeConvertedToExpression(body, head) { - return body.statements.length === 1 && (isReturnStatement(head) && !!head.expression); + return body.statements.length === 1 && isReturnStatement(head) && !!head.expression; } function isFunctionReferencedInFile(sourceFile, typeChecker, node) { return !!node.name && ts_FindAllReferences_exports.Core.isSymbolReferencedInFile(node.name, typeChecker, sourceFile); @@ -139344,6 +124544,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} var init_convertArrowFunctionOrFunctionExpression = __esm({ "src/services/refactors/convertArrowFunctionOrFunctionExpression.ts"() { "use strict"; + init_ts4(); init_ts_refactor(); refactorName8 = "Convert arrow function or function expression"; @@ -139364,11 +124565,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} kind: "refactor.rewrite.function.arrow" }; registerRefactor(refactorName8, { - kinds: [ - toAnonymousFunctionAction.kind, - toNamedFunctionAction.kind, - toArrowFunctionAction.kind - ], + kinds: [toAnonymousFunctionAction.kind, toNamedFunctionAction.kind, toArrowFunctionAction.kind], getEditsForAction: getRefactorEditsToConvertFunctionExpressions, getAvailableActions: getRefactorActionsToConvertFunctionExpressions }); @@ -139380,19 +124577,21 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} var init_ts_refactor_convertArrowFunctionOrFunctionExpression = __esm({ "src/services/_namespaces/ts.refactor.convertArrowFunctionOrFunctionExpression.ts"() { "use strict"; + init_convertArrowFunctionOrFunctionExpression(); } }); // src/services/refactors/convertParamsToDestructuredObject.ts function getRefactorActionsToConvertParametersToDestructuredObject(context) { - const { file, startPosition } = 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, @@ -139401,60 +124600,56 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } function getRefactorEditsToConvertParametersToDestructuredObject(context, actionName2) { Debug.assert(actionName2 === refactorName9, "Unexpected action name"); - const { file, startPosition, program, cancellationToken, host } = context; + 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)); - return { renameFilename: void 0, renameLocation: void 0, edits }; + const edits = ts_textChanges_exports.ChangeTracker.with(context, t => doChange5(file, program, host, t, functionDeclaration, groupedReferences)); + return { + renameFilename: void 0, + renameLocation: void 0, + edits + }; } - return { edits: [] }; + return { + edits: [] + }; } function doChange5(sourceFile, program, host, changes, functionDeclaration, groupedReferences) { const signature = groupedReferences.signature; - const newFunctionDeclarationParams = map(createNewParameters(functionDeclaration, program, host), (param) => getSynthesizedDeepClone(param)); + const newFunctionDeclarationParams = map(createNewParameters(functionDeclaration, program, host), param => getSynthesizedDeepClone(param)); if (signature) { - const newSignatureParams = map(createNewParameters(signature, program, host), (param) => getSynthesizedDeepClone(param)); + const newSignatureParams = map(createNewParameters(signature, program, host), param => getSynthesizedDeepClone(param)); replaceParameters(signature, newSignatureParams); } replaceParameters(functionDeclaration, newFunctionDeclarationParams); - const functionCalls = sortAndDeduplicate( - groupedReferences.functionCalls, - /*comparer*/ - (a, b) => compareValues(a.pos, b.pos) - ); + const functionCalls = sortAndDeduplicate(groupedReferences.functionCalls, /*comparer*/ + (a, b) => compareValues(a.pos, b.pos)); for (const call of functionCalls) { if (call.arguments && call.arguments.length) { - const newArgument = getSynthesizedDeepClone( - createNewArgument(functionDeclaration, call.arguments), - /*includeTrivia*/ - true - ); - changes.replaceNodeRange( - getSourceFileOfNode(call), - first(call.arguments), - last(call.arguments), - newArgument, - { leadingTriviaOption: ts_textChanges_exports.LeadingTriviaOption.IncludeAll, trailingTriviaOption: ts_textChanges_exports.TrailingTriviaOption.Include } - ); + const newArgument = getSynthesizedDeepClone(createNewArgument(functionDeclaration, call.arguments), /*includeTrivia*/ + true); + changes.replaceNodeRange(getSourceFileOfNode(call), first(call.arguments), last(call.arguments), newArgument, { + leadingTriviaOption: ts_textChanges_exports.LeadingTriviaOption.IncludeAll, + trailingTriviaOption: ts_textChanges_exports.TrailingTriviaOption.Include + }); } } function replaceParameters(declarationOrSignature, parameterDeclarations) { - changes.replaceNodeRangeWithNodes( - sourceFile, - first(declarationOrSignature.parameters), - last(declarationOrSignature.parameters), - parameterDeclarations, - { - joiner: ", ", - // indentation is set to 0 because otherwise the object parameter will be indented if there is a `this` parameter - indentation: 0, - leadingTriviaOption: ts_textChanges_exports.LeadingTriviaOption.IncludeAll, - trailingTriviaOption: ts_textChanges_exports.TrailingTriviaOption.Include - } - ); + changes.replaceNodeRangeWithNodes(sourceFile, first(declarationOrSignature.parameters), last(declarationOrSignature.parameters), parameterDeclarations, { + joiner: ", ", + // indentation is set to 0 because otherwise the object parameter will be indented if there is a `this` parameter + indentation: 0, + leadingTriviaOption: ts_textChanges_exports.LeadingTriviaOption.IncludeAll, + trailingTriviaOption: ts_textChanges_exports.TrailingTriviaOption.Include + }); } } function getGroupedReferences(functionDeclaration, program, cancellationToken) { @@ -139462,27 +124657,29 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} const classNames = isConstructorDeclaration(functionDeclaration) ? getClassNames(functionDeclaration) : []; const names = deduplicate([...functionNames, ...classNames], equateValues); const checker = program.getTypeChecker(); - const references = flatMap( - names, - /*mapfn*/ - (name) => ts_FindAllReferences_exports.getReferenceEntriesForNode(-1, name, program, program.getSourceFiles(), cancellationToken) - ); + const references = flatMap(names, /*mapfn*/ + name => ts_FindAllReferences_exports.getReferenceEntriesForNode(-1, name, program, program.getSourceFiles(), cancellationToken)); const groupedReferences = groupReferences(references); - if (!every( - groupedReferences.declarations, - /*callback*/ - (decl) => contains(names, decl) - )) { + if (!every(groupedReferences.declarations, /*callback*/ + decl => contains(names, decl))) { groupedReferences.valid = false; } return groupedReferences; function groupReferences(referenceEntries) { - const classReferences = { accessExpressions: [], typeUsages: [] }; - const groupedReferences2 = { functionCalls: [], declarations: [], classReferences, valid: true }; + const classReferences = { + accessExpressions: [], + typeUsages: [] + }; + const groupedReferences2 = { + functionCalls: [], + declarations: [], + classReferences, + valid: true + }; const functionSymbols = map(functionNames, getSymbolTargetAtLocation); const classSymbols = map(classNames, getSymbolTargetAtLocation); const isConstructor = isConstructorDeclaration(functionDeclaration); - const contextualSymbols = map(functionNames, (name) => getSymbolForContextualType(name, checker)); + const contextualSymbols = map(functionNames, name => getSymbolForContextualType(name, checker)); for (const entry of referenceEntries) { if (entry.kind === ts_FindAllReferences_exports.EntryKind.Span) { groupedReferences2.valid = false; @@ -139646,16 +124843,14 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} 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) { const containingJSDoc = findAncestor(node, isJSDocNode); if (containingJSDoc) { - const containingNonJSDoc = findAncestor(containingJSDoc, (n) => !isJSDocNode(n)); + const containingNonJSDoc = findAncestor(containingJSDoc, n => !isJSDocNode(n)); return !!containingNonJSDoc && isFunctionLikeDeclaration(containingNonJSDoc); } return false; @@ -139665,8 +124860,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } 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); @@ -139699,17 +124893,13 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return true; } function isValidParameterNodeArray(parameters, checker) { - return getRefactorableParametersLength(parameters) >= minimumParameterLength && every( - parameters, - /*callback*/ - (paramDecl) => isValidParameterDeclaration(paramDecl, checker) - ); + return getRefactorableParametersLength(parameters) >= minimumParameterLength && every(parameters, /*callback*/ + paramDecl => isValidParameterDeclaration(paramDecl, checker)); } function isValidParameterDeclaration(parameterDeclaration, checker) { if (isRestParameter(parameterDeclaration)) { const type = checker.getTypeAtLocation(parameterDeclaration); - if (!checker.isArrayType(type) && !checker.isTupleType(type)) - return false; + if (!checker.isArrayType(type) && !checker.isTupleType(type)) return false; } return !parameterDeclaration.modifiers && isIdentifier(parameterDeclaration.name); } @@ -139745,8 +124935,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} 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; }); @@ -139755,11 +124944,8 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} const restProperty = factory.createPropertyAssignment(getParameterName(last(parameters)), factory.createArrayLiteralExpression(restArguments)); properties.push(restProperty); } - const objectLiteral = factory.createObjectLiteralExpression( - properties, - /*multiLine*/ - false - ); + const objectLiteral = factory.createObjectLiteralExpression(properties, /*multiLine*/ + false); return objectLiteral; } function createNewParameters(functionDeclaration, program, host) { @@ -139772,29 +124958,16 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (every(refactorableParameters, isOptionalParameter)) { objectInitializer = factory.createObjectLiteralExpression(); } - const objectParameter = factory.createParameterDeclaration( - /*modifiers*/ - void 0, - /*dotDotDotToken*/ - void 0, - objectParameterName, - /*questionToken*/ - void 0, - objectParameterType, - objectInitializer - ); + const objectParameter = factory.createParameterDeclaration( /*modifiers*/ + void 0, /*dotDotDotToken*/ + void 0, objectParameterName, /*questionToken*/ + void 0, objectParameterType, objectInitializer); if (hasThisParameter(functionDeclaration.parameters)) { const thisParameter = functionDeclaration.parameters[0]; - const newThisParameter = factory.createParameterDeclaration( - /*modifiers*/ - void 0, - /*dotDotDotToken*/ - void 0, - thisParameter.name, - /*questionToken*/ - void 0, - thisParameter.type - ); + const newThisParameter = factory.createParameterDeclaration( /*modifiers*/ + void 0, /*dotDotDotToken*/ + void 0, thisParameter.name, /*questionToken*/ + void 0, thisParameter.type); suppressLeadingAndTrailingTrivia(newThisParameter.name); copyComments(thisParameter.name, newThisParameter.name); if (thisParameter.type) { @@ -139805,14 +124978,9 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } return factory.createNodeArray([objectParameter]); function createBindingElementFromParameterDeclaration(parameterDeclaration) { - const element = factory.createBindingElement( - /*dotDotDotToken*/ - void 0, - /*propertyName*/ - void 0, - getParameterName(parameterDeclaration), - isRestParameter(parameterDeclaration) && isOptionalParameter(parameterDeclaration) ? factory.createArrayLiteralExpression() : parameterDeclaration.initializer - ); + const element = factory.createBindingElement( /*dotDotDotToken*/ + void 0, /*propertyName*/ + void 0, getParameterName(parameterDeclaration), isRestParameter(parameterDeclaration) && isOptionalParameter(parameterDeclaration) ? factory.createArrayLiteralExpression() : parameterDeclaration.initializer); suppressLeadingAndTrailingTrivia(element); if (parameterDeclaration.initializer && element.initializer) { copyComments(parameterDeclaration.initializer, element.initializer); @@ -139829,13 +124997,8 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (!parameterType && (parameterDeclaration.initializer || isRestParameter(parameterDeclaration))) { parameterType = getTypeNode3(parameterDeclaration); } - const propertySignature = factory.createPropertySignature( - /*modifiers*/ - void 0, - getParameterName(parameterDeclaration), - isOptionalParameter(parameterDeclaration) ? factory.createToken(58 /* QuestionToken */) : parameterDeclaration.questionToken, - parameterType - ); + const propertySignature = factory.createPropertySignature( /*modifiers*/ + void 0, getParameterName(parameterDeclaration), isOptionalParameter(parameterDeclaration) ? factory.createToken(58 /* QuestionToken */) : parameterDeclaration.questionToken, parameterType); suppressLeadingAndTrailingTrivia(propertySignature); copyComments(parameterDeclaration.name, propertySignature.name); if (parameterDeclaration.type && propertySignature.type) { @@ -139862,39 +125025,27 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} switch (constructorDeclaration.parent.kind) { case 263 /* ClassDeclaration */: const classDeclaration = constructorDeclaration.parent; - if (classDeclaration.name) - return [classDeclaration.name]; - const defaultModifier = Debug.checkDefined( - findModifier(classDeclaration, 90 /* DefaultKeyword */), - "Nameless class declaration should be a default export" - ); + if (classDeclaration.name) return [classDeclaration.name]; + const defaultModifier = Debug.checkDefined(findModifier(classDeclaration, 90 /* DefaultKeyword */), "Nameless class declaration should be a default export"); return [defaultModifier]; case 231 /* ClassExpression */: const classExpression = constructorDeclaration.parent; const variableDeclaration = constructorDeclaration.parent.parent; const className = classExpression.name; - if (className) - return [className, variableDeclaration.name]; + if (className) return [className, variableDeclaration.name]; return [variableDeclaration.name]; } } function getFunctionNames(functionDeclaration) { switch (functionDeclaration.kind) { case 262 /* FunctionDeclaration */: - if (functionDeclaration.name) - return [functionDeclaration.name]; - const defaultModifier = Debug.checkDefined( - findModifier(functionDeclaration, 90 /* DefaultKeyword */), - "Nameless function declaration should be a default export" - ); + if (functionDeclaration.name) return [functionDeclaration.name]; + const defaultModifier = Debug.checkDefined(findModifier(functionDeclaration, 90 /* DefaultKeyword */), "Nameless function declaration should be a default export"); return [defaultModifier]; case 174 /* MethodDeclaration */: return [functionDeclaration.name]; case 176 /* Constructor */: - const ctrKeyword = Debug.checkDefined( - findChildOfKind(functionDeclaration, 137 /* ConstructorKeyword */, functionDeclaration.getSourceFile()), - "Constructor declaration should have constructor keyword" - ); + const ctrKeyword = Debug.checkDefined(findChildOfKind(functionDeclaration, 137 /* ConstructorKeyword */, functionDeclaration.getSourceFile()), "Constructor declaration should have constructor keyword"); if (functionDeclaration.parent.kind === 231 /* ClassExpression */) { const variableDeclaration = functionDeclaration.parent.parent; return [variableDeclaration.name, ctrKeyword]; @@ -139903,8 +125054,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} 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}`); @@ -139914,6 +125064,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} var init_convertParamsToDestructuredObject = __esm({ "src/services/refactors/convertParamsToDestructuredObject.ts"() { "use strict"; + init_ts4(); init_ts_refactor(); refactorName9 = "Convert parameters to destructured object"; @@ -139937,17 +125088,25 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} var init_ts_refactor_convertParamsToDestructuredObject = __esm({ "src/services/_namespaces/ts.refactor.convertParamsToDestructuredObject.ts"() { "use strict"; + init_convertParamsToDestructuredObject(); } }); // src/services/refactors/convertStringOrTemplateLiteral.ts function getRefactorActionsToConvertToTemplateString(context) { - const { file, startPosition } = context; + const { + file, + startPosition + } = context; const node = getNodeOrParentOfParentheses(file, startPosition); const maybeBinary = getParentBinaryExpression(node); const nodeIsStringLiteral = isStringLiteral(maybeBinary); - const refactorInfo = { name: refactorName10, description: refactorDescription6, actions: [] }; + const refactorInfo = { + name: refactorName10, + description: refactorDescription6, + actions: [] + }; if (nodeIsStringLiteral && context.triggerReason !== "invoked") { return emptyArray; } @@ -139955,7 +125114,10 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} refactorInfo.actions.push(convertStringAction); return [refactorInfo]; } else if (context.preferences.provideRefactorNotApplicableReason) { - refactorInfo.actions.push({ ...convertStringAction, notApplicableReason: getLocaleSpecificMessage(Diagnostics.Can_only_convert_string_concatenations_and_string_literals) }); + refactorInfo.actions.push({ + ...convertStringAction, + notApplicableReason: getLocaleSpecificMessage(Diagnostics.Can_only_convert_string_concatenations_and_string_literals) + }); return [refactorInfo]; } return emptyArray; @@ -139970,11 +125132,16 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return node; } function getRefactorEditsToConvertToTemplateString(context, actionName2) { - const { file, startPosition } = context; + const { + file, + startPosition + } = context; const node = getNodeOrParentOfParentheses(file, startPosition); switch (actionName2) { case refactorDescription6: - return { edits: getEditsForToTemplateLiteral(context, node) }; + return { + edits: getEditsForToTemplateLiteral(context, node) + }; default: return Debug.fail("invalid action"); } @@ -139986,20 +125153,24 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} const trailingCommentRanges = getTrailingCommentRanges(file.text, maybeBinary.end); if (trailingCommentRanges) { const lastComment = trailingCommentRanges[trailingCommentRanges.length - 1]; - const trailingRange = { pos: trailingCommentRanges[0].pos, end: lastComment.end }; - return ts_textChanges_exports.ChangeTracker.with(context, (t) => { + const trailingRange = { + pos: trailingCommentRanges[0].pos, + end: lastComment.end + }; + return ts_textChanges_exports.ChangeTracker.with(context, t => { t.deleteRange(file, trailingRange); t.replaceNode(file, maybeBinary, templateLiteral); }); } else { - return ts_textChanges_exports.ChangeTracker.with(context, (t) => t.replaceNode(file, maybeBinary, templateLiteral)); + return ts_textChanges_exports.ChangeTracker.with(context, t => t.replaceNode(file, maybeBinary, templateLiteral)); } } function isNotEqualsOperator(node) { return !(node.operatorToken.kind === 64 /* EqualsToken */ || node.operatorToken.kind === 65 /* PlusEqualsToken */); } + function getParentBinaryExpression(expr) { - const container = findAncestor(expr.parent, (n) => { + const container = findAncestor(expr.parent, n => { switch (n.kind) { case 211 /* PropertyAccessExpression */: case 212 /* ElementAccessExpression */: @@ -140014,25 +125185,54 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return container || expr; } function treeToArray(current) { - const loop = (current2) => { + const loop = current2 => { if (!isBinaryExpression(current2)) { - return { nodes: [current2], operators: [], validOperators: true, hasString: isStringLiteral(current2) || isNoSubstitutionTemplateLiteral(current2) }; + return { + nodes: [current2], + operators: [], + validOperators: true, + hasString: isStringLiteral(current2) || isNoSubstitutionTemplateLiteral(current2) + }; } - const { nodes: nodes2, operators: operators2, hasString: leftHasString, validOperators: leftOperatorValid } = loop(current2.left); + const { + nodes: nodes2, + operators: operators2, + hasString: leftHasString, + validOperators: leftOperatorValid + } = loop(current2.left); if (!(leftHasString || isStringLiteral(current2.right) || isTemplateExpression(current2.right))) { - return { nodes: [current2], operators: [], hasString: false, validOperators: true }; + return { + nodes: [current2], + operators: [], + hasString: false, + validOperators: true + }; } const currentOperatorValid = current2.operatorToken.kind === 40 /* PlusToken */; const validOperators2 = leftOperatorValid && currentOperatorValid; nodes2.push(current2.right); operators2.push(current2.operatorToken); - return { nodes: nodes2, operators: operators2, hasString: true, validOperators: validOperators2 }; + return { + nodes: nodes2, + operators: operators2, + hasString: true, + validOperators: validOperators2 + }; + }; + const { + nodes, + operators, + validOperators, + hasString + } = loop(current); + return { + nodes, + operators, + isValidConcatenation: validOperators && hasString }; - const { nodes, operators, validOperators, hasString } = loop(current); - return { nodes, operators, isValidConcatenation: validOperators && hasString }; } function escapeRawStringForTemplate(s) { - return s.replace(/\\.|[$`]/g, (m) => m[0] === "\\" ? m : "\\" + m); + return s.replace(/\\.|[$`]/g, m => m[0] === "\\" ? m : "\\" + m); } function getRawTextOfTemplate(node) { const rightShaving = isTemplateHead(node) || isTemplateMiddle(node) ? -2 : -1; @@ -140040,7 +125240,8 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } function concatConsecutiveString(index, nodes) { const indexes = []; - let text = "", rawText = ""; + let text = "", + rawText = ""; while (index < nodes.length) { const node = nodes[index]; if (isStringLiteralLike(node)) { @@ -140058,7 +125259,10 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } return [index, text, rawText, indexes]; } - function nodesToTemplate({ nodes, operators }, file) { + function nodesToTemplate({ + nodes, + operators + }, file) { const copyOperatorComments = copyTrailingOperatorComments(operators, file); const copyCommentFromStringLiterals = copyCommentFromMultiNode(nodes, file, copyOperatorComments); const [begin, headText, rawHeadText, headIndexes] = concatConsecutiveString(0, nodes); @@ -140082,10 +125286,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} const isLastSpan = index === currentNode.templateSpans.length - 1; const text = span.literal.text + (isLastSpan ? subsequentText : ""); const rawText = getRawTextOfTemplate(span.literal) + (isLastSpan ? rawSubsequentText : ""); - return factory.createTemplateSpan( - span.expression, - isLast && isLastSpan ? factory.createTemplateTail(text, rawText) : factory.createTemplateMiddle(text, rawText) - ); + return factory.createTemplateSpan(span.expression, isLast && isLastSpan ? factory.createTemplateTail(text, rawText) : factory.createTemplateMiddle(text, rawText)); }); templateSpans.push(...spans); } else { @@ -140098,22 +125299,10 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } function copyExpressionComments(node) { const file = node.getSourceFile(); - copyTrailingComments( - node, - node.expression, - file, - 3 /* MultiLineCommentTrivia */, - /*hasTrailingNewLine*/ - false - ); - copyTrailingAsLeadingComments( - node.expression, - node.expression, - file, - 3 /* MultiLineCommentTrivia */, - /*hasTrailingNewLine*/ - false - ); + copyTrailingComments(node, node.expression, file, 3 /* MultiLineCommentTrivia */, /*hasTrailingNewLine*/ + false); + copyTrailingAsLeadingComments(node.expression, node.expression, file, 3 /* MultiLineCommentTrivia */, /*hasTrailingNewLine*/ + false); } function getExpressionFromParenthesesOrExpression(node) { if (isParenthesizedExpression(node)) { @@ -140126,6 +125315,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} var init_convertStringOrTemplateLiteral = __esm({ "src/services/refactors/convertStringOrTemplateLiteral.ts"() { "use strict"; + init_ts4(); init_ts_refactor(); refactorName10 = "Convert to template string"; @@ -140142,27 +125332,15 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} }); copyTrailingOperatorComments = (operators, file) => (index, targetNode) => { if (index < operators.length) { - copyTrailingComments( - operators[index], - targetNode, - file, - 3 /* MultiLineCommentTrivia */, - /*hasTrailingNewLine*/ - false - ); + copyTrailingComments(operators[index], targetNode, file, 3 /* MultiLineCommentTrivia */, /*hasTrailingNewLine*/ + false); } }; copyCommentFromMultiNode = (nodes, file, copyOperatorComments) => (indexes, targetNode) => { while (indexes.length > 0) { const index = indexes.shift(); - copyTrailingComments( - nodes[index], - targetNode, - file, - 3 /* MultiLineCommentTrivia */, - /*hasTrailingNewLine*/ - false - ); + copyTrailingComments(nodes[index], targetNode, file, 3 /* MultiLineCommentTrivia */, /*hasTrailingNewLine*/ + false); copyOperatorComments(index, targetNode); } }; @@ -140174,6 +125352,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} var init_ts_refactor_convertStringOrTemplateLiteral = __esm({ "src/services/_namespaces/ts.refactor.convertStringOrTemplateLiteral.ts"() { "use strict"; + init_convertStringOrTemplateLiteral(); } }); @@ -140181,8 +125360,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} // src/services/refactors/convertToOptionalChainExpression.ts function getRefactorActionsToConvertToOptionalChain(context) { const info = getInfo3(context, context.triggerReason === "invoked"); - if (!info) - return emptyArray; + if (!info) return emptyArray; if (!isRefactorErrorInfo(info)) { return [{ name: refactorName11, @@ -140194,7 +125372,10 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return [{ name: refactorName11, description: convertToOptionalChainExpressionMessage, - actions: [{ ...toOptionalChainAction, notApplicableReason: info.error }] + actions: [{ + ...toOptionalChainAction, + notApplicableReason: info.error + }] }]; } return emptyArray; @@ -140202,8 +125383,12 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} function getRefactorEditsToConvertToOptionalChain(context, actionName2) { const info = getInfo3(context); Debug.assert(info && !isRefactorErrorInfo(info), "Expected applicable refactor info"); - const edits = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange6(context.file, context.program.getTypeChecker(), t, info, actionName2)); - return { edits, renameFilename: void 0, renameLocation: void 0 }; + const edits = ts_textChanges_exports.ChangeTracker.with(context, t => doChange6(context.file, context.program.getTypeChecker(), t, info, actionName2)); + return { + edits, + renameFilename: void 0, + renameLocation: void 0 + }; } function isValidExpression(node) { return isBinaryExpression(node) || isConditionalExpression(node); @@ -140215,18 +125400,21 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return isValidExpression(node) || isValidStatement(node); } function getInfo3(context, considerEmptySpans = true) { - const { file, program } = context; + 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); } @@ -140234,24 +125422,45 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} const condition = expression.condition; const finalExpression = getFinalExpressionInChain(expression.whenTrue); if (!finalExpression || checker.isNullableType(checker.getTypeAtLocation(finalExpression))) { - return { error: getLocaleSpecificMessage(Diagnostics.Could_not_find_convertible_access_expression) }; + return { + error: getLocaleSpecificMessage(Diagnostics.Could_not_find_convertible_access_expression) + }; } if ((isPropertyAccessExpression(condition) || isIdentifier(condition)) && getMatchingStart(condition, finalExpression.expression)) { - return { finalExpression, occurrences: [condition], expression }; + return { + finalExpression, + occurrences: [condition], + expression + }; } else if (isBinaryExpression(condition)) { const occurrences = getOccurrencesInExpression(finalExpression.expression, condition); - return occurrences ? { finalExpression, occurrences, expression } : { error: getLocaleSpecificMessage(Diagnostics.Could_not_find_matching_access_expressions) }; + return occurrences ? { + finalExpression, + occurrences, + expression + } : { + error: getLocaleSpecificMessage(Diagnostics.Could_not_find_matching_access_expressions) + }; } } function getBinaryInfo(expression) { if (expression.operatorToken.kind !== 56 /* AmpersandAmpersandToken */) { - return { error: getLocaleSpecificMessage(Diagnostics.Can_only_convert_logical_AND_access_chains) }; + 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) }; + return occurrences ? { + finalExpression, + occurrences, + expression + } : { + error: getLocaleSpecificMessage(Diagnostics.Could_not_find_matching_access_expressions) + }; } function getOccurrencesInExpression(matchTo, expression) { const occurrences = []; @@ -140278,13 +125487,11 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } 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; } @@ -140345,8 +125552,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} 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)) { @@ -140358,7 +125564,11 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return toConvert; } function doChange6(sourceFile, checker, changes, info, _actionName) { - const { finalExpression, occurrences, expression } = info; + const { + finalExpression, + occurrences, + expression + } = info; const firstOccurrence = occurrences[occurrences.length - 1]; const convertedChain = convertOccurrences(checker, finalExpression, occurrences); if (convertedChain && (isPropertyAccessExpression(convertedChain) || isElementAccessExpression(convertedChain) || isCallExpression(convertedChain))) { @@ -140373,6 +125583,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} var init_convertToOptionalChainExpression = __esm({ "src/services/refactors/convertToOptionalChainExpression.ts"() { "use strict"; + init_ts4(); init_ts_refactor(); refactorName11 = "Convert to optional chain expression"; @@ -140395,6 +125606,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} var init_ts_refactor_convertToOptionalChainExpression = __esm({ "src/services/_namespaces/ts.refactor.convertToOptionalChainExpression.ts"() { "use strict"; + init_convertToOptionalChainExpression(); } }); @@ -140413,14 +125625,20 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} errors.push({ name: refactorName12, description: extractFunctionAction.description, - actions: [{ ...extractFunctionAction, notApplicableReason: getStringError(rangeToExtract.errors) }] + actions: [{ + ...extractFunctionAction, + notApplicableReason: getStringError(rangeToExtract.errors) + }] }); } if (refactorKindBeginsWith(extractConstantAction.kind, requestedRefactor)) { errors.push({ name: refactorName12, description: extractConstantAction.description, - actions: [{ ...extractConstantAction, notApplicableReason: getStringError(rangeToExtract.errors) }] + actions: [{ + ...extractConstantAction, + notApplicableReason: getStringError(rangeToExtract.errors) + }] }); } return errors; @@ -140430,13 +125648,16 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return emptyArray; } const functionActions = []; - const usedFunctionNames = /* @__PURE__ */ new Map(); + const usedFunctionNames = /* @__PURE__ */new Map(); let innermostErrorFunctionAction; const constantActions = []; - const usedConstantNames = /* @__PURE__ */ new Map(); + const usedConstantNames = /* @__PURE__ */new Map(); let innermostErrorConstantAction; let i = 0; - for (const { functionExtraction, constantExtraction } of extractions) { + for (const { + functionExtraction, + constantExtraction + } of extractions) { if (refactorKindBeginsWith(extractFunctionAction.kind, requestedRefactor)) { const description3 = functionExtraction.description; if (functionExtraction.errors.length === 0) { @@ -140533,9 +125754,13 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} Debug.fail("Unrecognized action name"); } function getRangeToExtract2(sourceFile, span, invoked = true) { - const { length: length2 } = span; + const { + length: length2 + } = span; if (length2 === 0 && !invoked) { - return { errors: [createFileDiagnostic(sourceFile, span.start, length2, Messages.cannotExtractEmpty)] }; + return { + errors: [createFileDiagnostic(sourceFile, span.start, length2, Messages.cannotExtractEmpty)] + }; } const cursorRequest = length2 === 0 && invoked; const startToken = findFirstNonJsxWhitespaceToken(sourceFile, span.start); @@ -140546,24 +125771,34 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} let rangeFacts = 0 /* None */; let thisNode; if (!start || !end) { - return { errors: [createFileDiagnostic(sourceFile, span.start, length2, Messages.cannotExtractRange)] }; + return { + errors: [createFileDiagnostic(sourceFile, span.start, length2, Messages.cannotExtractRange)] + }; } if (start.flags & 16777216 /* JSDoc */) { - return { errors: [createFileDiagnostic(sourceFile, span.start, length2, Messages.cannotExtractJSDoc)] }; + return { + errors: [createFileDiagnostic(sourceFile, span.start, length2, Messages.cannotExtractJSDoc)] + }; } if (start.parent !== end.parent) { - return { errors: [createFileDiagnostic(sourceFile, span.start, length2, Messages.cannotExtractRange)] }; + return { + errors: [createFileDiagnostic(sourceFile, span.start, length2, Messages.cannotExtractRange)] + }; } if (start !== end) { if (!isBlockLike(start.parent)) { - return { errors: [createFileDiagnostic(sourceFile, span.start, length2, Messages.cannotExtractRange)] }; + return { + errors: [createFileDiagnostic(sourceFile, span.start, length2, Messages.cannotExtractRange)] + }; } const statements = []; for (const statement of start.parent.statements) { if (statement === start || statements.length) { const errors2 = checkNode(statement); if (errors2) { - return { errors: errors2 }; + return { + errors: errors2 + }; } statements.push(statement); } @@ -140572,19 +125807,37 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } } if (!statements.length) { - return { errors: [createFileDiagnostic(sourceFile, span.start, length2, Messages.cannotExtractRange)] }; + return { + errors: [createFileDiagnostic(sourceFile, span.start, length2, Messages.cannotExtractRange)] + }; } - return { targetRange: { range: statements, facts: rangeFacts, thisNode } }; + return { + targetRange: { + range: statements, + facts: rangeFacts, + thisNode + } + }; } if (isReturnStatement(start) && !start.expression) { - return { errors: [createFileDiagnostic(sourceFile, span.start, length2, Messages.cannotExtractRange)] }; + return { + errors: [createFileDiagnostic(sourceFile, span.start, length2, Messages.cannotExtractRange)] + }; } const node = refineNode(start); const errors = checkRootNode(node) || checkNode(node); if (errors) { - return { errors }; + return { + errors + }; } - return { targetRange: { range: getStatementOrExpressionRange(node), facts: rangeFacts, thisNode } }; + return { + targetRange: { + range: getStatementOrExpressionRange(node), + facts: rangeFacts, + thisNode + } + }; function refineNode(node2) { if (isReturnStatement(node2)) { if (node2.expression) { @@ -140623,24 +125876,27 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (isStatic(current)) { rangeFacts |= 32 /* InStaticRegion */; } + break; } else if (current.kind === 169 /* Parameter */) { const ctorOrMethod = getContainingFunction(current); if (ctorOrMethod.kind === 176 /* Constructor */) { rangeFacts |= 32 /* InStaticRegion */; } + break; } else if (current.kind === 174 /* MethodDeclaration */) { if (isStatic(current)) { rangeFacts |= 32 /* InStaticRegion */; } } + current = current.parent; } } function checkNode(nodeToCheck) { let PermittedJumps; - ((PermittedJumps2) => { + (PermittedJumps2 => { PermittedJumps2[PermittedJumps2["None"] = 0] = "None"; PermittedJumps2[PermittedJumps2["Break"] = 1] = "Break"; PermittedJumps2[PermittedJumps2["Continue"] = 2] = "Continue"; @@ -140663,17 +125919,14 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} let seenLabels; visit(nodeToCheck); if (rangeFacts & 8 /* UsesThis */) { - const container = getThisContainer( - nodeToCheck, - /*includeArrowFunctions*/ - false, - /*includeClassComputedPropertyName*/ - false - ); + const container = getThisContainer(nodeToCheck, /*includeArrowFunctions*/ + false, /*includeClassComputedPropertyName*/ + false); if (container.kind === 262 /* FunctionDeclaration */ || container.kind === 174 /* MethodDeclaration */ && container.parent.kind === 210 /* ObjectLiteralExpression */ || container.kind === 218 /* FunctionExpression */) { rangeFacts |= 16 /* UsesThisInFunction */; } } + return errors2; function visit(node2) { if (errors2) { @@ -140741,19 +125994,18 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (node2.parent && node2.parent.kind === 258 /* TryStatement */ && node2.parent.finallyBlock === node2) { permittedJumps = 4 /* Return */; } + break; case 297 /* DefaultClause */: case 296 /* CaseClause */: permittedJumps |= 1 /* Break */; break; default: - if (isIterationStatement( - node2, - /*lookInLabeledStatements*/ - false - )) { + if (isIterationStatement(node2, /*lookInLabeledStatements*/ + false)) { permittedJumps |= 1 /* Break */ | 2 /* Continue */; } + break; } switch (node2.kind) { @@ -140762,27 +126014,29 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} rangeFacts |= 8 /* UsesThis */; thisNode = node2; break; - case 256 /* LabeledStatement */: { - const label = node2.label; - (seenLabels || (seenLabels = [])).push(label.escapedText); - forEachChild(node2, visit); - seenLabels.pop(); - break; - } - case 252 /* BreakStatement */: - case 251 /* ContinueStatement */: { - const label = node2.label; - if (label) { - if (!contains(seenLabels, label.escapedText)) { - (errors2 || (errors2 = [])).push(createDiagnosticForNode(node2, Messages.cannotExtractRangeContainingLabeledBreakOrContinueStatementWithTargetOutsideOfTheRange)); - } - } else { - if (!(permittedJumps & (node2.kind === 252 /* BreakStatement */ ? 1 /* Break */ : 2 /* Continue */))) { - (errors2 || (errors2 = [])).push(createDiagnosticForNode(node2, Messages.cannotExtractRangeContainingConditionalBreakOrContinueStatements)); - } + case 256 /* LabeledStatement */: + { + const label = node2.label; + (seenLabels || (seenLabels = [])).push(label.escapedText); + forEachChild(node2, visit); + seenLabels.pop(); + break; + } + case 252 /* BreakStatement */: + case 251 /* ContinueStatement */: + { + const label = node2.label; + if (label) { + if (!contains(seenLabels, label.escapedText)) { + (errors2 || (errors2 = [])).push(createDiagnosticForNode(node2, Messages.cannotExtractRangeContainingLabeledBreakOrContinueStatementWithTargetOutsideOfTheRange)); + } + } else { + if (!(permittedJumps & (node2.kind === 252 /* BreakStatement */ ? 1 /* Break */ : 2 /* Continue */))) { + (errors2 || (errors2 = [])).push(createDiagnosticForNode(node2, Messages.cannotExtractRangeContainingConditionalBreakOrContinueStatements)); + } + } + break; } - break; - } case 223 /* AwaitExpression */: rangeFacts |= 4 /* IsAsyncFunction */; break; @@ -140810,7 +126064,10 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (sourceFile.text.charCodeAt(end) === 59 /* semicolon */) { end++; } - return { start, length: end - start }; + return { + start, + length: end - start + }; } function getStatementOrExpressionRange(node) { if (isStatement(node)) { @@ -140840,7 +126097,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} while (true) { current = current.parent; if (current.kind === 169 /* Parameter */) { - current = findAncestor(current, (parent2) => isFunctionLikeDeclaration(parent2)).parent; + current = findAncestor(current, parent2 => isFunctionLikeDeclaration(parent2)).parent; } if (isScope(current)) { scopes.push(current); @@ -140851,13 +126108,29 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } } function getFunctionExtractionAtIndex(targetRange, context, requestedChangesIndex) { - const { scopes, readsAndWrites: { target, usagesPerScope, functionErrorsPerScope, exposedVariableDeclarations } } = getPossibleExtractionsWorker(targetRange, context); + const { + scopes, + readsAndWrites: { + target, + usagesPerScope, + functionErrorsPerScope, + exposedVariableDeclarations + } + } = getPossibleExtractionsWorker(targetRange, context); Debug.assert(!functionErrorsPerScope[requestedChangesIndex].length, "The extraction went missing? How?"); context.cancellationToken.throwIfCancellationRequested(); return extractFunctionInScope(target, scopes[requestedChangesIndex], usagesPerScope[requestedChangesIndex], exposedVariableDeclarations, targetRange, context); } function getConstantExtractionAtIndex(targetRange, context, requestedChangesIndex) { - const { scopes, readsAndWrites: { target, usagesPerScope, constantErrorsPerScope, exposedVariableDeclarations } } = getPossibleExtractionsWorker(targetRange, context); + const { + scopes, + readsAndWrites: { + target, + usagesPerScope, + constantErrorsPerScope, + exposedVariableDeclarations + } + } = getPossibleExtractionsWorker(targetRange, context); Debug.assert(!constantErrorsPerScope[requestedChangesIndex].length, "The extraction went missing? How?"); Debug.assert(exposedVariableDeclarations.length === 0, "Extract constant accepted a range containing a variable declaration?"); context.cancellationToken.throwIfCancellationRequested(); @@ -140865,7 +126138,13 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return extractConstantInScope(expression, scopes[requestedChangesIndex], usagesPerScope[requestedChangesIndex], targetRange.facts, context); } function getPossibleExtractions(targetRange, context) { - const { scopes, readsAndWrites: { functionErrorsPerScope, constantErrorsPerScope } } = getPossibleExtractionsWorker(targetRange, context); + const { + scopes, + readsAndWrites: { + functionErrorsPerScope, + constantErrorsPerScope + } + } = getPossibleExtractionsWorker(targetRange, context); const extractions = scopes.map((scope, i) => { const functionDescriptionPart = getDescriptionForFunctionInScope(scope); const constantDescriptionPart = getDescriptionForConstantInScope(scope); @@ -140899,18 +126178,16 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return extractions; } function getPossibleExtractionsWorker(targetRange, context) { - const { file: sourceFile } = context; + const { + file: sourceFile + } = context; const scopes = collectEnclosingScopes(targetRange); const enclosingTextRange = getEnclosingTextRange(targetRange, sourceFile); - const readsAndWrites = collectReadsAndWrites( - targetRange, + const readsAndWrites = collectReadsAndWrites(targetRange, scopes, enclosingTextRange, sourceFile, context.program.getTypeChecker(), context.cancellationToken); + return { scopes, - enclosingTextRange, - sourceFile, - context.program.getTypeChecker(), - context.cancellationToken - ); - return { scopes, readsAndWrites }; + readsAndWrites + }; } function getDescriptionForFunctionInScope(scope) { return isFunctionLikeDeclaration(scope) ? "inner function" : isClassLike(scope) ? "method" : "function"; @@ -140943,7 +126220,12 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} function getDescriptionForModuleLikeDeclaration(scope) { return scope.kind === 268 /* ModuleBlock */ ? `namespace '${scope.parent.name.getText()}'` : scope.externalModuleIndicator ? 0 /* Module */ : 1 /* Global */; } - function extractFunctionInScope(node, scope, { usages: usagesInScope, typeParameterUsages, substitutions }, exposedVariableDeclarations, range, context) { + + function extractFunctionInScope(node, scope, { + usages: usagesInScope, + typeParameterUsages, + substitutions + }, exposedVariableDeclarations, range, context) { const checker = context.program.getTypeChecker(); const scriptTarget = getEmitScriptTarget(context.program.getCompilerOptions()); const importAdder = ts_codefix_exports.createImportAdder(context.file, context.program, context.preferences, context.host); @@ -140962,36 +126244,37 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} type = checker.getBaseTypeOfLiteralType(type); typeNode = ts_codefix_exports.typeToAutoImportableTypeNode(checker, importAdder, type, scope, scriptTarget, 1 /* NoTruncation */); } - const paramDecl = factory.createParameterDeclaration( - /*modifiers*/ - void 0, - /*dotDotDotToken*/ - void 0, - /*name*/ - name, - /*questionToken*/ - void 0, - typeNode - ); + + const paramDecl = factory.createParameterDeclaration( /*modifiers*/ + void 0, /*dotDotDotToken*/ + void 0, /*name*/ + name, /*questionToken*/ + void 0, typeNode); parameters.push(paramDecl); if (usage.usage === 2 /* Write */) { (writes || (writes = [])).push(usage); } callArguments.push(factory.createIdentifier(name)); }); - const typeParametersAndDeclarations = arrayFrom(typeParameterUsages.values(), (type) => ({ type, declaration: getFirstDeclarationBeforePosition(type, context.startPosition) })); + const typeParametersAndDeclarations = arrayFrom(typeParameterUsages.values(), type => ({ + type, + declaration: getFirstDeclarationBeforePosition(type, context.startPosition) + })); const sortedTypeParametersAndDeclarations = typeParametersAndDeclarations.sort(compareTypesByDeclarationOrder); - const typeParameters = sortedTypeParametersAndDeclarations.length === 0 ? void 0 : mapDefined(sortedTypeParametersAndDeclarations, ({ declaration }) => declaration); - const callTypeArguments = typeParameters !== void 0 ? typeParameters.map((decl) => factory.createTypeReferenceNode( - decl.name, - /*typeArguments*/ - void 0 - )) : void 0; + const typeParameters = sortedTypeParametersAndDeclarations.length === 0 ? void 0 : mapDefined(sortedTypeParametersAndDeclarations, ({ + declaration + }) => declaration); + const callTypeArguments = typeParameters !== void 0 ? typeParameters.map(decl => factory.createTypeReferenceNode(decl.name, /*typeArguments*/ + void 0)) : void 0; if (isExpression(node) && !isJS) { const contextualType = checker.getContextualType(node); returnType = checker.typeToTypeNode(contextualType, scope, 1 /* NoTruncation */); } - const { body, returnValueProperty } = transformFunctionBody(node, exposedVariableDeclarations, writes, substitutions, !!(range.facts & 1 /* HasReturn */)); + + const { + body, + returnValueProperty + } = transformFunctionBody(node, exposedVariableDeclarations, writes, substitutions, !!(range.facts & 1 /* HasReturn */)); suppressLeadingAndTrailingTrivia(body); let newFunction; const callThis = !!(range.facts & 16 /* UsesThisInFunction */); @@ -141000,63 +126283,30 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (range.facts & 32 /* InStaticRegion */) { modifiers.push(factory.createModifier(126 /* StaticKeyword */)); } + if (range.facts & 4 /* IsAsyncFunction */) { modifiers.push(factory.createModifier(134 /* AsyncKeyword */)); } - newFunction = factory.createMethodDeclaration( - modifiers.length ? modifiers : void 0, - range.facts & 2 /* IsGenerator */ ? factory.createToken(42 /* AsteriskToken */) : void 0, - functionName, - /*questionToken*/ - void 0, - typeParameters, - parameters, - returnType, - body - ); + + newFunction = factory.createMethodDeclaration(modifiers.length ? modifiers : void 0, range.facts & 2 /* IsGenerator */ ? factory.createToken(42 /* AsteriskToken */) : void 0, functionName, /*questionToken*/ + void 0, typeParameters, parameters, returnType, body); } else { if (callThis) { - parameters.unshift( - factory.createParameterDeclaration( - /*modifiers*/ - void 0, - /*dotDotDotToken*/ - void 0, - /*name*/ - "this", - /*questionToken*/ - void 0, - checker.typeToTypeNode( - checker.getTypeAtLocation(range.thisNode), - scope, - 1 /* NoTruncation */ - ), - /*initializer*/ - void 0 - ) - ); + parameters.unshift(factory.createParameterDeclaration( /*modifiers*/ + void 0, /*dotDotDotToken*/ + void 0, /*name*/ + "this", /*questionToken*/ + void 0, checker.typeToTypeNode(checker.getTypeAtLocation(range.thisNode), scope, 1 /* NoTruncation */), /*initializer*/ + void 0)); } - newFunction = factory.createFunctionDeclaration( - range.facts & 4 /* IsAsyncFunction */ ? [factory.createToken(134 /* AsyncKeyword */)] : void 0, - range.facts & 2 /* IsGenerator */ ? factory.createToken(42 /* AsteriskToken */) : void 0, - functionName, - typeParameters, - parameters, - returnType, - body - ); + newFunction = factory.createFunctionDeclaration(range.facts & 4 /* IsAsyncFunction */ ? [factory.createToken(134 /* AsyncKeyword */)] : void 0, range.facts & 2 /* IsGenerator */ ? factory.createToken(42 /* AsteriskToken */) : void 0, functionName, typeParameters, parameters, returnType, body); } const changeTracker = ts_textChanges_exports.ChangeTracker.fromContext(context); const minInsertionPos = (isReadonlyArray(range.range) ? last(range.range) : range.range).end; const nodeToInsertBefore = getNodeToInsertFunctionBefore(minInsertionPos, scope); if (nodeToInsertBefore) { - changeTracker.insertNodeBefore( - context.file, - nodeToInsertBefore, - newFunction, - /*blankLineBetween*/ - true - ); + changeTracker.insertNodeBefore(context.file, nodeToInsertBefore, newFunction, /*blankLineBetween*/ + true); } else { changeTracker.insertNodeAtEndOfScope(context.file, scope, newFunction); } @@ -141066,15 +126316,9 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (callThis) { callArguments.unshift(factory.createIdentifier("this")); } - let call = factory.createCallExpression( - callThis ? factory.createPropertyAccessExpression( - called, - "call" - ) : called, - callTypeArguments, - // Note that no attempt is made to take advantage of type argument inference - callArguments - ); + let call = factory.createCallExpression(callThis ? factory.createPropertyAccessExpression(called, "call") : called, callTypeArguments, + // Note that no attempt is made to take advantage of type argument inference + callArguments); if (range.facts & 2 /* IsGenerator */) { call = factory.createYieldExpression(factory.createToken(42 /* AsteriskToken */), call); } @@ -141082,62 +126326,36 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} call = factory.createAwaitExpression(call); } if (isInJSXContent(node)) { - call = factory.createJsxExpression( - /*dotDotDotToken*/ - void 0, - call - ); + call = factory.createJsxExpression( /*dotDotDotToken*/ + void 0, call); } if (exposedVariableDeclarations.length && !writes) { Debug.assert(!returnValueProperty, "Expected no returnValueProperty"); Debug.assert(!(range.facts & 1 /* HasReturn */), "Expected RangeFacts.HasReturn flag to be unset"); if (exposedVariableDeclarations.length === 1) { const variableDeclaration = exposedVariableDeclarations[0]; - newNodes.push(factory.createVariableStatement( - /*modifiers*/ - void 0, - factory.createVariableDeclarationList( - [factory.createVariableDeclaration( - getSynthesizedDeepClone(variableDeclaration.name), - /*exclamationToken*/ - void 0, - /*type*/ - getSynthesizedDeepClone(variableDeclaration.type), - /*initializer*/ - call - )], - variableDeclaration.parent.flags - ) - )); + newNodes.push(factory.createVariableStatement( /*modifiers*/ + void 0, factory.createVariableDeclarationList([factory.createVariableDeclaration(getSynthesizedDeepClone(variableDeclaration.name), /*exclamationToken*/ + void 0, /*type*/ + getSynthesizedDeepClone(variableDeclaration.type), /*initializer*/ + call)], variableDeclaration.parent.flags))); } else { const bindingElements = []; const typeElements = []; let commonNodeFlags = exposedVariableDeclarations[0].parent.flags; let sawExplicitType = false; for (const variableDeclaration of exposedVariableDeclarations) { - bindingElements.push(factory.createBindingElement( - /*dotDotDotToken*/ - void 0, - /*propertyName*/ - void 0, - /*name*/ - getSynthesizedDeepClone(variableDeclaration.name) - )); - const variableType = checker.typeToTypeNode( - checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(variableDeclaration)), - scope, - 1 /* NoTruncation */ - ); - typeElements.push(factory.createPropertySignature( - /*modifiers*/ - void 0, - /*name*/ - variableDeclaration.symbol.name, - /*questionToken*/ - void 0, - /*type*/ - variableType - )); + bindingElements.push(factory.createBindingElement( /*dotDotDotToken*/ + void 0, /*propertyName*/ + void 0, /*name*/ + getSynthesizedDeepClone(variableDeclaration.name))); + const variableType = checker.typeToTypeNode(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(variableDeclaration)), scope, 1 /* NoTruncation */); + + typeElements.push(factory.createPropertySignature( /*modifiers*/ + void 0, /*name*/ + variableDeclaration.symbol.name, /*questionToken*/ + void 0, /*type*/ + variableType)); sawExplicitType = sawExplicitType || variableDeclaration.type !== void 0; commonNodeFlags = commonNodeFlags & variableDeclaration.parent.flags; } @@ -141145,22 +126363,12 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (typeLiteral) { setEmitFlags(typeLiteral, 1 /* SingleLine */); } - newNodes.push(factory.createVariableStatement( - /*modifiers*/ - void 0, - factory.createVariableDeclarationList( - [factory.createVariableDeclaration( - factory.createObjectBindingPattern(bindingElements), - /*exclamationToken*/ - void 0, - /*type*/ - typeLiteral, - /*initializer*/ - call - )], - commonNodeFlags - ) - )); + + newNodes.push(factory.createVariableStatement( /*modifiers*/ + void 0, factory.createVariableDeclarationList([factory.createVariableDeclaration(factory.createObjectBindingPattern(bindingElements), /*exclamationToken*/ + void 0, /*type*/ + typeLiteral, /*initializer*/ + call)], commonNodeFlags))); } } else if (exposedVariableDeclarations.length || writes) { if (exposedVariableDeclarations.length) { @@ -141169,36 +126377,18 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (flags & 2 /* Const */) { flags = flags & ~2 /* Const */ | 1 /* Let */; } - newNodes.push(factory.createVariableStatement( - /*modifiers*/ - void 0, - factory.createVariableDeclarationList( - [factory.createVariableDeclaration( - variableDeclaration.symbol.name, - /*exclamationToken*/ - void 0, - getTypeDeepCloneUnionUndefined(variableDeclaration.type) - )], - flags - ) - )); + + newNodes.push(factory.createVariableStatement( /*modifiers*/ + void 0, factory.createVariableDeclarationList([factory.createVariableDeclaration(variableDeclaration.symbol.name, /*exclamationToken*/ + void 0, getTypeDeepCloneUnionUndefined(variableDeclaration.type))], flags))); } } if (returnValueProperty) { - newNodes.push(factory.createVariableStatement( - /*modifiers*/ - void 0, - factory.createVariableDeclarationList( - [factory.createVariableDeclaration( - returnValueProperty, - /*exclamationToken*/ - void 0, - getTypeDeepCloneUnionUndefined(returnType) - )], - 1 /* Let */ - ) - )); + newNodes.push(factory.createVariableStatement( /*modifiers*/ + void 0, factory.createVariableDeclarationList([factory.createVariableDeclaration(returnValueProperty, /*exclamationToken*/ + void 0, getTypeDeepCloneUnionUndefined(returnType))], 1 /* Let */))); } + const assignments = getPropertyAssignmentsForWritesAndVariableDeclarations(exposedVariableDeclarations, writes); if (returnValueProperty) { assignments.unshift(factory.createShorthandPropertyAssignment(returnValueProperty)); @@ -141232,14 +126422,13 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} const edits = changeTracker.getChanges(); const renameRange = isReadonlyArray(range.range) ? first(range.range) : range.range; const renameFilename = renameRange.getSourceFile().fileName; - const renameLocation = getRenameLocation( - edits, + const renameLocation = getRenameLocation(edits, renameFilename, functionNameText, /*preferLastLocation*/ + false); + return { renameFilename, - functionNameText, - /*preferLastLocation*/ - false - ); - return { renameFilename, renameLocation, edits }; + renameLocation, + edits + }; function getTypeDeepCloneUnionUndefined(typeNode) { if (typeNode === void 0) { return void 0; @@ -141249,23 +126438,24 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} while (isParenthesizedTypeNode(withoutParens)) { withoutParens = withoutParens.type; } - return isUnionTypeNode(withoutParens) && find(withoutParens.types, (t) => t.kind === 157 /* UndefinedKeyword */) ? clone2 : factory.createUnionTypeNode([clone2, factory.createKeywordTypeNode(157 /* UndefinedKeyword */)]); + return isUnionTypeNode(withoutParens) && find(withoutParens.types, t => t.kind === 157 /* UndefinedKeyword */) ? clone2 : factory.createUnionTypeNode([clone2, factory.createKeywordTypeNode(157 /* UndefinedKeyword */)]); } } - function extractConstantInScope(node, scope, { substitutions }, rangeFacts, context) { + + 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 = isPropertyAccessExpression(node) && !isClassLike(scope) && !checker.resolveName(node.name.text, node, 111551 /* Value */, /*excludeGlobals*/ + false) && !isPrivateIdentifier(node.name) && !identifierToKeywordKind(node.name) ? node.name.text : getUniqueName(isClassLike(scope) ? "newProperty" : "newLocal", file); const isJS = isInJSFile(scope); let variableType = isJS || !checker.isContextSensitive(node) ? void 0 : checker.typeToTypeNode(checker.getContextualType(node), scope, 1 /* NoTruncation */); let initializer = transformConstantInitializer(skipParentheses(node), substitutions); - ({ variableType, initializer } = transformFunctionInitializerAndType(variableType, initializer)); + ({ + variableType, + initializer + } = transformFunctionInitializerAndType(variableType, initializer)); suppressLeadingAndTrailingTrivia(initializer); const changeTracker = ts_textChanges_exports.ChangeTracker.fromContext(context); if (isClassLike(scope)) { @@ -141275,89 +126465,52 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (rangeFacts & 32 /* InStaticRegion */) { modifiers.push(factory.createModifier(126 /* StaticKeyword */)); } + modifiers.push(factory.createModifier(148 /* ReadonlyKeyword */)); - const newVariable = factory.createPropertyDeclaration( - modifiers, - localNameText, - /*questionOrExclamationToken*/ - void 0, - variableType, - initializer - ); - let localReference = factory.createPropertyAccessExpression( - rangeFacts & 32 /* InStaticRegion */ ? factory.createIdentifier(scope.name.getText()) : factory.createThis(), - factory.createIdentifier(localNameText) - ); + const newVariable = factory.createPropertyDeclaration(modifiers, localNameText, /*questionOrExclamationToken*/ + void 0, variableType, initializer); + let localReference = factory.createPropertyAccessExpression(rangeFacts & 32 /* InStaticRegion */ ? factory.createIdentifier(scope.name.getText()) : factory.createThis(), factory.createIdentifier(localNameText)); if (isInJSXContent(node)) { - localReference = factory.createJsxExpression( - /*dotDotDotToken*/ - void 0, - localReference - ); + localReference = factory.createJsxExpression( /*dotDotDotToken*/ + void 0, localReference); } const maxInsertionPos = node.pos; const nodeToInsertBefore = getNodeToInsertPropertyBefore(maxInsertionPos, scope); - changeTracker.insertNodeBefore( - context.file, - nodeToInsertBefore, - newVariable, - /*blankLineBetween*/ - true - ); + changeTracker.insertNodeBefore(context.file, nodeToInsertBefore, newVariable, /*blankLineBetween*/ + true); changeTracker.replaceNode(context.file, node, localReference); } else { - const newVariableDeclaration = factory.createVariableDeclaration( - localNameText, - /*exclamationToken*/ - void 0, - variableType, - initializer - ); + const newVariableDeclaration = factory.createVariableDeclaration(localNameText, /*exclamationToken*/ + void 0, variableType, initializer); const oldVariableDeclaration = getContainingVariableDeclarationIfInList(node, scope); if (oldVariableDeclaration) { changeTracker.insertNodeBefore(context.file, oldVariableDeclaration, newVariableDeclaration); const localReference = factory.createIdentifier(localNameText); changeTracker.replaceNode(context.file, node, localReference); } else if (node.parent.kind === 244 /* ExpressionStatement */ && scope === findAncestor(node, isScope)) { - const newVariableStatement = factory.createVariableStatement( - /*modifiers*/ - void 0, - factory.createVariableDeclarationList([newVariableDeclaration], 2 /* Const */) - ); + const newVariableStatement = factory.createVariableStatement( /*modifiers*/ + void 0, factory.createVariableDeclarationList([newVariableDeclaration], 2 /* Const */)); + changeTracker.replaceNode(context.file, node.parent, newVariableStatement); } else { - const newVariableStatement = factory.createVariableStatement( - /*modifiers*/ - void 0, - factory.createVariableDeclarationList([newVariableDeclaration], 2 /* Const */) - ); + const newVariableStatement = factory.createVariableStatement( /*modifiers*/ + void 0, factory.createVariableDeclarationList([newVariableDeclaration], 2 /* Const */)); + const nodeToInsertBefore = getNodeToInsertConstantBefore(node, scope); if (nodeToInsertBefore.pos === 0) { - changeTracker.insertNodeAtTopOfFile( - context.file, - newVariableStatement, - /*blankLineBetween*/ - false - ); + changeTracker.insertNodeAtTopOfFile(context.file, newVariableStatement, /*blankLineBetween*/ + false); } else { - changeTracker.insertNodeBefore( - context.file, - nodeToInsertBefore, - newVariableStatement, - /*blankLineBetween*/ - false - ); + changeTracker.insertNodeBefore(context.file, nodeToInsertBefore, newVariableStatement, /*blankLineBetween*/ + false); } if (node.parent.kind === 244 /* ExpressionStatement */) { changeTracker.delete(context.file, node.parent); } else { let localReference = factory.createIdentifier(localNameText); if (isInJSXContent(node)) { - localReference = factory.createJsxExpression( - /*dotDotDotToken*/ - void 0, - localReference - ); + localReference = factory.createJsxExpression( /*dotDotDotToken*/ + void 0, localReference); } changeTracker.replaceNode(context.file, node, localReference); } @@ -141365,25 +126518,32 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } const edits = changeTracker.getChanges(); const renameFilename = node.getSourceFile().fileName; - const renameLocation = getRenameLocation( - edits, + const renameLocation = getRenameLocation(edits, renameFilename, localNameText, /*preferLastLocation*/ + true); + return { renameFilename, - localNameText, - /*preferLastLocation*/ - true - ); - return { renameFilename, renameLocation, edits }; + 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) { @@ -141391,13 +126551,14 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} 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); @@ -141406,25 +126567,19 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} const firstParameter = firstOrUndefined(parameters); if (!firstParameter || isIdentifier(firstParameter.name) && firstParameter.name.escapedText !== "this") { const thisType = checker.getTypeOfSymbolAtLocation(functionSignature.thisParameter, node); - parameters.splice( - 0, - 0, - factory.createParameterDeclaration( - /*modifiers*/ - void 0, - /*dotDotDotToken*/ - void 0, - "this", - /*questionToken*/ - void 0, - checker.typeToTypeNode(thisType, scope, 1 /* NoTruncation */) - ) - ); + parameters.splice(0, 0, factory.createParameterDeclaration( /*modifiers*/ + void 0, /*dotDotDotToken*/ + void 0, "this", /*questionToken*/ + void 0, checker.typeToTypeNode(thisType, scope, 1 /* NoTruncation */))); } } + initializer2 = factory.updateFunctionExpression(initializer2, canHaveModifiers(node) ? getModifiers(node) : void 0, initializer2.asteriskToken, initializer2.name, initializer2.typeParameters, parameters, initializer2.type || checker.typeToTypeNode(functionSignature.getReturnType(), scope, 1 /* NoTruncation */), initializer2.body); } - return { variableType: variableType2, initializer: initializer2 }; + return { + variableType: variableType2, + initializer: initializer2 + }; } } function getContainingVariableDeclarationIfInList(node, scope) { @@ -141449,11 +126604,14 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } return firstDeclaration; } - function compareTypesByDeclarationOrder({ type: type1, declaration: declaration1 }, { type: type2, declaration: declaration2 }) { - return compareProperties(declaration1, declaration2, "pos", compareValues) || compareStringsCaseSensitive( - type1.symbol ? type1.symbol.getName() : "", - type2.symbol ? type2.symbol.getName() : "" - ) || compareValues(type1.id, type2.id); + function compareTypesByDeclarationOrder({ + type: type1, + declaration: declaration1 + }, { + type: type2, + declaration: declaration2 + }) { + return compareProperties(declaration1, declaration2, "pos", compareValues) || compareStringsCaseSensitive(type1.symbol ? type1.symbol.getName() : "", type2.symbol ? type2.symbol.getName() : "") || compareValues(type1.id, type2.id); } function getCalledExpression(scope, range, functionNameText) { const functionReference = factory.createIdentifier(functionNameText); @@ -141467,11 +126625,11 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} function transformFunctionBody(body, exposedVariableDeclarations, writes, substitutions, hasReturn2) { const hasWritesOrVariableDeclarations = writes !== void 0 || exposedVariableDeclarations.length > 0; if (isBlock(body) && !hasWritesOrVariableDeclarations && substitutions.size === 0) { - return { body: factory.createBlock( - body.statements, - /*multiLine*/ - true - ), returnValueProperty: void 0 }; + return { + body: factory.createBlock(body.statements, /*multiLine*/ + true), + returnValueProperty: void 0 + }; } let returnValueProperty; let ignoreReturns = false; @@ -141486,17 +126644,17 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} rewrittenStatements.push(factory.createReturnStatement(factory.createObjectLiteralExpression(assignments))); } } - return { body: factory.createBlock( - rewrittenStatements, - /*multiLine*/ - true - ), returnValueProperty }; + return { + body: factory.createBlock(rewrittenStatements, /*multiLine*/ + true), + returnValueProperty + }; } else { - return { body: factory.createBlock( - statements, - /*multiLine*/ - true - ), returnValueProperty: void 0 }; + return { + body: factory.createBlock(statements, /*multiLine*/ + true), + returnValueProperty: void 0 + }; } function visitor(node) { if (!ignoreReturns && isReturnStatement(node) && hasWritesOrVariableDeclarations) { @@ -141545,7 +126703,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return emptyArray; } function getNodeToInsertFunctionBefore(minPos, scope) { - return find(getStatementsOrClassElements(scope), (child) => child.pos >= minPos && isFunctionLikeDeclaration(child) && !isConstructorDeclaration(child)); + return find(getStatementsOrClassElements(scope), child => child.pos >= minPos && isFunctionLikeDeclaration(child) && !isConstructorDeclaration(child)); } function getNodeToInsertPropertyBefore(maxPos, scope) { const members = scope.members; @@ -141564,8 +126722,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } prevMember = member; } - if (prevMember === void 0) - return Debug.fail(); + if (prevMember === void 0) return Debug.fail(); return prevMember; } function getNodeToInsertConstantBefore(node, scope) { @@ -141576,7 +126733,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} prevScope = curr; } } - for (let curr = (prevScope || node).parent; ; curr = curr.parent) { + for (let curr = (prevScope || node).parent;; curr = curr.parent) { if (isBlockLike(curr)) { let prevStatement; for (const statement of curr.statements) { @@ -141595,24 +126752,27 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } } function getPropertyAssignmentsForWritesAndVariableDeclarations(exposedVariableDeclarations, writes) { - const variableAssignments = map(exposedVariableDeclarations, (v) => factory.createShorthandPropertyAssignment(v.symbol.name)); - const writeAssignments = map(writes, (w) => factory.createShorthandPropertyAssignment(w.symbol.name)); + const variableAssignments = map(exposedVariableDeclarations, v => factory.createShorthandPropertyAssignment(v.symbol.name)); + const writeAssignments = map(writes, w => factory.createShorthandPropertyAssignment(w.symbol.name)); return variableAssignments === void 0 ? writeAssignments : writeAssignments === void 0 ? variableAssignments : variableAssignments.concat(writeAssignments); } function isReadonlyArray(v) { return isArray(v); } function getEnclosingTextRange(targetRange, sourceFile) { - return isReadonlyArray(targetRange.range) ? { pos: first(targetRange.range).getStart(sourceFile), end: last(targetRange.range).getEnd() } : targetRange.range; + return isReadonlyArray(targetRange.range) ? { + pos: first(targetRange.range).getStart(sourceFile), + end: last(targetRange.range).getEnd() + } : targetRange.range; } function collectReadsAndWrites(targetRange, scopes, enclosingTextRange, sourceFile, checker, cancellationToken) { - const allTypeParameterUsages = /* @__PURE__ */ new Map(); + const allTypeParameterUsages = /* @__PURE__ */new Map(); const usagesPerScope = []; const substitutionsPerScope = []; const functionErrorsPerScope = []; const constantErrorsPerScope = []; const visibleDeclarationsInExtractedRange = []; - const exposedVariableSymbolSet = /* @__PURE__ */ new Map(); + const exposedVariableSymbolSet = /* @__PURE__ */new Map(); const exposedVariableDeclarations = []; let firstExposedNonVariableDeclaration; const expression = !isReadonlyArray(targetRange.range) ? targetRange.range : targetRange.range.length === 1 && isExpressionStatement(targetRange.range[0]) ? targetRange.range[0].expression : void 0; @@ -141626,8 +126786,12 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} expressionDiagnostic = createDiagnosticForNode(expression, Messages.uselessConstantType); } for (const scope of scopes) { - usagesPerScope.push({ usages: /* @__PURE__ */ new Map(), typeParameterUsages: /* @__PURE__ */ new Map(), substitutions: /* @__PURE__ */ new Map() }); - substitutionsPerScope.push(/* @__PURE__ */ new Map()); + usagesPerScope.push({ + usages: /* @__PURE__ */new Map(), + typeParameterUsages: /* @__PURE__ */new Map(), + substitutions: /* @__PURE__ */new Map() + }); + substitutionsPerScope.push( /* @__PURE__ */new Map()); functionErrorsPerScope.push([]); const constantErrors = []; if (expressionDiagnostic) { @@ -141641,7 +126805,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } constantErrorsPerScope.push(constantErrors); } - const seenUsages = /* @__PURE__ */ new Map(); + const seenUsages = /* @__PURE__ */new Map(); const target = isReadonlyArray(targetRange.range) ? factory.createBlock(targetRange.range) : targetRange.range; const unmodifiedNode = isReadonlyArray(targetRange.range) ? first(targetRange.range) : targetRange.range; const inGenericContext = isInGenericContext(unmodifiedNode); @@ -141651,7 +126815,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} recordTypeParameterUsages(contextualType); } if (allTypeParameterUsages.size > 0) { - const seenTypeParameterUsages = /* @__PURE__ */ new Map(); + const seenTypeParameterUsages = /* @__PURE__ */new Map(); let i = 0; for (let curr = unmodifiedNode; curr !== void 0 && i < scopes.length; curr = curr.parent) { if (curr === scopes[i]) { @@ -141686,7 +126850,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } let hasWrite = false; let readonlyClassPropertyWrite; - usagesPerScope[i].usages.forEach((value) => { + usagesPerScope[i].usages.forEach(value => { if (value.usage === 2 /* Write */) { hasWrite = true; if (value.symbol.flags & 106500 /* ClassMember */ && value.symbol.valueDeclaration && hasEffectiveModifier(value.symbol.valueDeclaration, 8 /* Readonly */)) { @@ -141709,13 +126873,21 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} constantErrorsPerScope[i].push(diag2); } } - return { target, usagesPerScope, functionErrorsPerScope, constantErrorsPerScope, exposedVariableDeclarations }; + return { + target, + usagesPerScope, + functionErrorsPerScope, + constantErrorsPerScope, + exposedVariableDeclarations + }; function isInGenericContext(node) { - return !!findAncestor(node, (n) => isDeclarationWithTypeParameters(n) && getEffectiveTypeParameterDeclarations(n).length !== 0); + return !!findAncestor(node, n => isDeclarationWithTypeParameters(n) && getEffectiveTypeParameterDeclarations(n).length !== 0); } function recordTypeParameterUsages(type) { const symbolWalker = checker.getSymbolWalker(() => (cancellationToken.throwIfCancellationRequested(), true)); - const { visitedTypes } = symbolWalker.walkType(type); + const { + visitedTypes + } = symbolWalker.walkType(type); for (const visitedType of visitedTypes) { if (visitedType.isTypeParameter()) { allTypeParameterUsages.set(visitedType.id.toString(), visitedType); @@ -141747,12 +126919,8 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (isPropertyAccessExpression(node.parent) && node !== node.parent.expression) { return; } - recordUsage( - node, - valueUsage, - /*isTypeNode*/ - isPartOfTypeNode(node) - ); + recordUsage(node, valueUsage, /*isTypeNode*/ + isPartOfTypeNode(node)); } else { forEachChild(node, collectUsages); } @@ -141783,13 +126951,17 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} for (const perScope of usagesPerScope) { const prevEntry = perScope.usages.get(identifier.text); if (prevEntry) { - perScope.usages.set(identifier.text, { usage, symbol, node: identifier }); + perScope.usages.set(identifier.text, { + usage, + symbol, + node: identifier + }); } } return symbolId; } const decls = symbol.getDeclarations(); - const declInFile = decls && find(decls, (d) => d.getSourceFile() === sourceFile); + const declInFile = decls && find(decls, d => d.getSourceFile() === sourceFile); if (!declInFile) { return void 0; } @@ -141807,13 +126979,8 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } for (let i = 0; i < scopes.length; i++) { const scope = scopes[i]; - const resolvedSymbol = checker.resolveName( - symbol.name, - scope, - symbol.flags, - /*excludeGlobals*/ - false - ); + const resolvedSymbol = checker.resolveName(symbol.name, scope, symbol.flags, /*excludeGlobals*/ + false); if (resolvedSymbol === symbol) { continue; } @@ -141828,7 +126995,11 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} constantErrorsPerScope[i].push(diag2); } } else { - usagesPerScope[i].usages.set(identifier.text, { usage, symbol, node: identifier }); + usagesPerScope[i].usages.set(identifier.text, { + usage, + symbol, + node: identifier + }); } } } @@ -141840,7 +127011,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } const sym = isIdentifier(node) ? getSymbolReferencedByIdentifier(node) : checker.getSymbolAtLocation(node); if (sym) { - const decl = find(visibleDeclarationsInExtractedRange, (d) => d.symbol === sym); + const decl = find(visibleDeclarationsInExtractedRange, d => d.symbol === sym); if (decl) { if (isVariableDeclaration(decl)) { const idString = decl.symbol.id.toString(); @@ -141863,7 +127034,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return void 0; } const decls = symbol.getDeclarations(); - if (decls && decls.some((d) => d.parent === scopeDecl)) { + if (decls && decls.some(d => d.parent === scopeDecl)) { return factory.createIdentifier(symbol.name); } const prefix = tryReplaceWithQualifiedNameOrPropertyAccess(symbol.parent, scopeDecl, isTypeNode2); @@ -141874,10 +127045,12 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } } function getExtractableParent(node) { - return findAncestor(node, (node2) => node2.parent && isExtractableExpression(node2) && !isBinaryExpression(node2.parent)); + return findAncestor(node, node2 => node2.parent && isExtractableExpression(node2) && !isBinaryExpression(node2.parent)); } function isExtractableExpression(node) { - const { parent: parent2 } = node; + const { + parent: parent2 + } = node; switch (parent2.kind) { case 306 /* EnumMember */: return false; @@ -141892,6 +127065,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} case 80 /* Identifier */: return parent2.kind !== 208 /* BindingElement */ && parent2.kind !== 276 /* ImportSpecifier */ && parent2.kind !== 281 /* ExportSpecifier */; } + return true; } function isBlockLike(node) { @@ -141915,6 +127089,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} var init_extractSymbol = __esm({ "src/services/refactors/extractSymbol.ts"() { "use strict"; + init_ts4(); init_ts_refactor(); refactorName12 = "Extract Symbol"; @@ -141929,16 +127104,18 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} kind: "refactor.extract.function" }; registerRefactor(refactorName12, { - kinds: [ - extractConstantAction.kind, - extractFunctionAction.kind - ], + kinds: [extractConstantAction.kind, extractFunctionAction.kind], getEditsForAction: getRefactorEditsToExtractSymbol, getAvailableActions: getRefactorActionsToExtractSymbol }); - ((Messages2) => { + (Messages2 => { function createMessage(message) { - return { message, code: 0, category: 3 /* Message */, key: message }; + return { + message, + code: 0, + category: 3 /* Message */, + key: message + }; } Messages2.cannotExtractRange = createMessage("Cannot extract range."); Messages2.cannotExtractImport = createMessage("Cannot extract import statement."); @@ -141964,7 +127141,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} Messages2.cannotExtractToExpressionArrowFunction = createMessage("Cannot extract constant to an arrow function without a block"); Messages2.cannotExtractFunctionsContainingThisToMethod = createMessage("Cannot extract functions containing this to method"); })(Messages || (Messages = {})); - RangeFacts = /* @__PURE__ */ ((RangeFacts2) => { + RangeFacts = /* @__PURE__ */(RangeFacts2 => { RangeFacts2[RangeFacts2["None"] = 0] = "None"; RangeFacts2[RangeFacts2["HasReturn"] = 1] = "HasReturn"; RangeFacts2[RangeFacts2["IsGenerator"] = 2] = "IsGenerator"; @@ -141989,6 +127166,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} var init_ts_refactor_extractSymbol = __esm({ "src/services/_namespaces/ts.refactor.extractSymbol.ts"() { "use strict"; + init_extractSymbol(); } }); @@ -141998,6 +127176,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} var init_generateGetAccessorAndSetAccessor = __esm({ "src/services/refactors/generateGetAccessorAndSetAccessor.ts"() { "use strict"; + init_ts4(); init_ts_refactor(); actionName = "Generate 'get' and 'set' accessors"; @@ -142010,31 +127189,26 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} 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; - const renameLocation = renameLocationOffset + getRenameLocation( - edits, + const renameLocation = renameLocationOffset + getRenameLocation(edits, renameFilename, nameNeedRename.text, /*preferLastLocation*/ + isParameter(info.declaration)); + return { renameFilename, - nameNeedRename.text, - /*preferLastLocation*/ - isParameter(info.declaration) - ); - return { renameFilename, renameLocation, edits }; + 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, @@ -142046,7 +127220,10 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return [{ name: actionName, description: actionDescription, - actions: [{ ...generateGetSetAction, notApplicableReason: info.error }] + actions: [{ + ...generateGetSetAction, + notApplicableReason: info.error + }] }]; } return emptyArray; @@ -142060,6 +127237,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} var init_ts_refactor_generateGetAccessorAndSetAccessor = __esm({ "src/services/_namespaces/ts.refactor.generateGetAccessorAndSetAccessor.ts"() { "use strict"; + init_generateGetAccessorAndSetAccessor(); } }); @@ -142068,15 +127246,18 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} function getRefactorEditsToInferReturnType(context) { const info = getInfo4(context); if (info && !isRefactorErrorInfo(info)) { - const edits = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange7(context.file, t, info.declaration, info.returnTypeNode)); - return { renameFilename: void 0, renameLocation: void 0, edits }; + const edits = ts_textChanges_exports.ChangeTracker.with(context, t => doChange7(context.file, t, info.declaration, info.returnTypeNode)); + return { + renameFilename: void 0, + renameLocation: void 0, + edits + }; } return void 0; } function getRefactorActionsToInferReturnType(context) { const info = getInfo4(context); - if (!info) - return emptyArray; + if (!info) return emptyArray; if (!isRefactorErrorInfo(info)) { return [{ name: refactorName13, @@ -142088,7 +127269,10 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return [{ name: refactorName13, description: refactorDescription7, - actions: [{ ...inferReturnTypeAction, notApplicableReason: info.error }] + actions: [{ + ...inferReturnTypeAction, + notApplicableReason: info.error + }] }]; } return emptyArray; @@ -142102,25 +127286,34 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} changes.insertNodeBefore(sourceFile, endNode2, factory.createToken(21 /* OpenParenToken */)); changes.insertNodeAfter(sourceFile, endNode2, factory.createToken(22 /* CloseParenToken */)); } - changes.insertNodeAt(sourceFile, endNode2.end, typeNode, { prefix: ": " }); + + changes.insertNodeAt(sourceFile, endNode2.end, typeNode, { + prefix: ": " + }); } } 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)); + const declaration = findAncestor(token, n => isBlock(n) || n.parent && isArrowFunction(n.parent) && (n.kind === 39 /* EqualsGreaterThanToken */ || n.parent.body === n) ? "quit" : isConvertibleDeclaration(n)); if (!declaration || !declaration.body || declaration.type) { - return { error: getLocaleSpecificMessage(Diagnostics.Return_type_must_be_inferred_from_a_function) }; + return { + error: getLocaleSpecificMessage(Diagnostics.Return_type_must_be_inferred_from_a_function) + }; } const typeChecker = context.program.getTypeChecker(); const returnType = tryGetReturnType(typeChecker, declaration); if (!returnType) { - return { error: getLocaleSpecificMessage(Diagnostics.Could_not_determine_function_return_type) }; + return { + error: getLocaleSpecificMessage(Diagnostics.Could_not_determine_function_return_type) + }; } const returnTypeNode = typeChecker.typeToTypeNode(returnType, declaration, 1 /* NoTruncation */); if (returnTypeNode) { - return { declaration, returnTypeNode }; + return { + declaration, + returnTypeNode + }; } } function isConvertibleDeclaration(node) { @@ -142138,7 +127331,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (typeChecker.isImplementationOfOverload(node)) { const signatures = typeChecker.getTypeAtLocation(node).getCallSignatures(); if (signatures.length > 1) { - return typeChecker.getUnionType(mapDefined(signatures, (s) => s.getReturnType())); + return typeChecker.getUnionType(mapDefined(signatures, s => s.getReturnType())); } } const signature = typeChecker.getSignatureFromDeclaration(node); @@ -142150,6 +127343,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} var init_inferFunctionReturnType = __esm({ "src/services/refactors/inferFunctionReturnType.ts"() { "use strict"; + init_ts4(); init_ts_refactor(); refactorName13 = "Infer function return type"; @@ -142172,6 +127366,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} var init_ts_refactor_inferFunctionReturnType = __esm({ "src/services/_namespaces/ts.refactor.inferFunctionReturnType.ts"() { "use strict"; + init_inferFunctionReturnType(); } }); @@ -142215,6 +127410,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} var init_ts_refactor = __esm({ "src/services/_namespaces/ts.refactor.ts"() { "use strict"; + init_refactorProvider(); init_convertExport(); init_convertImport(); @@ -142254,6 +127450,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} endOfLineState: 0 /* None */ }; } + function getSemanticTokens(program, sourceFile, span, cancellationToken) { const resultTokens = []; const collector = (node, typeIdx, modifierSet) => { @@ -142303,9 +127500,11 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} modifierSet = 1 << 0 /* declaration */; } } + if (typeIdx === 6 /* parameter */ && isRightSideOfQualifiedNameOrPropertyAccess2(node)) { typeIdx = 9 /* property */; } + typeIdx = reclassifyByType(typeChecker, node, typeIdx); const decl = symbol.valueDeclaration; if (decl) { @@ -142314,23 +127513,28 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (modifiers & 256 /* Static */) { modifierSet |= 1 << 1 /* static */; } + if (modifiers & 1024 /* Async */) { modifierSet |= 1 << 2 /* async */; } + if (typeIdx !== 0 /* class */ && typeIdx !== 2 /* interface */) { if (modifiers & 8 /* Readonly */ || nodeFlags & 2 /* Const */ || symbol.getFlags() & 8 /* EnumMember */) { modifierSet |= 1 << 3 /* readonly */; } } + if ((typeIdx === 7 /* variable */ || typeIdx === 10 /* function */) && isLocalDeclaration(decl, sourceFile)) { modifierSet |= 1 << 5 /* local */; } + if (program.isSourceFileDefaultLibrary(decl.getSourceFile())) { modifierSet |= 1 << 4 /* defaultLibrary */; } - } else if (symbol.declarations && symbol.declarations.some((d) => program.isSourceFileDefaultLibrary(d.getSourceFile()))) { + } else if (symbol.declarations && symbol.declarations.some(d => program.isSourceFileDefaultLibrary(d.getSourceFile()))) { modifierSet |= 1 << 4 /* defaultLibrary */; } + collector(node, typeIdx, modifierSet); } } @@ -142355,6 +127559,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } else if (flags & 262144 /* TypeParameter */) { return 4 /* typeParameter */; } + let decl = symbol.valueDeclaration || symbol.declarations && symbol.declarations[0]; if (decl && isBindingElement(decl)) { decl = getDeclarationForBindingElement(decl); @@ -142365,17 +127570,19 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (typeIdx === 7 /* variable */ || typeIdx === 9 /* property */ || typeIdx === 6 /* parameter */) { const type = typeChecker.getTypeAtLocation(node); if (type) { - const test = (condition) => { + const test = condition => { return condition(type) || type.isUnion() && type.types.some(condition); }; - if (typeIdx !== 6 /* parameter */ && test((t) => t.getConstructSignatures().length > 0)) { + if (typeIdx !== 6 /* parameter */ && test(t => t.getConstructSignatures().length > 0)) { return 0 /* class */; } - if (test((t) => t.getCallSignatures().length > 0) && !test((t) => t.getProperties().length > 0) || isExpressionInCallExpression(node)) { + + if (test(t => t.getCallSignatures().length > 0) && !test(t => t.getProperties().length > 0) || isExpressionInCallExpression(node)) { return typeIdx === 9 /* property */ ? 11 /* member */ : 10 /* function */; } } } + return typeIdx; } function isLocalDeclaration(decl, sourceFile) { @@ -142415,13 +127622,14 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} var init_classifier2020 = __esm({ "src/services/classifier2020.ts"() { "use strict"; + init_ts4(); - TokenEncodingConsts = /* @__PURE__ */ ((TokenEncodingConsts2) => { + TokenEncodingConsts = /* @__PURE__ */(TokenEncodingConsts2 => { TokenEncodingConsts2[TokenEncodingConsts2["typeOffset"] = 8] = "typeOffset"; TokenEncodingConsts2[TokenEncodingConsts2["modifierMask"] = 255] = "modifierMask"; return TokenEncodingConsts2; })(TokenEncodingConsts || {}); - TokenType = /* @__PURE__ */ ((TokenType2) => { + TokenType = /* @__PURE__ */(TokenType2 => { TokenType2[TokenType2["class"] = 0] = "class"; TokenType2[TokenType2["enum"] = 1] = "enum"; TokenType2[TokenType2["interface"] = 2] = "interface"; @@ -142436,7 +127644,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} TokenType2[TokenType2["member"] = 11] = "member"; return TokenType2; })(TokenType || {}); - TokenModifier = /* @__PURE__ */ ((TokenModifier2) => { + TokenModifier = /* @__PURE__ */(TokenModifier2 => { TokenModifier2[TokenModifier2["declaration"] = 0] = "declaration"; TokenModifier2[TokenModifier2["static"] = 1] = "static"; TokenModifier2[TokenModifier2["async"] = 2] = "async"; @@ -142445,27 +127653,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} TokenModifier2[TokenModifier2["local"] = 5] = "local"; return TokenModifier2; })(TokenModifier || {}); - tokenFromDeclarationMapping = /* @__PURE__ */ new Map([ - [260 /* VariableDeclaration */, 7 /* variable */], - [169 /* Parameter */, 6 /* parameter */], - [172 /* PropertyDeclaration */, 9 /* property */], - [267 /* ModuleDeclaration */, 3 /* namespace */], - [266 /* EnumDeclaration */, 1 /* enum */], - [306 /* EnumMember */, 8 /* enumMember */], - [263 /* ClassDeclaration */, 0 /* class */], - [174 /* MethodDeclaration */, 11 /* member */], - [262 /* FunctionDeclaration */, 10 /* function */], - [218 /* FunctionExpression */, 10 /* function */], - [173 /* MethodSignature */, 11 /* member */], - [177 /* GetAccessor */, 9 /* property */], - [178 /* SetAccessor */, 9 /* property */], - [171 /* PropertySignature */, 9 /* property */], - [264 /* InterfaceDeclaration */, 2 /* interface */], - [265 /* TypeAliasDeclaration */, 5 /* type */], - [168 /* TypeParameter */, 4 /* typeParameter */], - [303 /* PropertyAssignment */, 9 /* property */], - [304 /* ShorthandPropertyAssignment */, 9 /* property */] - ]); + tokenFromDeclarationMapping = /* @__PURE__ */new Map([[260 /* VariableDeclaration */, 7 /* variable */], [169 /* Parameter */, 6 /* parameter */], [172 /* PropertyDeclaration */, 9 /* property */], [267 /* ModuleDeclaration */, 3 /* namespace */], [266 /* EnumDeclaration */, 1 /* enum */], [306 /* EnumMember */, 8 /* enumMember */], [263 /* ClassDeclaration */, 0 /* class */], [174 /* MethodDeclaration */, 11 /* member */], [262 /* FunctionDeclaration */, 10 /* function */], [218 /* FunctionExpression */, 10 /* function */], [173 /* MethodSignature */, 11 /* member */], [177 /* GetAccessor */, 9 /* property */], [178 /* SetAccessor */, 9 /* property */], [171 /* PropertySignature */, 9 /* property */], [264 /* InterfaceDeclaration */, 2 /* interface */], [265 /* TypeAliasDeclaration */, 5 /* type */], [168 /* TypeParameter */, 4 /* typeParameter */], [303 /* PropertyAssignment */, 9 /* property */], [304 /* ShorthandPropertyAssignment */, 9 /* property */]]); } }); @@ -142482,19 +127670,19 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } const children = []; if (isJSDocCommentContainingNode(node)) { - node.forEachChild((child) => { + node.forEachChild(child => { children.push(child); }); return children; } scanner.setText((sourceFile || node.getSourceFile()).text); let pos = node.pos; - const processNode = (child) => { + const processNode = child => { addSyntheticNodes(children, pos, child.pos, node); children.push(child); pos = child.end; }; - const processNodes = (nodes) => { + const processNodes = nodes => { addSyntheticNodes(children, pos, nodes.pos, node); children.push(createSyntaxList(nodes, node)); pos = nodes.end; @@ -142539,16 +127727,15 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return list; } function hasJSDocInheritDocTag(node) { - return getJSDocTags(node).some((tag) => tag.tagName.text === "inheritDoc" || tag.tagName.text === "inheritdoc"); + 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(); + const seenSymbols = /* @__PURE__ */new Set(); for (const declaration of declarations) { - const inheritedTags = findBaseOfDeclaration(checker, declaration, (symbol) => { + const inheritedTags = findBaseOfDeclaration(checker, declaration, symbol => { var _a; if (!seenSymbols.has(symbol)) { seenSymbols.add(symbol); @@ -142566,13 +127753,12 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} 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(); + const seenSymbols = /* @__PURE__ */new Set(); for (const declaration of declarations) { - const inheritedDocs = findBaseOfDeclaration(checker, declaration, (symbol) => { + const inheritedDocs = findBaseOfDeclaration(checker, declaration, symbol => { if (!seenSymbols.has(symbol)) { seenSymbols.add(symbol); if (declaration.kind === 177 /* GetAccessor */ || declaration.kind === 178 /* SetAccessor */) { @@ -142581,8 +127767,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} 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; @@ -142590,10 +127775,9 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} function findBaseOfDeclaration(checker, declaration, cb) { var _a; const classOrInterfaceDeclaration = ((_a = declaration.parent) == null ? void 0 : _a.kind) === 176 /* Constructor */ ? declaration.parent.parent : declaration.parent; - if (!classOrInterfaceDeclaration) - return; + if (!classOrInterfaceDeclaration) return; const isStaticMember = hasStaticModifier(declaration); - return firstDefined(getAllSuperTypeNodes(classOrInterfaceDeclaration), (superTypeNode) => { + return firstDefined(getAllSuperTypeNodes(classOrInterfaceDeclaration), superTypeNode => { const baseType = checker.getTypeAtLocation(superTypeNode); const type = isStaticMember && baseType.symbol ? checker.getTypeOfSymbol(baseType.symbol) : baseType; const symbol = checker.getPropertyOfType(type, declaration.symbol.name); @@ -142638,7 +127822,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } function displayPartsToString(displayParts) { if (displayParts) { - return map(displayParts, (displayPart2) => displayPart2.text).join(""); + return map(displayParts, displayPart2 => displayPart2.text).join(""); } return ""; } @@ -142648,6 +127832,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} jsx: 1 /* Preserve */ }; } + function getSupportedCodeFixes() { return ts_codefix_exports.getSupportedErrorCodes(); } @@ -142690,15 +127875,8 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} setExternalModuleIndicator: sourceFile.setExternalModuleIndicator, jsDocParsingMode: sourceFile.jsDocParsingMode }; - return createLanguageServiceSourceFile( - sourceFile.fileName, - scriptSnapshot, - options, - version2, - /*setNodeParents*/ - true, - sourceFile.scriptKind - ); + return createLanguageServiceSourceFile(sourceFile.fileName, scriptSnapshot, options, version2, /*setNodeParents*/ + true, sourceFile.scriptKind); } function createLanguageService(host, documentRegistry = createDocumentRegistry(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames(), host.getCurrentDirectory()), syntaxOnlyOrLanguageServiceMode) { var _a; @@ -142738,7 +127916,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} const sourceFile = program.getSourceFile(fileName); if (!sourceFile) { const error2 = new Error(`Could not find source file: '${fileName}'.`); - error2.ProgramFiles = program.getSourceFiles().map((f) => f.fileName); + error2.ProgramFiles = program.getSourceFiles().map(f => f.fileName); throw error2; } return sourceFile; @@ -142775,17 +127953,17 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} getCanonicalFileName, useCaseSensitiveFileNames: () => useCaseSensitiveFileNames2, getNewLine: () => getNewLineCharacter(newSettings), - getDefaultLibFileName: (options2) => host.getDefaultLibFileName(options2), + getDefaultLibFileName: options2 => host.getDefaultLibFileName(options2), writeFile: noop, getCurrentDirectory: () => currentDirectory, - fileExists: (fileName) => host.fileExists(fileName), - readFile: (fileName) => host.readFile && host.readFile(fileName), + fileExists: fileName => host.fileExists(fileName), + readFile: fileName => host.readFile && host.readFile(fileName), getSymlinkCache: maybeBind(host, host.getSymlinkCache), realpath: maybeBind(host, host.realpath), - directoryExists: (directoryName) => { + directoryExists: directoryName => { return directoryProbablyExists(directoryName, host); }, - getDirectories: (path) => { + getDirectories: path => { return host.getDirectories ? host.getDirectories(path) : []; }, readDirectory: (path, extensions, exclude, include, depth) => { @@ -142810,19 +127988,17 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} jsDocParsingMode: host.jsDocParsingMode }; const originalGetSourceFile = compilerHost.getSourceFile; - const { getSourceFileWithCache } = changeCompilerHostLikeToUseCache( - compilerHost, - (fileName) => toPath(fileName, currentDirectory, getCanonicalFileName), - (...args) => originalGetSourceFile.call(compilerHost, ...args) - ); + const { + getSourceFileWithCache + } = changeCompilerHostLikeToUseCache(compilerHost, fileName => toPath(fileName, currentDirectory, getCanonicalFileName), (...args) => originalGetSourceFile.call(compilerHost, ...args)); compilerHost.getSourceFile = getSourceFileWithCache; (_c = host.setCompilerHost) == null ? void 0 : _c.call(host, compilerHost); const parseConfigHost = { useCaseSensitiveFileNames: useCaseSensitiveFileNames2, - fileExists: (fileName) => compilerHost.fileExists(fileName), - readFile: (fileName) => compilerHost.readFile(fileName), - directoryExists: (f) => compilerHost.directoryExists(f), - getDirectories: (f) => compilerHost.getDirectories(f), + fileExists: fileName => compilerHost.fileExists(fileName), + readFile: fileName => compilerHost.readFile(fileName), + directoryExists: f => compilerHost.directoryExists(f), + getDirectories: f => compilerHost.getDirectories(f), realpath: compilerHost.realpath, readDirectory: (...args) => compilerHost.readDirectory(...args), trace: compilerHost.trace, @@ -142830,8 +128006,8 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} onUnRecoverableConfigFileDiagnostic: noop }; const documentRegistryBucketKey = documentRegistry.getKeyForCompilationSettings(newSettings); - let releasedScriptKinds = /* @__PURE__ */ new Set(); - if (isProgramUptoDate(program, rootFileNames, newSettings, (_path, fileName) => host.getScriptVersion(fileName), (fileName) => compilerHost.fileExists(fileName), hasInvalidatedResolutions, hasInvalidatedLibResolutions, hasChangedAutomaticTypeDirectiveNames, getParsedCommandLine, projectReferences)) { + let releasedScriptKinds = /* @__PURE__ */new Set(); + if (isProgramUptoDate(program, rootFileNames, newSettings, (_path, fileName) => host.getScriptVersion(fileName), fileName => compilerHost.fileExists(fileName), hasInvalidatedResolutions, hasInvalidatedLibResolutions, hasChangedAutomaticTypeDirectiveNames, getParsedCommandLine, projectReferences)) { compilerHost = void 0; parsedCommandLines = void 0; releasedScriptKinds = void 0; @@ -142854,27 +128030,19 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} 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); + (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; - return parseJsonSourceFileConfigFileContent( - result, - parseConfigHost, - getNormalizedAbsolutePath(getDirectoryPath(configFileName), currentDirectory), - /*existingOptions*/ - void 0, - getNormalizedAbsolutePath(configFileName, currentDirectory) - ); + return parseJsonSourceFileConfigFileContent(result, parseConfigHost, getNormalizedAbsolutePath(getDirectoryPath(configFileName), currentDirectory), /*existingOptions*/ + void 0, getNormalizedAbsolutePath(configFileName, currentDirectory)); } function onReleaseParsedCommandLine(configFileName, oldResolvedRef, oldOptions) { var _a3; @@ -142928,8 +128096,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} 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); @@ -142968,17 +128135,18 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } 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 }); + const adjustedNode = ts_FindAllReferences_exports.Core.getAdjustedNode(rawNode, { + use: ts_FindAllReferences_exports.FindReferencesUse.References + }); return adjustedNode; } } function cleanupSemanticCache() { if (program) { const key = documentRegistry.getKeyForCompilationSettings(program.getCompilerOptions()); - forEach(program.getSourceFiles(), (f) => documentRegistry.releaseDocumentWithKey(f.resolvedPath, key, f.scriptKind, f.impliedNodeFormat)); + forEach(program.getSourceFiles(), f => documentRegistry.releaseDocumentWithKey(f.resolvedPath, key, f.scriptKind, f.impliedNodeFormat)); program = void 0; } } @@ -143016,38 +128184,24 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} includeCompletionsWithInsertText: options.includeCompletionsWithInsertText || options.includeInsertTextCompletions }; synchronizeHostData(); - return ts_Completions_exports.getCompletionsAtPosition( - host, - program, - log, - getValidSourceFile(fileName), - position, - fullPreferences, - options.triggerCharacter, - options.triggerKind, - cancellationToken, - formattingSettings && ts_formatting_exports.getFormatContext(formattingSettings, host), - options.includeSymbol - ); + return ts_Completions_exports.getCompletionsAtPosition(host, program, log, getValidSourceFile(fileName), position, fullPreferences, options.triggerCharacter, options.triggerKind, cancellationToken, formattingSettings && ts_formatting_exports.getFormatContext(formattingSettings, host), options.includeSymbol); } function getCompletionEntryDetails2(fileName, position, name, formattingOptions, source, preferences = emptyOptions, data) { synchronizeHostData(); - return ts_Completions_exports.getCompletionEntryDetails( - program, - log, - getValidSourceFile(fileName), - position, - { name, source, data }, - host, - formattingOptions && ts_formatting_exports.getFormatContext(formattingOptions, host), - // TODO: GH#18217 - preferences, - cancellationToken - ); + return ts_Completions_exports.getCompletionEntryDetails(program, log, getValidSourceFile(fileName), position, { + name, + source, + data + }, host, formattingOptions && ts_formatting_exports.getFormatContext(formattingOptions, host), + // TODO: GH#18217 + preferences, cancellationToken); } function getCompletionEntrySymbol2(fileName, position, name, source, preferences = emptyOptions) { synchronizeHostData(); - return ts_Completions_exports.getCompletionEntrySymbol(program, log, getValidSourceFile(fileName), position, { name, source }, host, preferences); + return ts_Completions_exports.getCompletionEntrySymbol(program, log, getValidSourceFile(fileName), position, { + name, + source + }, host, preferences); } function getQuickInfoAtPosition(fileName, position) { synchronizeHostData(); @@ -143065,12 +128219,17 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} kind: "" /* unknown */, kindModifiers: "" /* none */, textSpan: createTextSpanFromNode(nodeForQuickInfo, sourceFile), - displayParts: typeChecker.runWithCancellationToken(cancellationToken, (typeChecker2) => typeToDisplayParts(typeChecker2, type, getContainerNode(nodeForQuickInfo))), + displayParts: typeChecker.runWithCancellationToken(cancellationToken, typeChecker2 => typeToDisplayParts(typeChecker2, type, getContainerNode(nodeForQuickInfo))), documentation: type.symbol ? type.symbol.getDocumentationComment(typeChecker) : void 0, tags: type.symbol ? type.symbol.getJsDocTags(typeChecker) : void 0 }; } - const { symbolKind, displayParts, documentation, tags } = typeChecker.runWithCancellationToken(cancellationToken, (typeChecker2) => ts_SymbolDisplay_exports.getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker2, symbol, sourceFile, getContainerNode(nodeForQuickInfo), nodeForQuickInfo)); + const { + symbolKind, + displayParts, + documentation, + tags + } = typeChecker.runWithCancellationToken(cancellationToken, typeChecker2 => ts_SymbolDisplay_exports.getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker2, symbol, sourceFile, getContainerNode(nodeForQuickInfo), nodeForQuickInfo)); return { kind: symbolKind, kindModifiers: ts_SymbolDisplay_exports.getSymbolModifiers(typeChecker, symbol), @@ -143131,9 +128290,9 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } function getDocumentHighlights(fileName, position, filesToSearch) { const normalizedFileName = normalizePath(fileName); - Debug.assert(filesToSearch.some((f) => normalizePath(f) === normalizedFileName)); + Debug.assert(filesToSearch.some(f => normalizePath(f) === normalizedFileName)); synchronizeHostData(); - const sourceFilesToSearch = mapDefined(filesToSearch, (fileName2) => program.getSourceFile(fileName2)); + const sourceFilesToSearch = mapDefined(filesToSearch, fileName2 => program.getSourceFile(fileName2)); const sourceFile = getValidSourceFile(fileName); return DocumentHighlights.getDocumentHighlights(program, cancellationToken, sourceFile, position, sourceFilesToSearch); } @@ -143141,11 +128300,13 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} 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) => { + const { + openingElement, + closingElement + } = node.parent.parent; + return [openingElement, closingElement].map(node2 => { const textSpan = createTextSpanFromNode(node2.tagName, sourceFile); return { fileName: sourceFile.fileName, @@ -143154,18 +128315,25 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} }; }); } else { - const quotePreference = getQuotePreference(sourceFile, preferences ?? emptyOptions); + const quotePreference = getQuotePreference(sourceFile, preferences !== null && preferences !== void 0 ? preferences : emptyOptions); const providePrefixAndSuffixTextForRename = typeof preferences === "boolean" ? preferences : preferences == null ? void 0 : preferences.providePrefixAndSuffixTextForRename; - return getReferencesWorker2(node, position, { findInStrings, findInComments, providePrefixAndSuffixTextForRename, use: ts_FindAllReferences_exports.FindReferencesUse.Rename }, (entry, originalNode, checker) => ts_FindAllReferences_exports.toRenameLocation(entry, originalNode, checker, providePrefixAndSuffixTextForRename || false, quotePreference)); + return getReferencesWorker2(node, position, { + findInStrings, + findInComments, + providePrefixAndSuffixTextForRename, + use: ts_FindAllReferences_exports.FindReferencesUse.Rename + }, (entry, originalNode, checker) => ts_FindAllReferences_exports.toRenameLocation(entry, originalNode, checker, providePrefixAndSuffixTextForRename || false, quotePreference)); } } function getReferencesAtPosition(fileName, position) { synchronizeHostData(); - return getReferencesWorker2(getTouchingPropertyName(getValidSourceFile(fileName), position), position, { use: ts_FindAllReferences_exports.FindReferencesUse.References }, ts_FindAllReferences_exports.toReferenceEntry); + return getReferencesWorker2(getTouchingPropertyName(getValidSourceFile(fileName), position), position, { + use: ts_FindAllReferences_exports.FindReferencesUse.References + }, ts_FindAllReferences_exports.toReferenceEntry); } function getReferencesWorker2(node, position, options, cb) { synchronizeHostData(); - const sourceFiles = options && options.use === ts_FindAllReferences_exports.FindReferencesUse.Rename ? program.getSourceFiles().filter((sourceFile) => !program.isSourceFileDefaultLibrary(sourceFile)) : program.getSourceFiles(); + const sourceFiles = options && options.use === ts_FindAllReferences_exports.FindReferencesUse.Rename ? program.getSourceFiles().filter(sourceFile => !program.isSourceFileDefaultLibrary(sourceFile)) : program.getSourceFiles(); return ts_FindAllReferences_exports.findReferenceOrRenameEntries(program, cancellationToken, sourceFiles, node, position, options, cb); } function findReferences(fileName, position) { @@ -143187,7 +128355,9 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} const customTransformers = host.getCustomTransformers && host.getCustomTransformers(); return getFileEmitOutput(program, sourceFile, !!emitOnlyDtsFiles, cancellationToken, customTransformers, forceDtsEmit); } - function getSignatureHelpItems2(fileName, position, { triggerReason } = emptyOptions) { + function getSignatureHelpItems2(fileName, position, { + triggerReason + } = emptyOptions) { synchronizeHostData(); const sourceFile = getValidSourceFile(fileName); return ts_SignatureHelp_exports.getSignatureHelpItems(program, sourceFile, position, triggerReason, cancellationToken); @@ -143276,6 +128446,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} [23 /* OpenBracketToken */]: 24 /* CloseBracketToken */, [32 /* GreaterThanToken */]: 30 /* LessThanToken */ })); + braceMatching.forEach((value, key) => braceMatching.set(value.toString(), Number(key))); function getBraceMatchingAtPosition(fileName, position) { const sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); @@ -143323,9 +128494,18 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} const sourceFile = getValidSourceFile(fileName); const span = createTextSpanFromBounds(start, end); const formatContext = ts_formatting_exports.getFormatContext(formatOptions, host); - return flatMap(deduplicate(errorCodes64, equateValues, compareValues), (errorCode) => { + return flatMap(deduplicate(errorCodes64, equateValues, compareValues), errorCode => { cancellationToken.throwIfCancellationRequested(); - return ts_codefix_exports.getFixes({ errorCode, sourceFile, span, program, host, cancellationToken, formatContext, preferences }); + return ts_codefix_exports.getFixes({ + errorCode, + sourceFile, + span, + program, + host, + cancellationToken, + formatContext, + preferences + }); }); } function getCombinedCodeFix(scope, fixId52, formatOptions, preferences = emptyOptions) { @@ -143333,14 +128513,23 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} Debug.assert(scope.type === "file"); const sourceFile = getValidSourceFile(scope.fileName); const formatContext = ts_formatting_exports.getFormatContext(formatOptions, host); - return ts_codefix_exports.getAllFixes({ fixId: fixId52, sourceFile, program, host, cancellationToken, formatContext, preferences }); + return ts_codefix_exports.getAllFixes({ + fixId: fixId52, + sourceFile, + program, + host, + cancellationToken, + formatContext, + preferences + }); } function organizeImports2(args, formatOptions, preferences = emptyOptions) { + var _args$mode; synchronizeHostData(); Debug.assert(args.type === "file"); const sourceFile = getValidSourceFile(args.fileName); const formatContext = ts_formatting_exports.getFormatContext(formatOptions, host); - const mode = args.mode ?? (args.skipDestructiveCodeActions ? "SortAndCombine" /* SortAndCombine */ : "All" /* All */); + const mode = (_args$mode = args.mode) !== null && _args$mode !== void 0 ? _args$mode : args.skipDestructiveCodeActions ? "SortAndCombine" /* SortAndCombine */ : "All" /* All */; return ts_OrganizeImports_exports.organizeImports(sourceFile, formatContext, host, program, preferences, mode); } function getEditsForFileRename2(oldFilePath, newFilePath, formatOptions, preferences = emptyOptions) { @@ -143348,12 +128537,15 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } function applyCodeActionCommand(fileName, actionOrFormatSettingsOrUndefined) { const action = typeof fileName === "string" ? actionOrFormatSettingsOrUndefined : fileName; - return isArray(action) ? Promise.all(action.map((a) => applySingleCodeActionCommand(a))) : applySingleCodeActionCommand(action); + return isArray(action) ? Promise.all(action.map(a => applySingleCodeActionCommand(a))) : applySingleCodeActionCommand(action); } function applySingleCodeActionCommand(action) { - const getPath = (path) => toPath(path, currentDirectory, getCanonicalFileName); + const getPath = path => toPath(path, currentDirectory, getCanonicalFileName); Debug.assertEqual(action.type, "install package"); - return host.installPackage ? host.installPackage({ fileName: getPath(action.file), packageName: action.packageName }) : Promise.reject("Host does not implement `installPackage`"); + return host.installPackage ? host.installPackage({ + fileName: getPath(action.file), + packageName: action.packageName + }) : Promise.reject("Host does not implement `installPackage`"); } function getDocCommentTemplateAtPosition2(fileName, position, options, formatOptions) { const formatSettings = formatOptions ? ts_formatting_exports.getFormatContext(formatOptions, host).options : void 0; @@ -143370,6 +128562,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (isInsideJsxElementOrAttribute(sourceFile, position)) { return openingBrace === 123 /* openBrace */; } + if (isInTemplateString(sourceFile, position)) { return false; } @@ -143384,45 +128577,50 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} 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: `` }; + return { + newText: `` + }; } const fragment = token.kind === 32 /* GreaterThanToken */ && isJsxOpeningFragment(token.parent) ? token.parent.parent : isJsxText(token) && isJsxFragment(token.parent) ? token.parent : void 0; if (fragment && isUnclosedFragment(fragment)) { - return { newText: "" }; + return { + newText: "" + }; } } function getLinkedEditingRangeAtPosition(fileName, position) { const sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); const token = findPrecedingToken(position, sourceFile); - if (!token || token.parent.kind === 312 /* SourceFile */) - return void 0; + if (!token || token.parent.kind === 312 /* SourceFile */) return void 0; const jsxTagWordPattern = "[a-zA-Z0-9:\\-\\._$]*"; if (isJsxFragment(token.parent.parent)) { const openFragment = token.parent.parent.openingFragment; const closeFragment = token.parent.parent.closingFragment; - if (containsParseError(openFragment) || containsParseError(closeFragment)) - return void 0; + 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 }], + ranges: [{ + start: openPos, + length: 0 + }, { + start: closePos, + length: 0 + }], wordPattern: jsxTagWordPattern }; } else { - const tag = findAncestor(token.parent, (n) => { + const tag = findAncestor(token.parent, n => { if (isJsxOpeningElement(n) || isJsxClosingElement(n)) { return true; } 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; @@ -143430,13 +128628,17 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} const openTagEnd = openTag.tagName.end; const closeTagStart = closeTag.tagName.getStart(sourceFile); const closeTagEnd = closeTag.tagName.end; - if (!(openTagStart <= position && position <= openTagEnd || closeTagStart <= position && position <= closeTagEnd)) - return void 0; + if (!(openTagStart <= position && position <= openTagEnd || closeTagStart <= position && position <= closeTagEnd)) return void 0; const openingTagText = openTag.tagName.getText(sourceFile); - if (openingTagText !== closeTag.tagName.getText(sourceFile)) - return void 0; + if (openingTagText !== closeTag.tagName.getText(sourceFile)) return void 0; return { - ranges: [{ start: openTagStart, length: openTagEnd - openTagStart }, { start: closeTagStart, length: closeTagEnd - closeTagStart }], + ranges: [{ + start: openTagStart, + length: openTagEnd - openTagStart + }, { + start: closeTagStart, + length: closeTagEnd - closeTagStart + }], wordPattern: jsxTagWordPattern }; } @@ -143451,10 +128653,14 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} function toggleLineComment(fileName, textRange, insertComment) { const sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); const textChanges2 = []; - const { lineStarts, firstLine, lastLine } = getLinesForRange(sourceFile, textRange); + const { + lineStarts, + firstLine, + lastLine + } = getLinesForRange(sourceFile, textRange); let isCommenting = insertComment || false; let leftMostPosition = Number.MAX_VALUE; - const lineTextStarts = /* @__PURE__ */ new Map(); + const lineTextStarts = /* @__PURE__ */new Map(); const firstNonWhitespaceCharacterRegex = new RegExp(/\S/); const isJsx = isInsideJsxElement(sourceFile, lineStarts[firstLine]); const openComment = isJsx ? "{/*" : "//"; @@ -143476,7 +128682,10 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} const lineTextStart = lineTextStarts.get(i.toString()); if (lineTextStart !== void 0) { if (isJsx) { - textChanges2.push(...toggleMultilineComment(fileName, { pos: lineStarts[i] + leftMostPosition, end: sourceFile.getLineEndOfPosition(lineStarts[i]) }, isCommenting, isJsx)); + textChanges2.push(...toggleMultilineComment(fileName, { + pos: lineStarts[i] + leftMostPosition, + end: sourceFile.getLineEndOfPosition(lineStarts[i]) + }, isCommenting, isJsx)); } else if (isCommenting) { textChanges2.push({ newText: openComment, @@ -143502,11 +128711,15 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} var _a2; const sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); const textChanges2 = []; - const { text } = sourceFile; + const { + text + } = sourceFile; let hasComment = false; let isCommenting = insertComment || false; const positions = []; - let { pos } = textRange; + let { + pos + } = textRange; const isJsx = isInsideJsx !== void 0 ? isInsideJsx : isInsideJsxElement(sourceFile, pos); const openMultiline = isJsx ? "{/*" : "/*"; const closeMultiline = isJsx ? "*/}" : "*/"; @@ -143593,24 +128806,23 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } function commentSelection(fileName, textRange) { const sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); - const { firstLine, lastLine } = getLinesForRange(sourceFile, textRange); - return firstLine === lastLine && textRange.pos !== textRange.end ? toggleMultilineComment( - fileName, - textRange, - /*insertComment*/ - true - ) : toggleLineComment( - fileName, - textRange, - /*insertComment*/ - true - ); + const { + firstLine, + lastLine + } = getLinesForRange(sourceFile, textRange); + return firstLine === lastLine && textRange.pos !== textRange.end ? toggleMultilineComment(fileName, textRange, /*insertComment*/ + true) : toggleLineComment(fileName, textRange, /*insertComment*/ + true); } function uncommentSelection(fileName, textRange) { const sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); const textChanges2 = []; - const { pos } = textRange; - let { end } = textRange; + const { + pos + } = textRange; + let { + end + } = textRange; if (pos === end) { end += isInsideJsxElement(sourceFile, pos) ? 2 : 1; } @@ -143619,30 +128831,35 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (commentRange) { switch (commentRange.kind) { case 2 /* SingleLineCommentTrivia */: - textChanges2.push(...toggleLineComment( - fileName, - { end: commentRange.end, pos: commentRange.pos + 1 }, - /*insertComment*/ - false - )); + textChanges2.push(...toggleLineComment(fileName, { + end: commentRange.end, + pos: commentRange.pos + 1 + }, /*insertComment*/ + false)); break; case 3 /* MultiLineCommentTrivia */: - textChanges2.push(...toggleMultilineComment( - fileName, - { end: commentRange.end, pos: commentRange.pos + 1 }, - /*insertComment*/ - false - )); + textChanges2.push(...toggleMultilineComment(fileName, { + end: commentRange.end, + pos: commentRange.pos + 1 + }, /*insertComment*/ + false)); } i = commentRange.end + 1; } } return textChanges2; } - function isUnclosedTag({ openingElement, closingElement, parent: parent2 }) { + function isUnclosedTag({ + openingElement, + closingElement, + parent: parent2 + }) { return !tagNamesAreEquivalent(openingElement.tagName, closingElement.tagName) || isJsxElement(parent2) && tagNamesAreEquivalent(openingElement.tagName, parent2.openingElement.tagName) && isUnclosedTag(parent2); } - function isUnclosedFragment({ closingFragment, parent: parent2 }) { + function isUnclosedFragment({ + closingFragment, + parent: parent2 + }) { return !!(closingFragment.flags & 262144 /* ThisNodeHasError */) || isJsxFragment(parent2) && isUnclosedFragment(parent2); } function getSpanOfEnclosingComment(fileName, position, onlyMultiLine) { @@ -143674,13 +128891,16 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} 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; } const message = matchArray[2]; - result.push({ descriptor, message, position: matchPosition }); + result.push({ + descriptor, + message, + position: matchPosition + }); } } return result; @@ -143692,7 +128912,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} const multiLineCommentStart = /(?:\/\*+\s*)/.source; const anyNumberOfSpacesAndAsterisksAtStartOfLine = /(?:^(?:\s|\*)*)/.source; const preamble = "(" + anyNumberOfSpacesAndAsterisksAtStartOfLine + "|" + singleLineCommentStart + "|" + multiLineCommentStart + ")"; - const literals = "(?:" + map(descriptors, (d) => "(" + escapeRegExp(d.text) + ")").join("|") + ")"; + const literals = "(?:" + map(descriptors, d => "(" + escapeRegExp(d.text) + ")").join("|") + ")"; const endOfLineOrEndOfComment = /(?:$|\*\/)/.source; const messageRemainder = /(?:.*?)/.source; const messagePortion = "(" + literals + messageRemainder + ")"; @@ -143702,6 +128922,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} function isLetterOrDigit(char) { return char >= 97 /* a */ && char <= 122 /* z */ || char >= 65 /* A */ && char <= 90 /* Z */ || char >= 48 /* _0 */ && char <= 57 /* _9 */; } + function isNodeModulesFile(path) { return path.includes("/node_modules/"); } @@ -143749,9 +128970,12 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} const sourceFile = getValidSourceFile(fileName); const allFiles = Debug.checkDefined(program.getSourceFiles()); const extension = extensionFromPath(fileName); - const files = mapDefined(allFiles, (file) => !(program == null ? void 0 : program.isSourceFileFromExternalLibrary(sourceFile)) && !(sourceFile === getValidSourceFile(file.fileName) || extension === ".ts" /* Ts */ && extensionFromPath(file.fileName) === ".d.ts" /* Dts */ || extension === ".d.ts" /* Dts */ && startsWith(getBaseFileName(file.fileName), "lib.") && extensionFromPath(file.fileName) === ".d.ts" /* Dts */) && extension === extensionFromPath(file.fileName) ? file.fileName : void 0); + const files = mapDefined(allFiles, file => !(program == null ? void 0 : program.isSourceFileFromExternalLibrary(sourceFile)) && !(sourceFile === getValidSourceFile(file.fileName) || extension === ".ts" /* Ts */ && extensionFromPath(file.fileName) === ".d.ts" /* Dts */ || extension === ".d.ts" /* Dts */ && startsWith(getBaseFileName(file.fileName), "lib.") && extensionFromPath(file.fileName) === ".d.ts" /* Dts */) && extension === extensionFromPath(file.fileName) ? file.fileName : void 0); const newFileName = createNewFileName(sourceFile, program, getRefactorContext(sourceFile, positionOrRange, preferences, emptyOptions), host); - return { newFileName, files }; + return { + newFileName, + files + }; } function getEditsForRefactor2(fileName, formatOptions, positionOrRange, refactorName14, actionName2, preferences = emptyOptions, interactiveRefactorArguments) { synchronizeHostData(); @@ -143760,14 +128984,17 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } function toLineColumnOffset(fileName, position) { if (position === 0) { - return { line: 0, character: 0 }; + return { + line: 0, + character: 0 + }; } return sourceMapper.toLineColumnOffset(fileName, position); } function prepareCallHierarchy(fileName, position) { synchronizeHostData(); const declarations = ts_CallHierarchy_exports.resolveCallHierarchyDeclaration(program, getTouchingPropertyName(getValidSourceFile(fileName), position)); - return declarations && mapOneOrMany(declarations, (declaration) => ts_CallHierarchy_exports.createCallHierarchyItem(program, declaration)); + return declarations && mapOneOrMany(declarations, declaration => ts_CallHierarchy_exports.createCallHierarchyItem(program, declaration)); } function provideCallHierarchyIncomingCalls(fileName, position) { synchronizeHostData(); @@ -143861,18 +129088,14 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} case 0 /* Semantic */: break; case 1 /* PartialSemantic */: - invalidOperationsInPartialSemanticMode.forEach( - (key) => ls[key] = () => { - throw new Error(`LanguageService Operation: ${key} not allowed in LanguageServiceMode.PartialSemantic`); - } - ); + invalidOperationsInPartialSemanticMode.forEach(key => ls[key] = () => { + throw new Error(`LanguageService Operation: ${key} not allowed in LanguageServiceMode.PartialSemantic`); + }); break; case 2 /* Syntactic */: - invalidOperationsInSyntacticMode.forEach( - (key) => ls[key] = () => { - throw new Error(`LanguageService Operation: ${key} not allowed in LanguageServiceMode.Syntactic`); - } - ); + invalidOperationsInSyntacticMode.forEach(key => ls[key] = () => { + throw new Error(`LanguageService Operation: ${key} not allowed in LanguageServiceMode.Syntactic`); + }); break; default: Debug.assertNever(languageServiceMode); @@ -143886,7 +129109,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return sourceFile.nameTable; } function initializeNameTable(sourceFile) { - const nameTable = sourceFile.nameTable = /* @__PURE__ */ new Map(); + const nameTable = sourceFile.nameTable = /* @__PURE__ */new Map(); sourceFile.forEachChild(function walk(node) { if (isIdentifier(node) && !isTagName(node) && node.escapedText || isStringOrNumericLiteralLike(node) && literalIsName(node)) { const text = getEscapedTextOfIdentifierOrLiteral(node); @@ -143927,13 +129150,8 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} const object = getContainingObjectLiteralElement(node); if (object) { const contextualType = checker.getContextualType(object.parent); - const properties = contextualType && getPropertySymbolsFromContextualType( - object, - checker, - contextualType, - /*unionSymbolOk*/ - false - ); + const properties = contextualType && getPropertySymbolsFromContextualType(object, checker, contextualType, /*unionSymbolOk*/ + false); if (properties && properties.length === 1) { return first(properties); } @@ -143942,20 +129160,18 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } 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; } - const discriminatedPropertySymbols = mapDefined(contextualType.types, (t) => (isObjectLiteralExpression(node.parent) || isJsxAttributes(node.parent)) && checker.isTypeInvalidDueToUnionDiscriminant(t, node.parent) ? void 0 : t.getProperty(name)); + const discriminatedPropertySymbols = mapDefined(contextualType.types, t => (isObjectLiteralExpression(node.parent) || isJsxAttributes(node.parent)) && checker.isTypeInvalidDueToUnionDiscriminant(t, node.parent) ? void 0 : t.getProperty(name)); if (unionSymbolOk && (discriminatedPropertySymbols.length === 0 || discriminatedPropertySymbols.length === contextualType.types.length)) { const symbol = contextualType.getProperty(name); - if (symbol) - return [symbol]; + if (symbol) return [symbol]; } if (discriminatedPropertySymbols.length === 0) { - return mapDefined(contextualType.types, (t) => t.getProperty(name)); + return mapDefined(contextualType.types, t => t.getProperty(name)); } return discriminatedPropertySymbols; } @@ -143972,6 +129188,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} var init_services = __esm({ "src/services/services.ts"() { "use strict"; + init_ts4(); init_ts_NavigateTo(); init_ts_NavigationBar(); @@ -144046,7 +129263,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (!children.length) { return void 0; } - const child = find(children, (kid) => kid.kind < 316 /* FirstJSDocNode */ || kid.kind > 357 /* LastJSDocNode */); + const child = find(children, kid => kid.kind < 316 /* FirstJSDocNode */ || kid.kind > 357 /* LastJSDocNode */); return child.kind < 166 /* FirstNode */ ? child : child.getFirstToken(sourceFile); } getLastToken(sourceFile) { @@ -144214,6 +129431,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} super(pos, end); this.kind = 80 /* Identifier */; } + get text() { return idText(this); } @@ -144224,6 +129442,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} super(pos, end); this.kind = 81 /* PrivateIdentifier */; } + get text() { return idText(this); } @@ -144252,15 +129471,19 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} getCallSignatures() { return this.checker.getSignaturesOfType(this, 0 /* Call */); } + getConstructSignatures() { return this.checker.getSignaturesOfType(this, 1 /* Construct */); } + getStringIndexType() { return this.checker.getIndexTypeOfType(this, 0 /* String */); } + getNumberIndexType() { return this.checker.getIndexTypeOfType(this, 1 /* Number */); } + getBaseTypes() { return this.isClassOrInterface() ? this.checker.getBaseTypes(this) : void 0; } @@ -144282,30 +129505,39 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} isUnion() { return !!(this.flags & 1048576 /* Union */); } + isIntersection() { return !!(this.flags & 2097152 /* Intersection */); } + isUnionOrIntersection() { return !!(this.flags & 3145728 /* UnionOrIntersection */); } + isLiteral() { return !!(this.flags & (128 /* StringLiteral */ | 256 /* NumberLiteral */ | 2048 /* BigIntLiteral */)); } + isStringLiteral() { return !!(this.flags & 128 /* StringLiteral */); } + isNumberLiteral() { return !!(this.flags & 256 /* NumberLiteral */); } + isTypeParameter() { return !!(this.flags & 262144 /* TypeParameter */); } + isClassOrInterface() { return !!(getObjectFlags(this) & 3 /* ClassOrInterface */); } + isClass() { return !!(getObjectFlags(this) & 1 /* Class */); } + isIndexType() { return !!(this.flags & 4194304 /* Index */); } @@ -144359,6 +129591,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} super(kind, pos, end); this.kind = 312 /* SourceFile */; } + update(newText, textChangeRange) { return updateSourceFile(this, newText, textChangeRange); } @@ -144372,7 +129605,9 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return computePositionOfLineAndCharacter(getLineStarts(this), line, character, this.text, allowEdits); } getLineEndOfPosition(pos) { - const { line } = this.getLineAndCharacterOfPosition(pos); + const { + line + } = this.getLineAndCharacterOfPosition(pos); const lineStarts = this.getLineStarts(); let lastCharPos; if (line + 1 >= lineStarts.length) { @@ -144454,16 +129689,17 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} break; } case 260 /* VariableDeclaration */: - case 208 /* BindingElement */: { - const decl = node; - if (isBindingPattern(decl.name)) { - forEachChild(decl.name, visit); - break; + case 208 /* BindingElement */: + { + const decl = node; + if (isBindingPattern(decl.name)) { + forEachChild(decl.name, visit); + break; + } + if (decl.initializer) { + visit(decl.initializer); + } } - if (decl.initializer) { - visit(decl.initializer); - } - } case 306 /* EnumMember */: case 172 /* PropertyDeclaration */: case 171 /* PropertySignature */: @@ -144530,25 +129766,14 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (this.currentFileName !== fileName) { const options = { languageVersion: 99 /* Latest */, - impliedNodeFormat: getImpliedNodeFormatForFile( - toPath(fileName, this.host.getCurrentDirectory(), ((_c = (_b = (_a = this.host).getCompilerHost) == null ? void 0 : _b.call(_a)) == null ? void 0 : _c.getCanonicalFileName) || hostGetCanonicalFileName(this.host)), - (_h = (_g = (_f = (_e = (_d = this.host).getCompilerHost) == null ? void 0 : _e.call(_d)) == null ? void 0 : _f.getModuleResolutionCache) == null ? void 0 : _g.call(_f)) == null ? void 0 : _h.getPackageJsonInfoCache(), - this.host, - this.host.getCompilationSettings() - ), + impliedNodeFormat: getImpliedNodeFormatForFile(toPath(fileName, this.host.getCurrentDirectory(), ((_c = (_b = (_a = this.host).getCompilerHost) == null ? void 0 : _b.call(_a)) == null ? void 0 : _c.getCanonicalFileName) || hostGetCanonicalFileName(this.host)), (_h = (_g = (_f = (_e = (_d = this.host).getCompilerHost) == null ? void 0 : _e.call(_d)) == null ? void 0 : _f.getModuleResolutionCache) == null ? void 0 : _g.call(_f)) == null ? void 0 : _h.getPackageJsonInfoCache(), this.host, this.host.getCompilationSettings()), setExternalModuleIndicator: getSetExternalModuleIndicator(this.host.getCompilationSettings()), // These files are used to produce syntax-based highlighting, which reads JSDoc, so we must use ParseAll. jsDocParsingMode: 0 /* ParseAll */ }; - sourceFile = createLanguageServiceSourceFile( - fileName, - scriptSnapshot, - options, - version2, - /*setNodeParents*/ - true, - scriptKind - ); + + sourceFile = createLanguageServiceSourceFile(fileName, scriptSnapshot, options, version2, /*setNodeParents*/ + true, scriptKind); } else if (this.currentFileVersion !== version2) { const editRange = scriptSnapshot.getChangeRange(this.currentFileScriptSnapshot); sourceFile = updateLanguageServiceSourceFile(this.currentSourceFile, scriptSnapshot, version2, editRange); @@ -144576,7 +129801,9 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} throwIfCancellationRequested() { var _a; if (this.isCancellationRequested()) { - (_a = tracing) == null ? void 0 : _a.instant(tracing.Phase.Session, "cancellationThrown", { kind: "CancellationTokenObject" }); + (_a = tracing) == null ? void 0 : _a.instant(tracing.Phase.Session, "cancellationThrown", { + kind: "CancellationTokenObject" + }); throw new OperationCanceledException(); } } @@ -144602,50 +129829,15 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} throwIfCancellationRequested() { var _a; if (this.isCancellationRequested()) { - (_a = tracing) == null ? void 0 : _a.instant(tracing.Phase.Session, "cancellationThrown", { kind: "ThrottledCancellationToken" }); + (_a = tracing) == null ? void 0 : _a.instant(tracing.Phase.Session, "cancellationThrown", { + kind: "ThrottledCancellationToken" + }); throw new OperationCanceledException(); } } }; - invalidOperationsInPartialSemanticMode = [ - "getSemanticDiagnostics", - "getSuggestionDiagnostics", - "getCompilerOptionsDiagnostics", - "getSemanticClassifications", - "getEncodedSemanticClassifications", - "getCodeFixesAtPosition", - "getCombinedCodeFix", - "applyCodeActionCommand", - "organizeImports", - "getEditsForFileRename", - "getEmitOutput", - "getApplicableRefactors", - "getEditsForRefactor", - "prepareCallHierarchy", - "provideCallHierarchyIncomingCalls", - "provideCallHierarchyOutgoingCalls", - "provideInlayHints", - "getSupportedCodeFixes" - ]; - invalidOperationsInSyntacticMode = [ - ...invalidOperationsInPartialSemanticMode, - "getCompletionsAtPosition", - "getCompletionEntryDetails", - "getCompletionEntrySymbol", - "getSignatureHelpItems", - "getQuickInfoAtPosition", - "getDefinitionAtPosition", - "getDefinitionAndBoundSpan", - "getImplementationAtPosition", - "getTypeDefinitionAtPosition", - "getReferencesAtPosition", - "findReferences", - "getDocumentHighlights", - "getNavigateToItems", - "getRenameInfo", - "findRenameLocations", - "getApplicableRefactors" - ]; + invalidOperationsInPartialSemanticMode = ["getSemanticDiagnostics", "getSuggestionDiagnostics", "getCompilerOptionsDiagnostics", "getSemanticClassifications", "getEncodedSemanticClassifications", "getCodeFixesAtPosition", "getCombinedCodeFix", "applyCodeActionCommand", "organizeImports", "getEditsForFileRename", "getEmitOutput", "getApplicableRefactors", "getEditsForRefactor", "prepareCallHierarchy", "provideCallHierarchyIncomingCalls", "provideCallHierarchyOutgoingCalls", "provideInlayHints", "getSupportedCodeFixes"]; + invalidOperationsInSyntacticMode = [...invalidOperationsInPartialSemanticMode, "getCompletionsAtPosition", "getCompletionEntryDetails", "getCompletionEntrySymbol", "getSignatureHelpItems", "getQuickInfoAtPosition", "getDefinitionAtPosition", "getDefinitionAndBoundSpan", "getImplementationAtPosition", "getTypeDefinitionAtPosition", "getReferencesAtPosition", "findReferences", "getDocumentHighlights", "getNavigateToItems", "getRenameInfo", "findRenameLocations", "getApplicableRefactors"]; setObjectAllocator(getServicesObjectAllocator()); } }); @@ -144655,24 +129847,17 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} const diagnostics = []; compilerOptions = fixupCompilerOptions(compilerOptions, diagnostics); const nodes = isArray(source) ? source : [source]; - const result = transformNodes( - /*resolver*/ - void 0, - /*host*/ - void 0, - factory, - compilerOptions, - nodes, - transformers, - /*allowDtsFiles*/ - true - ); + const result = transformNodes( /*resolver*/ + void 0, /*host*/ + void 0, factory, compilerOptions, nodes, transformers, /*allowDtsFiles*/ + true); result.diagnostics = concatenate(result.diagnostics, diagnostics); return result; } var init_transform = __esm({ "src/services/transform.ts"() { "use strict"; + init_ts4(); } }); @@ -144715,10 +129900,8 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} 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); } } @@ -144732,7 +129915,9 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } function spanInNode(node) { if (node) { - const { parent: parent2 } = node; + const { + parent: parent2 + } = node; switch (node.kind) { case 243 /* VariableStatement */: return spanInVariableDeclaration(node.declarationList.declarations[0]); @@ -144854,11 +130039,12 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return textSpan(node); } if (node.kind === 226 /* BinaryExpression */) { - const { left, operatorToken } = node; + const { + left, + operatorToken + } = node; if (isArrayLiteralOrObjectLiteralDestructuringPattern(left)) { - return spanInArrayLiteralOrObjectLiteralDestructuringPattern( - left - ); + return spanInArrayLiteralOrObjectLiteralDestructuringPattern(left); } if (operatorToken.kind === 64 /* EqualsToken */ && isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent)) { return textSpan(node); @@ -144900,20 +130086,27 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } break; case 260 /* VariableDeclaration */: - case 169 /* Parameter */: { - const { initializer, type } = node.parent; - if (initializer === node || type === node || isAssignmentOperator(node.kind)) { - return spanInPreviousNode(node); + case 169 /* Parameter */: + { + const { + initializer, + type + } = node.parent; + if (initializer === node || type === node || isAssignmentOperator(node.kind)) { + return spanInPreviousNode(node); + } + break; } - break; - } - case 226 /* BinaryExpression */: { - const { left } = node.parent; - if (isArrayLiteralOrObjectLiteralDestructuringPattern(left) && node !== left) { - return spanInPreviousNode(node); + case 226 /* BinaryExpression */: + { + const { + left + } = node.parent; + if (isArrayLiteralOrObjectLiteralDestructuringPattern(left) && node !== left) { + return spanInPreviousNode(node); + } + break; } - break; - } default: if (isFunctionLike(node.parent) && node.parent.type === node) { return spanInPreviousNode(node); @@ -144947,6 +130140,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} function canHaveSpanInParameterDeclaration(parameter) { return !!parameter.initializer || parameter.dotDotDotToken !== void 0 || hasSyntacticModifier(parameter, 1 /* Public */ | 2 /* Private */); } + function spanInParameterDeclaration(parameter) { if (isBindingPattern(parameter.name)) { return spanInBindingPattern(parameter.name); @@ -144966,6 +130160,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} function canFunctionHaveSpanInWholeDeclaration(functionDeclaration) { return hasSyntacticModifier(functionDeclaration, 32 /* Export */) || functionDeclaration.parent.kind === 263 /* ClassDeclaration */ && functionDeclaration.kind !== 176 /* Constructor */; } + function spanInFunctionDeclaration(functionDeclaration) { if (!functionDeclaration.body) { return void 0; @@ -145020,7 +130215,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } } function spanInBindingPattern(bindingPattern) { - const firstBindingElement = forEach(bindingPattern.elements, (element) => element.kind !== 232 /* OmittedExpression */ ? element : void 0); + const firstBindingElement = forEach(bindingPattern.elements, element => element.kind !== 232 /* OmittedExpression */ ? element : void 0); if (firstBindingElement) { return spanInNode(firstBindingElement); } @@ -145032,7 +130227,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} function spanInArrayLiteralOrObjectLiteralDestructuringPattern(node2) { Debug.assert(node2.kind !== 207 /* ArrayBindingPattern */ && node2.kind !== 206 /* ObjectBindingPattern */); const elements = node2.kind === 209 /* ArrayLiteralExpression */ ? node2.elements : node2.properties; - const firstBindingElement = forEach(elements, (element) => element.kind !== 232 /* OmittedExpression */ ? element : void 0); + const firstBindingElement = forEach(elements, element => element.kind !== 232 /* OmittedExpression */ ? element : void 0); if (firstBindingElement) { return spanInNode(firstBindingElement); } @@ -145098,7 +130293,8 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } } function spanInOpenParenToken(node2) { - if (node2.parent.kind === 246 /* DoStatement */ || // Go to while keyword and do action instead + if (node2.parent.kind === 246 /* DoStatement */ || + // Go to while keyword and do action instead node2.parent.kind === 213 /* CallExpression */ || node2.parent.kind === 214 /* NewExpression */) { return spanInPreviousNode(node2); } @@ -145158,6 +130354,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} var init_breakpoints = __esm({ "src/services/breakpoints.ts"() { "use strict"; + init_ts4(); } }); @@ -145170,6 +130367,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} var init_ts_BreakpointResolver = __esm({ "src/services/_namespaces/ts.BreakpointResolver.ts"() { "use strict"; + init_breakpoints(); } }); @@ -145181,6 +130379,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} function isConstNamedExpression(node) { return (isFunctionExpression(node) || isArrowFunction(node) || isClassExpression(node)) && isVariableDeclaration(node.parent) && node === node.parent.initializer && isIdentifier(node.parent.name) && !!(getCombinedNodeFlags(node.parent) & 2 /* Const */); } + function isPossibleCallHierarchyDeclaration(node) { return isSourceFile(node) || isModuleDeclaration(node) || isFunctionDeclaration(node) || isFunctionExpression(node) || isClassDeclaration(node) || isClassExpression(node) || isClassStaticBlockDeclaration(node) || isMethodDeclaration(node) || isMethodSignature(node) || isGetAccessorDeclaration(node) || isSetAccessorDeclaration(node); } @@ -145188,29 +130387,35 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return isSourceFile(node) || isModuleDeclaration(node) && isIdentifier(node.name) || isFunctionDeclaration(node) || isClassDeclaration(node) || isClassStaticBlockDeclaration(node) || isMethodDeclaration(node) || isMethodSignature(node) || isGetAccessorDeclaration(node) || isSetAccessorDeclaration(node) || isNamedExpression(node) || isConstNamedExpression(node); } function getCallHierarchyDeclarationReferenceNode(node) { - if (isSourceFile(node)) - return node; - if (isNamedDeclaration(node)) - return node.name; - if (isConstNamedExpression(node)) - return node.parent.name; + if (isSourceFile(node)) return node; + if (isNamedDeclaration(node)) return node.name; + if (isConstNamedExpression(node)) return node.parent.name; return Debug.checkDefined(node.modifiers && find(node.modifiers, isDefaultModifier3)); } function isDefaultModifier3(node) { return node.kind === 90 /* DefaultKeyword */; } + function getSymbolOfCallHierarchyDeclaration(typeChecker, node) { const location = getCallHierarchyDeclarationReferenceNode(node); return location && typeChecker.getSymbolAtLocation(location); } function getCallHierarchyItemName(program, node) { if (isSourceFile(node)) { - return { text: node.fileName, pos: 0, end: 0 }; + return { + text: node.fileName, + pos: 0, + end: 0 + }; } if ((isFunctionDeclaration(node) || isClassDeclaration(node)) && !isNamedDeclaration(node)) { const defaultModifier = node.modifiers && find(node.modifiers, isDefaultModifier3); if (defaultModifier) { - return { text: "default", pos: defaultModifier.getStart(), end: defaultModifier.getEnd() }; + return { + text: "default", + pos: defaultModifier.getStart(), + end: defaultModifier.getEnd() + }; } } if (isClassStaticBlockDeclaration(node)) { @@ -145220,7 +130425,11 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} const typeChecker = program.getTypeChecker(); const symbol = typeChecker.getSymbolAtLocation(node.parent); const prefix = symbol ? `${typeChecker.symbolToString(symbol, node.parent)} ` : ""; - return { text: `${prefix}static {}`, pos, end }; + return { + text: `${prefix}static {}`, + pos, + end + }; } const declName = isConstNamedExpression(node) ? node.parent.name : Debug.checkDefined(getNameOfDeclaration(node), "Expected call hierarchy item to have a name"); let text = isIdentifier(declName) ? idText(declName) : isStringOrNumericLiteralLike(declName) ? declName.text : isComputedPropertyName(declName) ? isStringOrNumericLiteralLike(declName.expression) ? declName.expression.text : void 0 : void 0; @@ -145233,9 +130442,13 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } if (text === void 0) { const printer = createPrinterWithRemoveCommentsOmitTrailingSemicolon(); - text = usingSingleLineStringWriter((writer) => printer.writeNode(4 /* Unspecified */, node, node.getSourceFile(), writer)); + text = usingSingleLineStringWriter(writer => printer.writeNode(4 /* Unspecified */, node, node.getSourceFile(), writer)); } - return { text, pos: declName.getStart(), end: declName.getEnd() }; + return { + text, + pos: declName.getStart(), + end: declName.getEnd() + }; } function getCallHierarchItemContainerName(node) { var _a, _b; @@ -145282,9 +130495,12 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} let declarations; if (symbol && symbol.declarations) { const indices = indicesOf(symbol.declarations); - const keys = map(symbol.declarations, (decl) => ({ file: decl.getSourceFile().fileName, pos: decl.pos })); + const keys = map(symbol.declarations, decl => ({ + file: decl.getSourceFile().fileName, + pos: decl.pos + })); indices.sort((a, b) => compareStringsCaseSensitive(keys[a].file, keys[b].file) || keys[a].pos - keys[b].pos); - const sortedDeclarations = map(indices, (i) => symbol.declarations[i]); + const sortedDeclarations = map(indices, i => symbol.declarations[i]); let lastDecl; for (const decl of sortedDeclarations) { if (isValidCallHierarchyDeclaration(decl)) { @@ -145298,13 +130514,15 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return declarations; } function findImplementationOrAllInitialDeclarations(typeChecker, node) { + var _findAllInitialDeclar; if (isClassStaticBlockDeclaration(node)) { return node; } if (isFunctionLikeDeclaration(node)) { - return findImplementation(typeChecker, node) ?? findAllInitialDeclarations(typeChecker, node) ?? node; + var _ref42, _findImplementation; + return (_ref42 = (_findImplementation = findImplementation(typeChecker, node)) !== null && _findImplementation !== void 0 ? _findImplementation : findAllInitialDeclarations(typeChecker, node)) !== null && _ref42 !== void 0 ? _ref42 : node; } - return findAllInitialDeclarations(typeChecker, node) ?? node; + return (_findAllInitialDeclar = findAllInitialDeclarations(typeChecker, node)) !== null && _findAllInitialDeclar !== void 0 ? _findAllInitialDeclar : node; } function resolveCallHierarchyDeclaration(program, location) { const typeChecker = program.getTypeChecker(); @@ -145365,51 +130583,43 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} const containerName = getCallHierarchItemContainerName(node); const kind = getNodeKind(node); const kindModifiers = getNodeModifiers(node); - const span = createTextSpanFromBounds(skipTrivia( - sourceFile.text, - node.getFullStart(), - /*stopAfterLineBreak*/ - false, - /*stopAtComments*/ - true - ), node.getEnd()); + const span = createTextSpanFromBounds(skipTrivia(sourceFile.text, node.getFullStart(), /*stopAfterLineBreak*/ + false, /*stopAtComments*/ + true), node.getEnd()); const selectionSpan = createTextSpanFromBounds(name.pos, name.end); - return { file: sourceFile.fileName, kind, kindModifiers, name: name.text, containerName, span, selectionSpan }; + return { + file: sourceFile.fileName, + kind, + kindModifiers, + name: name.text, + containerName, + span, + selectionSpan + }; } function isDefined(x) { return x !== void 0; } function convertEntryToCallSite(entry) { if (entry.kind === ts_FindAllReferences_exports.EntryKind.Node) { - const { node } = entry; - if (isCallOrNewExpressionTarget( - node, - /*includeElementAccess*/ - true, - /*skipPastOuterExpressions*/ - true - ) || isTaggedTemplateTag( - node, - /*includeElementAccess*/ - true, - /*skipPastOuterExpressions*/ - true - ) || isDecoratorTarget( - node, - /*includeElementAccess*/ - true, - /*skipPastOuterExpressions*/ - true - ) || isJsxOpeningLikeElementTagName( - node, - /*includeElementAccess*/ - true, - /*skipPastOuterExpressions*/ - true - ) || isRightSideOfPropertyAccess(node) || isArgumentExpressionOfElementAccess(node)) { + const { + node + } = entry; + if (isCallOrNewExpressionTarget(node, /*includeElementAccess*/ + true, /*skipPastOuterExpressions*/ + true) || isTaggedTemplateTag(node, /*includeElementAccess*/ + true, /*skipPastOuterExpressions*/ + true) || isDecoratorTarget(node, /*includeElementAccess*/ + true, /*skipPastOuterExpressions*/ + true) || isJsxOpeningLikeElementTagName(node, /*includeElementAccess*/ + true, /*skipPastOuterExpressions*/ + true) || isRightSideOfPropertyAccess(node) || isArgumentExpressionOfElementAccess(node)) { const sourceFile = node.getSourceFile(); const ancestor = findAncestor(node, isValidCallHierarchyDeclaration) || sourceFile; - return { declaration: ancestor, range: createTextRangeFromNode(node, sourceFile) }; + return { + declaration: ancestor, + range: createTextRangeFromNode(node, sourceFile) + }; } } } @@ -145417,27 +130627,24 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return getNodeId(entry.declaration); } function createCallHierarchyIncomingCall(from, fromSpans) { - return { from, fromSpans }; + return { + from, + fromSpans + }; } function convertCallSiteGroupToIncomingCall(program, entries) { - return createCallHierarchyIncomingCall(createCallHierarchyItem(program, entries[0].declaration), map(entries, (entry) => createTextSpanFromRange(entry.range))); + return createCallHierarchyIncomingCall(createCallHierarchyItem(program, entries[0].declaration), map(entries, entry => createTextSpanFromRange(entry.range))); } function getIncomingCalls(program, declaration, cancellationToken) { if (isSourceFile(declaration) || isModuleDeclaration(declaration) || isClassStaticBlockDeclaration(declaration)) { return []; } const location = getCallHierarchyDeclarationReferenceNode(declaration); - const calls = filter(ts_FindAllReferences_exports.findReferenceOrRenameEntries( - program, - cancellationToken, - program.getSourceFiles(), - location, - /*position*/ - 0, - { use: ts_FindAllReferences_exports.FindReferencesUse.References }, - convertEntryToCallSite - ), isDefined); - return calls ? group(calls, getCallSiteGroupKey, (entries) => convertCallSiteGroupToIncomingCall(program, entries)) : []; + const calls = filter(ts_FindAllReferences_exports.findReferenceOrRenameEntries(program, cancellationToken, program.getSourceFiles(), location, /*position*/ + 0, { + use: ts_FindAllReferences_exports.FindReferencesUse.References + }, convertEntryToCallSite), isDefined); + return calls ? group(calls, getCallSiteGroupKey, entries => convertCallSiteGroupToIncomingCall(program, entries)) : []; } function createCallSiteCollector(program, callSites) { function recordCallSite(node) { @@ -145447,16 +130654,21 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} const range = createTextRangeFromNode(target, node.getSourceFile()); if (isArray(declaration)) { for (const decl of declaration) { - callSites.push({ declaration: decl, range }); + callSites.push({ + declaration: decl, + range + }); } } else { - callSites.push({ declaration, range }); + callSites.push({ + declaration, + range + }); } } } function collect(node) { - if (!node) - return; + if (!node) return; if (node.flags & 33554432 /* Ambient */) { return; } @@ -145600,20 +130812,24 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return callSites; } function createCallHierarchyOutgoingCall(to, fromSpans) { - return { to, fromSpans }; + return { + to, + fromSpans + }; } function convertCallSiteGroupToOutgoingCall(program, entries) { - return createCallHierarchyOutgoingCall(createCallHierarchyItem(program, entries[0].declaration), map(entries, (entry) => createTextSpanFromRange(entry.range))); + return createCallHierarchyOutgoingCall(createCallHierarchyItem(program, entries[0].declaration), map(entries, entry => createTextSpanFromRange(entry.range))); } function getOutgoingCalls(program, declaration) { if (declaration.flags & 33554432 /* Ambient */ || isMethodSignature(declaration)) { return []; } - return group(collectCallSites(program, declaration), getCallSiteGroupKey, (entries) => convertCallSiteGroupToOutgoingCall(program, entries)); + return group(collectCallSites(program, declaration), getCallSiteGroupKey, entries => convertCallSiteGroupToOutgoingCall(program, entries)); } var init_callHierarchy = __esm({ "src/services/callHierarchy.ts"() { "use strict"; + init_ts4(); } }); @@ -145629,6 +130845,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} var init_ts_CallHierarchy = __esm({ "src/services/_namespaces/ts.CallHierarchy.ts"() { "use strict"; + init_callHierarchy(); } }); @@ -145645,6 +130862,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} var init_ts_classifier_v2020 = __esm({ "src/services/_namespaces/ts.classifier.v2020.ts"() { "use strict"; + init_classifier2020(); } }); @@ -145657,21 +130875,16 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} var init_ts_classifier = __esm({ "src/services/_namespaces/ts.classifier.ts"() { "use strict"; + init_ts_classifier_v2020(); } }); // src/services/codeFixProvider.ts function createCodeFixActionWithoutFixAll(fixName8, changes, description3) { - return createCodeFixActionWorker( - fixName8, - diagnosticToString(description3), - changes, - /*fixId*/ - void 0, - /*fixAllDescription*/ - void 0 - ); + return createCodeFixActionWorker(fixName8, diagnosticToString(description3), changes, /*fixId*/ + void 0, /*fixAllDescription*/ + void 0); } function createCodeFixAction(fixName8, changes, description3, fixId52, fixAllDescription, command) { return createCodeFixActionWorker(fixName8, diagnosticToString(description3), changes, fixId52, diagnosticToString(fixAllDescription), command); @@ -145680,7 +130893,14 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return createCodeFixActionWorker(fixName8, diagnosticToString(description3), changes, fixId52, fixAllDescription && diagnosticToString(fixAllDescription), command); } function createCodeFixActionWorker(fixName8, description3, changes, fixId52, fixAllDescription, command) { - return { fixName: fixName8, description: description3, changes, fixId: fixId52, fixAllDescription, commands: command ? [command] : void 0 }; + return { + fixName: fixName8, + description: description3, + changes, + fixId: fixId52, + fixAllDescription, + commands: command ? [command] : void 0 + }; } function registerCodeFix(reg) { for (const error2 of reg.errorCodes) { @@ -145695,39 +130915,54 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } } function getSupportedErrorCodes() { - return errorCodeToFixesArray ?? (errorCodeToFixesArray = arrayFrom(errorCodeToFixes.keys())); + var _errorCodeToFixesArra; + return (_errorCodeToFixesArra = errorCodeToFixesArray) !== null && _errorCodeToFixesArra !== void 0 ? _errorCodeToFixesArra : errorCodeToFixesArray = arrayFrom(errorCodeToFixes.keys()); } function removeFixIdIfFixAllUnavailable(registration, diagnostics) { - const { errorCodes: errorCodes64 } = registration; + const { + errorCodes: errorCodes64 + } = registration; let maybeFixableDiagnostics = 0; for (const diag2 of diagnostics) { - if (contains(errorCodes64, diag2.code)) - maybeFixableDiagnostics++; - if (maybeFixableDiagnostics > 1) - break; + if (contains(errorCodes64, diag2.code)) maybeFixableDiagnostics++; + if (maybeFixableDiagnostics > 1) break; } const fixAllUnavailable = maybeFixableDiagnostics < 2; - return ({ fixId: fixId52, fixAllDescription, ...action }) => { - return fixAllUnavailable ? action : { ...action, fixId: fixId52, fixAllDescription }; + return ({ + fixId: fixId52, + fixAllDescription, + ...action + }) => { + return fixAllUnavailable ? action : { + ...action, + fixId: fixId52, + fixAllDescription + }; }; } function getFixes(context) { const diagnostics = getDiagnostics(context); const registrations = errorCodeToFixes.get(String(context.errorCode)); - return flatMap(registrations, (f) => map(f.getCodeActions(context), removeFixIdIfFixAllUnavailable(f, diagnostics))); + return flatMap(registrations, f => map(f.getCodeActions(context), removeFixIdIfFixAllUnavailable(f, diagnostics))); } function getAllFixes(context) { return fixIdToRegistration.get(cast(context.fixId, isString)).getAllCodeActions(context); } function createCombinedCodeActions(changes, commands) { - return { changes, commands }; + return { + changes, + commands + }; } function createFileTextChanges(fileName, textChanges2) { - return { fileName, textChanges: textChanges2 }; + return { + fileName, + textChanges: textChanges2 + }; } function codeFixAll(context, errorCodes64, use) { const commands = []; - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => eachDiagnostic(context, errorCodes64, (diag2) => use(t, diag2, commands))); + const changes = ts_textChanges_exports.ChangeTracker.with(context, t => eachDiagnostic(context, errorCodes64, diag2 => use(t, diag2, commands))); return createCombinedCodeActions(changes, commands.length === 0 ? void 0 : commands); } function eachDiagnostic(context, errorCodes64, cb) { @@ -145737,20 +130972,21 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } } } - function getDiagnostics({ program, sourceFile, cancellationToken }) { - return [ - ...program.getSemanticDiagnostics(sourceFile, cancellationToken), - ...program.getSyntacticDiagnostics(sourceFile, cancellationToken), - ...computeSuggestionDiagnostics(sourceFile, program, cancellationToken) - ]; + function getDiagnostics({ + program, + sourceFile, + cancellationToken + }) { + return [...program.getSemanticDiagnostics(sourceFile, cancellationToken), ...program.getSyntacticDiagnostics(sourceFile, cancellationToken), ...computeSuggestionDiagnostics(sourceFile, program, cancellationToken)]; } var errorCodeToFixes, fixIdToRegistration, errorCodeToFixesArray; var init_codeFixProvider = __esm({ "src/services/codeFixProvider.ts"() { "use strict"; + init_ts4(); errorCodeToFixes = createMultiMap(); - fixIdToRegistration = /* @__PURE__ */ new Map(); + fixIdToRegistration = /* @__PURE__ */new Map(); } }); @@ -145760,14 +130996,14 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} changeTracker.replaceNode(sourceFile, assertion.expression, replacement); } function getAssertion(sourceFile, pos) { - if (isInJSFile(sourceFile)) - return void 0; - return findAncestor(getTokenAtPosition(sourceFile, pos), (n) => isAsExpression(n) || isTypeAssertionExpression(n)); + if (isInJSFile(sourceFile)) return void 0; + return findAncestor(getTokenAtPosition(sourceFile, pos), n => isAsExpression(n) || isTypeAssertionExpression(n)); } var fixId, errorCodes; var init_addConvertToUnknownForNonOverlappingTypes = __esm({ "src/services/codefixes/addConvertToUnknownForNonOverlappingTypes.ts"() { "use strict"; + init_ts4(); init_ts_codefix(); fixId = "addConvertToUnknownForNonOverlappingTypes"; @@ -145776,13 +131012,12 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} errorCodes, getCodeActions: function getCodeActionsToAddConvertToUnknownForNonOverlappingTypes(context) { const assertion = getAssertion(context.sourceFile, context.span.start); - if (assertion === void 0) - return void 0; - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => makeChange(t, context.sourceFile, assertion)); + if (assertion === void 0) return void 0; + const changes = ts_textChanges_exports.ChangeTracker.with(context, t => makeChange(t, context.sourceFile, assertion)); return [createCodeFixAction(fixId, changes, Diagnostics.Add_unknown_conversion_for_non_overlapping_types, fixId, Diagnostics.Add_unknown_to_all_conversions_of_non_overlapping_types)]; }, fixIds: [fixId], - getAllCodeActions: (context) => codeFixAll(context, errorCodes, (changes, diag2) => { + getAllCodeActions: context => codeFixAll(context, errorCodes, (changes, diag2) => { const assertion = getAssertion(diag2.file, diag2.start); if (assertion) { makeChange(changes, diag2.file, assertion); @@ -145796,26 +131031,20 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} var init_addEmptyExportDeclaration = __esm({ "src/services/codefixes/addEmptyExportDeclaration.ts"() { "use strict"; + init_ts4(); init_ts_codefix(); registerCodeFix({ - errorCodes: [ - Diagnostics.await_expressions_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module.code, - Diagnostics.await_using_statements_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module.code, - Diagnostics.for_await_loops_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module.code - ], + errorCodes: [Diagnostics.await_expressions_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module.code, Diagnostics.await_using_statements_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module.code, Diagnostics.for_await_loops_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module.code], getCodeActions: function getCodeActionsToAddEmptyExportDeclaration(context) { - const { sourceFile } = context; - const changes = ts_textChanges_exports.ChangeTracker.with(context, (changes2) => { - const exportDeclaration = factory.createExportDeclaration( - /*modifiers*/ - void 0, - /*isTypeOnly*/ - false, - factory.createNamedExports([]), - /*moduleSpecifier*/ - void 0 - ); + const { + sourceFile + } = context; + const changes = ts_textChanges_exports.ChangeTracker.with(context, changes2 => { + const exportDeclaration = factory.createExportDeclaration( /*modifiers*/ + void 0, /*isTypeOnly*/ + false, factory.createNamedExports([]), /*moduleSpecifier*/ + void 0); changes2.insertNodeAtEndOfScope(sourceFile, sourceFile, exportDeclaration); }); return [createCodeFixActionWithoutFixAll("addEmptyExportDeclaration", changes, Diagnostics.Add_export_to_make_this_file_into_a_module)]; @@ -145826,7 +131055,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} // src/services/codefixes/addMissingAsync.ts function getFix(context, decl, trackChanges, fixedDeclarations) { - const changes = trackChanges((t) => makeChange2(t, context.sourceFile, decl, fixedDeclarations)); + const changes = trackChanges(t => makeChange2(t, context.sourceFile, decl, fixedDeclarations)); return createCodeFixAction(fixId2, changes, Diagnostics.Add_async_modifier_to_containing_function, fixId2, Diagnostics.Add_all_missing_async_modifiers); } function makeChange2(changeTracker, sourceFile, insertionSite, fixedDeclarations) { @@ -145836,25 +131065,15 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } } fixedDeclarations == null ? void 0 : fixedDeclarations.add(getNodeId(insertionSite)); - const cloneWithModifier = factory.replaceModifiers( - getSynthesizedDeepClone( - insertionSite, - /*includeTrivia*/ - true - ), - factory.createNodeArray(factory.createModifiersFromModifierFlags(getSyntacticModifierFlags(insertionSite) | 1024 /* Async */)) - ); - changeTracker.replaceNode( - sourceFile, - insertionSite, - cloneWithModifier - ); + const cloneWithModifier = factory.replaceModifiers(getSynthesizedDeepClone(insertionSite, /*includeTrivia*/ + true), factory.createNodeArray(factory.createModifiersFromModifierFlags(getSyntacticModifierFlags(insertionSite) | 1024 /* Async */))); + + changeTracker.replaceNode(sourceFile, insertionSite, cloneWithModifier); } 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) => { + const decl = findAncestor(token, node => { if (node.getStart(sourceFile) < span.start || node.getEnd() > textSpanEnd(span)) { return "quit"; } @@ -145863,44 +131082,57 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return decl; } function getIsMatchingAsyncError(span, errorCode) { - return ({ start, length: length2, relatedInformation, code }) => isNumber(start) && isNumber(length2) && textSpansEqual({ start, length: length2 }, span) && code === errorCode && !!relatedInformation && some(relatedInformation, (related) => related.code === Diagnostics.Did_you_mean_to_mark_this_function_as_async.code); + return ({ + start, + length: length2, + relatedInformation, + code + }) => isNumber(start) && isNumber(length2) && textSpansEqual({ + start, + length: length2 + }, span) && code === errorCode && !!relatedInformation && some(relatedInformation, related => related.code === Diagnostics.Did_you_mean_to_mark_this_function_as_async.code); } var fixId2, errorCodes2; var init_addMissingAsync = __esm({ "src/services/codefixes/addMissingAsync.ts"() { "use strict"; + init_ts4(); init_ts_codefix(); fixId2 = "addMissingAsync"; - errorCodes2 = [ - Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1.code, - Diagnostics.Type_0_is_not_assignable_to_type_1.code, - Diagnostics.Type_0_is_not_comparable_to_type_1.code - ]; + errorCodes2 = [Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1.code, Diagnostics.Type_0_is_not_assignable_to_type_1.code, Diagnostics.Type_0_is_not_comparable_to_type_1.code]; registerCodeFix({ fixIds: [fixId2], errorCodes: errorCodes2, getCodeActions: function getCodeActionsToAddMissingAsync(context) { - const { sourceFile, errorCode, cancellationToken, program, span } = context; + const { + sourceFile, + errorCode, + cancellationToken, + program, + span + } = context; const diagnostic = find(program.getTypeChecker().getDiagnostics(sourceFile, cancellationToken), getIsMatchingAsyncError(span, errorCode)); - const directSpan = diagnostic && diagnostic.relatedInformation && find(diagnostic.relatedInformation, (r) => r.code === Diagnostics.Did_you_mean_to_mark_this_function_as_async.code); + const directSpan = diagnostic && diagnostic.relatedInformation && find(diagnostic.relatedInformation, r => r.code === Diagnostics.Did_you_mean_to_mark_this_function_as_async.code); const decl = getFixableErrorSpanDeclaration(sourceFile, directSpan); if (!decl) { return; } - const trackChanges = (cb) => ts_textChanges_exports.ChangeTracker.with(context, cb); + const trackChanges = cb => ts_textChanges_exports.ChangeTracker.with(context, cb); return [getFix(context, decl, trackChanges)]; }, - getAllCodeActions: (context) => { - const { sourceFile } = context; - const fixedDeclarations = /* @__PURE__ */ new Set(); + getAllCodeActions: context => { + const { + sourceFile + } = context; + const fixedDeclarations = /* @__PURE__ */new Set(); return codeFixAll(context, errorCodes2, (t, diagnostic) => { - const span = diagnostic.relatedInformation && find(diagnostic.relatedInformation, (r) => r.code === Diagnostics.Did_you_mean_to_mark_this_function_as_async.code); + const span = diagnostic.relatedInformation && find(diagnostic.relatedInformation, r => r.code === Diagnostics.Did_you_mean_to_mark_this_function_as_async.code); const decl = getFixableErrorSpanDeclaration(sourceFile, span); if (!decl) { return; } - const trackChanges = (cb) => (cb(t), []); + const trackChanges = cb => (cb(t), []); return getFix(context, decl, trackChanges, fixedDeclarations); }); } @@ -145914,30 +131146,40 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return expression && isMissingAwaitError(sourceFile, errorCode, span, cancellationToken, program) && isInsideAwaitableBody(expression) ? expression : void 0; } function getDeclarationSiteFix(context, expression, errorCode, checker, trackChanges, fixedDeclarations) { - const { sourceFile, program, cancellationToken } = context; + const { + sourceFile, + program, + cancellationToken + } = context; const awaitableInitializers = findAwaitableInitializers(expression, sourceFile, cancellationToken, program, checker); if (awaitableInitializers) { - const initializerChanges = trackChanges((t) => { - forEach(awaitableInitializers.initializers, ({ expression: expression2 }) => makeChange3(t, errorCode, sourceFile, checker, expression2, fixedDeclarations)); + const initializerChanges = trackChanges(t => { + forEach(awaitableInitializers.initializers, ({ + expression: expression2 + }) => makeChange3(t, errorCode, sourceFile, checker, expression2, fixedDeclarations)); if (fixedDeclarations && awaitableInitializers.needsSecondPassForFixAll) { makeChange3(t, errorCode, sourceFile, checker, expression, fixedDeclarations); } }); - return createCodeFixActionWithoutFixAll( - "addMissingAwaitToInitializer", - initializerChanges, - awaitableInitializers.initializers.length === 1 ? [Diagnostics.Add_await_to_initializer_for_0, awaitableInitializers.initializers[0].declarationSymbol.name] : Diagnostics.Add_await_to_initializers - ); + return createCodeFixActionWithoutFixAll("addMissingAwaitToInitializer", initializerChanges, awaitableInitializers.initializers.length === 1 ? [Diagnostics.Add_await_to_initializer_for_0, awaitableInitializers.initializers[0].declarationSymbol.name] : Diagnostics.Add_await_to_initializers); } } function getUseSiteFix(context, expression, errorCode, checker, trackChanges, fixedDeclarations) { - const changes = trackChanges((t) => makeChange3(t, errorCode, context.sourceFile, checker, expression, fixedDeclarations)); + const changes = trackChanges(t => makeChange3(t, errorCode, context.sourceFile, checker, expression, fixedDeclarations)); return createCodeFixAction(fixId3, changes, Diagnostics.Add_await, fixId3, Diagnostics.Fix_all_expressions_possibly_missing_await); } function isMissingAwaitError(sourceFile, errorCode, span, cancellationToken, program) { const checker = program.getTypeChecker(); const diagnostics = checker.getDiagnostics(sourceFile, cancellationToken); - return some(diagnostics, ({ start, length: length2, relatedInformation, code }) => isNumber(start) && isNumber(length2) && textSpansEqual({ start, length: length2 }, span) && code === errorCode && !!relatedInformation && some(relatedInformation, (related) => related.code === Diagnostics.Did_you_forget_to_use_await.code)); + return some(diagnostics, ({ + start, + length: length2, + relatedInformation, + code + }) => isNumber(start) && isNumber(length2) && textSpansEqual({ + start, + length: length2 + }, span) && code === errorCode && !!relatedInformation && some(relatedInformation, related => related.code === Diagnostics.Did_you_forget_to_use_await.code)); } function findAwaitableInitializers(expression, sourceFile, cancellationToken, program, checker) { const identifiers = getIdentifiersFromErrorSpanExpression(expression, checker); @@ -145959,7 +131201,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} continue; } const diagnostics = program.getSemanticDiagnostics(sourceFile, cancellationToken); - const isUsedElsewhere = ts_FindAllReferences_exports.Core.eachSymbolReferenceInFile(variableName, checker, sourceFile, (reference) => { + const isUsedElsewhere = ts_FindAllReferences_exports.Core.eachSymbolReferenceInFile(variableName, checker, sourceFile, reference => { return identifier !== reference && !symbolReferenceIsAlsoMissingAwait(reference, diagnostics, sourceFile, checker); }); if (isUsedElsewhere) { @@ -145978,10 +131220,16 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } function getIdentifiersFromErrorSpanExpression(expression, checker) { if (isPropertyAccessExpression(expression.parent) && isIdentifier(expression.parent.expression)) { - return { identifiers: [expression.parent.expression], isCompleteFix: true }; + return { + identifiers: [expression.parent.expression], + isCompleteFix: true + }; } if (isIdentifier(expression)) { - return { identifiers: [expression], isCompleteFix: true }; + return { + identifiers: [expression], + isCompleteFix: true + }; } if (isBinaryExpression(expression)) { let sides; @@ -145996,13 +131244,17 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} (sides || (sides = [])).push(side); } } - return sides && { identifiers: sides, isCompleteFix }; + return sides && { + identifiers: sides, + isCompleteFix + }; } } function symbolReferenceIsAlsoMissingAwait(reference, diagnostics, sourceFile, checker) { const errorNode = isPropertyAccessExpression(reference.parent) ? reference.parent.name : isBinaryExpression(reference.parent) ? reference.parent : reference; - const diagnostic = find(diagnostics, (diagnostic2) => diagnostic2.start === errorNode.getStart(sourceFile) && diagnostic2.start + diagnostic2.length === errorNode.getEnd()); - return diagnostic && contains(errorCodes3, diagnostic.code) || // A Promise is usually not correct in a binary expression (it's not valid + const diagnostic = find(diagnostics, diagnostic2 => diagnostic2.start === errorNode.getStart(sourceFile) && diagnostic2.start + diagnostic2.length === errorNode.getEnd()); + return diagnostic && contains(errorCodes3, diagnostic.code) || + // A Promise is usually not correct in a binary expression (it's not valid // in an arithmetic expression and an equality comparison seems unusual), // but if the other side of the binary expression has an error, the side // is typed `any` which will squash the error that would identify this @@ -146011,9 +131263,11 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} // is accidentally missing `await`. checker.getTypeAtLocation(errorNode).flags & 1 /* Any */; } + function isInsideAwaitableBody(node) { - return node.flags & 65536 /* AwaitContext */ || !!findAncestor(node, (ancestor) => ancestor.parent && isArrowFunction(ancestor.parent) && ancestor.parent.body === ancestor || isBlock(ancestor) && (ancestor.parent.kind === 262 /* FunctionDeclaration */ || ancestor.parent.kind === 218 /* FunctionExpression */ || ancestor.parent.kind === 219 /* ArrowFunction */ || ancestor.parent.kind === 174 /* MethodDeclaration */)); + return node.flags & 65536 /* AwaitContext */ || !!findAncestor(node, ancestor => ancestor.parent && isArrowFunction(ancestor.parent) && ancestor.parent.body === ancestor || isBlock(ancestor) && (ancestor.parent.kind === 262 /* FunctionDeclaration */ || ancestor.parent.kind === 218 /* FunctionExpression */ || ancestor.parent.kind === 219 /* ArrowFunction */ || ancestor.parent.kind === 174 /* MethodDeclaration */)); } + function makeChange3(changeTracker, errorCode, sourceFile, checker, insertionSite, fixedDeclarations) { if (isForOfStatement(insertionSite.parent) && !insertionSite.parent.awaitModifier) { const exprType = checker.getTypeAtLocation(insertionSite); @@ -146043,11 +131297,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return; } } - changeTracker.replaceNode( - sourceFile, - insertionSite.parent.expression, - factory.createParenthesizedExpression(factory.createAwaitExpression(insertionSite.parent.expression)) - ); + changeTracker.replaceNode(sourceFile, insertionSite.parent.expression, factory.createParenthesizedExpression(factory.createAwaitExpression(insertionSite.parent.expression))); insertLeadingSemicolonIfNeeded(changeTracker, insertionSite.parent.expression, sourceFile); } else if (contains(callableConstructableErrorCodes, errorCode) && isCallOrNewExpression(insertionSite.parent)) { if (fixedDeclarations && isIdentifier(insertionSite)) { @@ -146078,59 +131328,46 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} var init_addMissingAwait = __esm({ "src/services/codefixes/addMissingAwait.ts"() { "use strict"; + init_ts4(); init_ts_codefix(); fixId3 = "addMissingAwait"; propertyAccessCode = Diagnostics.Property_0_does_not_exist_on_type_1.code; - callableConstructableErrorCodes = [ - Diagnostics.This_expression_is_not_callable.code, - Diagnostics.This_expression_is_not_constructable.code - ]; - errorCodes3 = [ - Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_bigint_or_an_enum_type.code, - Diagnostics.The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type.code, - Diagnostics.The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type.code, - Diagnostics.Operator_0_cannot_be_applied_to_type_1.code, - Diagnostics.Operator_0_cannot_be_applied_to_types_1_and_2.code, - Diagnostics.This_comparison_appears_to_be_unintentional_because_the_types_0_and_1_have_no_overlap.code, - Diagnostics.This_condition_will_always_return_true_since_this_0_is_always_defined.code, - Diagnostics.Type_0_is_not_an_array_type.code, - Diagnostics.Type_0_is_not_an_array_type_or_a_string_type.code, - Diagnostics.Type_0_can_only_be_iterated_through_when_using_the_downlevelIteration_flag_or_with_a_target_of_es2015_or_higher.code, - Diagnostics.Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator.code, - Diagnostics.Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator.code, - Diagnostics.Type_0_must_have_a_Symbol_iterator_method_that_returns_an_iterator.code, - Diagnostics.Type_0_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator.code, - Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1.code, - propertyAccessCode, - ...callableConstructableErrorCodes - ]; + callableConstructableErrorCodes = [Diagnostics.This_expression_is_not_callable.code, Diagnostics.This_expression_is_not_constructable.code]; + errorCodes3 = [Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_bigint_or_an_enum_type.code, Diagnostics.The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type.code, Diagnostics.The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type.code, Diagnostics.Operator_0_cannot_be_applied_to_type_1.code, Diagnostics.Operator_0_cannot_be_applied_to_types_1_and_2.code, Diagnostics.This_comparison_appears_to_be_unintentional_because_the_types_0_and_1_have_no_overlap.code, Diagnostics.This_condition_will_always_return_true_since_this_0_is_always_defined.code, Diagnostics.Type_0_is_not_an_array_type.code, Diagnostics.Type_0_is_not_an_array_type_or_a_string_type.code, Diagnostics.Type_0_can_only_be_iterated_through_when_using_the_downlevelIteration_flag_or_with_a_target_of_es2015_or_higher.code, Diagnostics.Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator.code, Diagnostics.Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator.code, Diagnostics.Type_0_must_have_a_Symbol_iterator_method_that_returns_an_iterator.code, Diagnostics.Type_0_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator.code, Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1.code, propertyAccessCode, ...callableConstructableErrorCodes]; registerCodeFix({ fixIds: [fixId3], errorCodes: errorCodes3, getCodeActions: function getCodeActionsToAddMissingAwait(context) { - const { sourceFile, errorCode, span, cancellationToken, program } = context; + const { + sourceFile, + errorCode, + span, + cancellationToken, + program + } = context; const expression = getAwaitErrorSpanExpression(sourceFile, errorCode, span, cancellationToken, program); if (!expression) { return; } const checker = context.program.getTypeChecker(); - const trackChanges = (cb) => ts_textChanges_exports.ChangeTracker.with(context, cb); - return compact([ - getDeclarationSiteFix(context, expression, errorCode, checker, trackChanges), - getUseSiteFix(context, expression, errorCode, checker, trackChanges) - ]); + const trackChanges = cb => ts_textChanges_exports.ChangeTracker.with(context, cb); + return compact([getDeclarationSiteFix(context, expression, errorCode, checker, trackChanges), getUseSiteFix(context, expression, errorCode, checker, trackChanges)]); }, - getAllCodeActions: (context) => { - const { sourceFile, program, cancellationToken } = context; + getAllCodeActions: context => { + const { + sourceFile, + program, + cancellationToken + } = context; const checker = context.program.getTypeChecker(); - const fixedDeclarations = /* @__PURE__ */ new Set(); + const fixedDeclarations = /* @__PURE__ */new Set(); return codeFixAll(context, errorCodes3, (t, diagnostic) => { const expression = getAwaitErrorSpanExpression(sourceFile, diagnostic.code, diagnostic, cancellationToken, program); if (!expression) { return; } - const trackChanges = (cb) => (cb(t), []); + const trackChanges = cb => (cb(t), []); return getDeclarationSiteFix(context, expression, diagnostic.code, checker, trackChanges, fixedDeclarations) || getUseSiteFix(context, expression, diagnostic.code, checker, trackChanges, fixedDeclarations); }); } @@ -146141,21 +131378,20 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} // src/services/codefixes/addMissingConst.ts function makeChange4(changeTracker, sourceFile, pos, program, fixedNodes) { const token = getTokenAtPosition(sourceFile, pos); - const forInitializer = findAncestor(token, (node) => isForInOrOfStatement(node.parent) ? node.parent.initializer === node : isPossiblyPartOfDestructuring(node) ? false : "quit"); - if (forInitializer) - return applyChange(changeTracker, forInitializer, sourceFile, fixedNodes); + const forInitializer = findAncestor(token, node => isForInOrOfStatement(node.parent) ? node.parent.initializer === node : isPossiblyPartOfDestructuring(node) ? false : "quit"); + if (forInitializer) return applyChange(changeTracker, forInitializer, sourceFile, fixedNodes); const parent2 = token.parent; if (isBinaryExpression(parent2) && parent2.operatorToken.kind === 64 /* EqualsToken */ && isExpressionStatement(parent2.parent)) { return applyChange(changeTracker, token, sourceFile, fixedNodes); } if (isArrayLiteralExpression(parent2)) { const checker = program.getTypeChecker(); - if (!every(parent2.elements, (element) => arrayElementCouldBeVariableDeclaration(element, checker))) { + if (!every(parent2.elements, element => arrayElementCouldBeVariableDeclaration(element, checker))) { return; } return applyChange(changeTracker, parent2, sourceFile, fixedNodes); } - const commaExpression = findAncestor(token, (node) => isExpressionStatement(node.parent) ? true : isPossiblyPartOfCommaSeperatedInitializer(node) ? false : "quit"); + const commaExpression = findAncestor(token, node => isExpressionStatement(node.parent) ? true : isPossiblyPartOfCommaSeperatedInitializer(node) ? false : "quit"); if (commaExpression) { const checker = program.getTypeChecker(); if (!expressionCouldBeVariableDeclaration(commaExpression, checker)) { @@ -146182,11 +131418,8 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } } function arrayElementCouldBeVariableDeclaration(expression, checker) { - const identifier = isIdentifier(expression) ? expression : isAssignmentExpression( - expression, - /*excludeCompoundAssignment*/ - true - ) && isIdentifier(expression.left) ? expression.left : void 0; + const identifier = isIdentifier(expression) ? expression : isAssignmentExpression(expression, /*excludeCompoundAssignment*/ + true) && isIdentifier(expression.left) ? expression.left : void 0; return !!identifier && !checker.getSymbolAtLocation(identifier); } function isPossiblyPartOfCommaSeperatedInitializer(node) { @@ -146204,7 +131437,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return false; } if (expression.operatorToken.kind === 28 /* CommaToken */) { - return every([expression.left, expression.right], (expression2) => expressionCouldBeVariableDeclaration(expression2, checker)); + return every([expression.left, expression.right], expression2 => expressionCouldBeVariableDeclaration(expression2, checker)); } return expression.operatorToken.kind === 64 /* EqualsToken */ && isIdentifier(expression.left) && !checker.getSymbolAtLocation(expression.left); } @@ -146212,24 +131445,22 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} var init_addMissingConst = __esm({ "src/services/codefixes/addMissingConst.ts"() { "use strict"; + init_ts4(); init_ts_codefix(); fixId4 = "addMissingConst"; - errorCodes4 = [ - Diagnostics.Cannot_find_name_0.code, - Diagnostics.No_value_exists_in_scope_for_the_shorthand_property_0_Either_declare_one_or_provide_an_initializer.code - ]; + errorCodes4 = [Diagnostics.Cannot_find_name_0.code, Diagnostics.No_value_exists_in_scope_for_the_shorthand_property_0_Either_declare_one_or_provide_an_initializer.code]; registerCodeFix({ errorCodes: errorCodes4, getCodeActions: function getCodeActionsToAddMissingConst(context) { - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => makeChange4(t, context.sourceFile, context.span.start, context.program)); + const changes = ts_textChanges_exports.ChangeTracker.with(context, t => makeChange4(t, context.sourceFile, context.span.start, context.program)); if (changes.length > 0) { return [createCodeFixAction(fixId4, changes, Diagnostics.Add_const_to_unresolved_variable, fixId4, Diagnostics.Add_const_to_all_unresolved_variables)]; } }, fixIds: [fixId4], - getAllCodeActions: (context) => { - const fixedNodes = /* @__PURE__ */ new Set(); + getAllCodeActions: context => { + const fixedNodes = /* @__PURE__ */new Set(); return codeFixAll(context, errorCodes4, (changes, diag2) => makeChange4(changes, diag2.file, diag2.start, context.program, fixedNodes)); } }); @@ -146251,23 +131482,22 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} var init_addMissingDeclareProperty = __esm({ "src/services/codefixes/addMissingDeclareProperty.ts"() { "use strict"; + init_ts4(); init_ts_codefix(); fixId5 = "addMissingDeclareProperty"; - errorCodes5 = [ - Diagnostics.Property_0_will_overwrite_the_base_property_in_1_If_this_is_intentional_add_an_initializer_Otherwise_add_a_declare_modifier_or_remove_the_redundant_declaration.code - ]; + errorCodes5 = [Diagnostics.Property_0_will_overwrite_the_base_property_in_1_If_this_is_intentional_add_an_initializer_Otherwise_add_a_declare_modifier_or_remove_the_redundant_declaration.code]; registerCodeFix({ errorCodes: errorCodes5, getCodeActions: function getCodeActionsToAddMissingDeclareOnProperty(context) { - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => makeChange5(t, context.sourceFile, context.span.start)); + const changes = ts_textChanges_exports.ChangeTracker.with(context, t => makeChange5(t, context.sourceFile, context.span.start)); if (changes.length > 0) { return [createCodeFixAction(fixId5, changes, Diagnostics.Prefix_with_declare, fixId5, Diagnostics.Prefix_all_incorrect_property_declarations_with_declare)]; } }, fixIds: [fixId5], - getAllCodeActions: (context) => { - const fixedNodes = /* @__PURE__ */ new Set(); + getAllCodeActions: context => { + const fixedNodes = /* @__PURE__ */new Set(); return codeFixAll(context, errorCodes5, (changes, diag2) => makeChange5(changes, diag2.file, diag2.start, fixedNodes)); } }); @@ -146279,19 +131509,16 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} const token = getTokenAtPosition(sourceFile, pos); const decorator = findAncestor(token, isDecorator); Debug.assert(!!decorator, "Expected position to be owned by a decorator."); - const replacement = factory.createCallExpression( - decorator.expression, - /*typeArguments*/ - void 0, - /*argumentsArray*/ - void 0 - ); + const replacement = factory.createCallExpression(decorator.expression, /*typeArguments*/ + void 0, /*argumentsArray*/ + void 0); changeTracker.replaceNode(sourceFile, decorator.expression, replacement); } var fixId6, errorCodes6; var init_addMissingInvocationForDecorator = __esm({ "src/services/codefixes/addMissingInvocationForDecorator.ts"() { "use strict"; + init_ts4(); init_ts_codefix(); fixId6 = "addMissingInvocationForDecorator"; @@ -146299,11 +131526,11 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} registerCodeFix({ errorCodes: errorCodes6, getCodeActions: function getCodeActionsToAddMissingInvocationForDecorator(context) { - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => makeChange6(t, context.sourceFile, context.span.start)); + const changes = ts_textChanges_exports.ChangeTracker.with(context, t => makeChange6(t, context.sourceFile, context.span.start)); return [createCodeFixAction(fixId6, changes, Diagnostics.Call_decorator_expression, fixId6, Diagnostics.Add_to_all_uncalled_decorators)]; }, fixIds: [fixId6], - getAllCodeActions: (context) => codeFixAll(context, errorCodes6, (changes, diag2) => makeChange6(changes, diag2.file, diag2.start)) + getAllCodeActions: context => codeFixAll(context, errorCodes6, (changes, diag2) => makeChange6(changes, diag2.file, diag2.start)) }); } }); @@ -146319,25 +131546,15 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} Debug.assert(!param.type, "Tried to add a parameter name to a parameter that already had one."); Debug.assert(i > -1, "Parameter not found in parent parameter list."); let end = param.name.getEnd(); - let typeNode = factory.createTypeReferenceNode( - param.name, - /*typeArguments*/ - void 0 - ); + let typeNode = factory.createTypeReferenceNode(param.name, /*typeArguments*/ + void 0); let nextParam = tryGetNextParam(sourceFile, param); while (nextParam) { typeNode = factory.createArrayTypeNode(typeNode); end = nextParam.getEnd(); nextParam = tryGetNextParam(sourceFile, nextParam); } - const replacement = factory.createParameterDeclaration( - param.modifiers, - param.dotDotDotToken, - "arg" + i, - param.questionToken, - param.dotDotDotToken && !isArrayTypeNode(typeNode) ? factory.createArrayTypeNode(typeNode) : typeNode, - param.initializer - ); + const replacement = factory.createParameterDeclaration(param.modifiers, param.dotDotDotToken, "arg" + i, param.questionToken, param.dotDotDotToken && !isArrayTypeNode(typeNode) ? factory.createArrayTypeNode(typeNode) : typeNode, param.initializer); changeTracker.replaceRange(sourceFile, createRange(param.getStart(sourceFile), end), replacement); } function tryGetNextParam(sourceFile, param) { @@ -146351,6 +131568,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} var init_addNameToNamelessParameter = __esm({ "src/services/codefixes/addNameToNamelessParameter.ts"() { "use strict"; + init_ts4(); init_ts_codefix(); fixId7 = "addNameToNamelessParameter"; @@ -146358,11 +131576,11 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} registerCodeFix({ errorCodes: errorCodes7, getCodeActions: function getCodeActionsToAddNameToNamelessParameter(context) { - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => makeChange7(t, context.sourceFile, context.span.start)); + const changes = ts_textChanges_exports.ChangeTracker.with(context, t => makeChange7(t, context.sourceFile, context.span.start)); return [createCodeFixAction(fixId7, changes, Diagnostics.Add_parameter_name, fixId7, Diagnostics.Add_names_to_all_parameters_without_names)]; }, fixIds: [fixId7], - getAllCodeActions: (context) => codeFixAll(context, errorCodes7, (changes, diag2) => makeChange7(changes, diag2.file, diag2.start)) + getAllCodeActions: context => codeFixAll(context, errorCodes7, (changes, diag2) => makeChange7(changes, diag2.file, diag2.start)) }); } }); @@ -146374,9 +131592,12 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (!sourceTarget) { return emptyArray; } - const { source: sourceNode, target: targetNode } = sourceTarget; + const { + source: sourceNode, + target: targetNode + } = sourceTarget; const target = shouldUseParentTypeOfProperty(sourceNode, targetNode, checker) ? checker.getTypeAtLocation(targetNode.expression) : checker.getTypeAtLocation(targetNode); - if ((_b = (_a = target.symbol) == null ? void 0 : _a.declarations) == null ? void 0 : _b.some((d) => getSourceFileOfNode(d).fileName.match(/\.d\.ts$/))) { + if ((_b = (_a = target.symbol) == null ? void 0 : _a.declarations) == null ? void 0 : _b.some(d => getSourceFileOfNode(d).fileName.match(/\.d\.ts$/))) { return emptyArray; } return checker.getExactOptionalProperties(target); @@ -146389,29 +131610,32 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (!errorNode) { return void 0; } else if (isBinaryExpression(errorNode.parent) && errorNode.parent.operatorToken.kind === 64 /* EqualsToken */) { - return { source: errorNode.parent.right, target: errorNode.parent.left }; + return { + source: errorNode.parent.right, + target: errorNode.parent.left + }; } else if (isVariableDeclaration(errorNode.parent) && errorNode.parent.initializer) { - return { source: errorNode.parent.initializer, target: errorNode.parent.name }; + 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 @@ -146423,10 +131647,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} for (const add of toAdd) { const d = add.valueDeclaration; if (d && (isPropertySignature(d) || isPropertyDeclaration(d)) && d.type) { - const t = factory.createUnionTypeNode([ - ...d.type.kind === 192 /* UnionType */ ? d.type.types : [d.type], - factory.createTypeReferenceNode("undefined") - ]); + const t = factory.createUnionTypeNode([...(d.type.kind === 192 /* UnionType */ ? d.type.types : [d.type]), factory.createTypeReferenceNode("undefined")]); changes.replaceNode(d.getSourceFile(), d.type, t); } } @@ -146435,14 +131656,11 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} var init_addOptionalPropertyUndefined = __esm({ "src/services/codefixes/addOptionalPropertyUndefined.ts"() { "use strict"; + init_ts4(); init_ts_codefix(); addOptionalPropertyUndefined = "addOptionalPropertyUndefined"; - errorCodes8 = [ - Diagnostics.Type_0_is_not_assignable_to_type_1_with_exactOptionalPropertyTypes_Colon_true_Consider_adding_undefined_to_the_type_of_the_target.code, - Diagnostics.Type_0_is_not_assignable_to_type_1_with_exactOptionalPropertyTypes_Colon_true_Consider_adding_undefined_to_the_types_of_the_target_s_properties.code, - Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1_with_exactOptionalPropertyTypes_Colon_true_Consider_adding_undefined_to_the_types_of_the_target_s_properties.code - ]; + errorCodes8 = [Diagnostics.Type_0_is_not_assignable_to_type_1_with_exactOptionalPropertyTypes_Colon_true_Consider_adding_undefined_to_the_type_of_the_target.code, Diagnostics.Type_0_is_not_assignable_to_type_1_with_exactOptionalPropertyTypes_Colon_true_Consider_adding_undefined_to_the_types_of_the_target_s_properties.code, Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1_with_exactOptionalPropertyTypes_Colon_true_Consider_adding_undefined_to_the_types_of_the_target_s_properties.code]; registerCodeFix({ errorCodes: errorCodes8, getCodeActions(context) { @@ -146451,7 +131669,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (!toAdd.length) { return void 0; } - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => addUndefinedToOptionalProperty(t, toAdd)); + const changes = ts_textChanges_exports.ChangeTracker.with(context, t => addUndefinedToOptionalProperty(t, toAdd)); return [createCodeFixActionWithoutFixAll(addOptionalPropertyUndefined, changes, Diagnostics.Add_undefined_to_optional_property_type)]; }, fixIds: [addOptionalPropertyUndefined] @@ -146471,28 +131689,23 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return isFunctionLikeDeclaration(decl) ? decl.parameters.some(hasUsableJSDoc) || !decl.type && !!getJSDocReturnType(decl) : !decl.type && !!getJSDocType(decl); } function doChange8(changes, sourceFile, decl) { - if (isFunctionLikeDeclaration(decl) && (getJSDocReturnType(decl) || decl.parameters.some((p) => !!getJSDocType(p)))) { + if (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"); @@ -146503,6 +131716,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} function isDeclarationWithType(node) { return isFunctionLikeDeclaration(node) || node.kind === 260 /* VariableDeclaration */ || node.kind === 171 /* PropertySignature */ || node.kind === 172 /* PropertyDeclaration */; } + function transformJSDocType(node) { switch (node.kind) { case 319 /* JSDocAllType */: @@ -146529,13 +131743,9 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } } function transformJSDocTypeLiteral(node) { - const typeNode = factory.createTypeLiteralNode(map(node.jsDocPropertyTags, (tag) => factory.createPropertySignature( - /*modifiers*/ - void 0, - isIdentifier(tag.name) ? tag.name : tag.name.right, - isOptionalJSDocPropertyLikeTag(tag) ? factory.createToken(58 /* QuestionToken */) : void 0, - tag.typeExpression && visitNode(tag.typeExpression.type, transformJSDocType, isTypeNode) || factory.createKeywordTypeNode(133 /* AnyKeyword */) - ))); + const typeNode = factory.createTypeLiteralNode(map(node.jsDocPropertyTags, tag => factory.createPropertySignature( /*modifiers*/ + void 0, isIdentifier(tag.name) ? tag.name : tag.name.right, isOptionalJSDocPropertyLikeTag(tag) ? factory.createToken(58 /* QuestionToken */) : void 0, tag.typeExpression && visitNode(tag.typeExpression.type, transformJSDocType, isTypeNode) || factory.createKeywordTypeNode(133 /* AnyKeyword */)))); + setEmitFlags(typeNode, 1 /* SingleLine */); return typeNode; } @@ -146549,8 +131759,10 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return factory.createArrayTypeNode(visitNode(node.type, transformJSDocType, isTypeNode)); } function transformJSDocFunctionType(node) { - return factory.createFunctionTypeNode(emptyArray, node.parameters.map(transformJSDocParameter), node.type ?? factory.createKeywordTypeNode(133 /* AnyKeyword */)); + var _node$type; + return factory.createFunctionTypeNode(emptyArray, node.parameters.map(transformJSDocParameter), (_node$type = node.type) !== null && _node$type !== void 0 ? _node$type : factory.createKeywordTypeNode(133 /* AnyKeyword */)); } + function transformJSDocParameter(node) { const index = node.parent.parameters.indexOf(node); const isRest = node.type.kind === 325 /* JSDocVariadicType */ && index === node.parent.parameters.length - 1; @@ -146589,24 +131801,13 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return factory.createTypeReferenceNode(name, args); } function transformJSDocIndexSignature(node) { - const index = factory.createParameterDeclaration( - /*modifiers*/ - void 0, - /*dotDotDotToken*/ - void 0, - node.typeArguments[0].kind === 150 /* NumberKeyword */ ? "n" : "s", - /*questionToken*/ - void 0, - factory.createTypeReferenceNode(node.typeArguments[0].kind === 150 /* NumberKeyword */ ? "number" : "string", []), - /*initializer*/ - void 0 - ); - const indexSignature = factory.createTypeLiteralNode([factory.createIndexSignature( - /*modifiers*/ - void 0, - [index], - node.typeArguments[1] - )]); + const index = factory.createParameterDeclaration( /*modifiers*/ + void 0, /*dotDotDotToken*/ + void 0, node.typeArguments[0].kind === 150 /* NumberKeyword */ ? "n" : "s", /*questionToken*/ + void 0, factory.createTypeReferenceNode(node.typeArguments[0].kind === 150 /* NumberKeyword */ ? "number" : "string", []), /*initializer*/ + void 0); + const indexSignature = factory.createTypeLiteralNode([factory.createIndexSignature( /*modifiers*/ + void 0, [index], node.typeArguments[1])]); setEmitFlags(indexSignature, 1 /* SingleLine */); return indexSignature; } @@ -146614,6 +131815,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} var init_annotateWithTypeFromJSDoc = __esm({ "src/services/codefixes/annotateWithTypeFromJSDoc.ts"() { "use strict"; + init_ts4(); init_ts_codefix(); fixId8 = "annotateWithTypeFromJSDoc"; @@ -146622,16 +131824,14 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} errorCodes: errorCodes9, getCodeActions(context) { const decl = getDeclaration(context.sourceFile, context.span.start); - if (!decl) - return; - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange8(t, context.sourceFile, decl)); + 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) => { + 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); }) }); } @@ -146662,17 +131862,13 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} function createClassElementsFromSymbol(symbol) { const memberElements = []; if (symbol.exports) { - symbol.exports.forEach((member) => { + symbol.exports.forEach(member => { if (member.name === "prototype" && member.declarations) { const firstDeclaration = member.declarations[0]; if (member.declarations.length === 1 && isPropertyAccessExpression(firstDeclaration) && isBinaryExpression(firstDeclaration.parent) && firstDeclaration.parent.operatorToken.kind === 64 /* EqualsToken */ && isObjectLiteralExpression(firstDeclaration.parent.right)) { const prototypes = firstDeclaration.parent.right; - createClassElement( - prototypes.symbol, - /*modifiers*/ - void 0, - memberElements - ); + createClassElement(prototypes.symbol, /*modifiers*/ + void 0, memberElements); } } else { createClassElement(member, [factory.createToken(126 /* StaticKeyword */)], memberElements); @@ -146684,34 +131880,25 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} var _a, _b, _c, _d; if (key === "constructor" && member.valueDeclaration) { const prototypeAssignment = (_d = (_c = (_b = (_a = symbol.exports) == null ? void 0 : _a.get("prototype")) == null ? void 0 : _b.declarations) == null ? void 0 : _c[0]) == null ? void 0 : _d.parent; - if (prototypeAssignment && isBinaryExpression(prototypeAssignment) && isObjectLiteralExpression(prototypeAssignment.right) && some(prototypeAssignment.right.properties, isConstructorAssignment)) { - } else { + if (prototypeAssignment && isBinaryExpression(prototypeAssignment) && isObjectLiteralExpression(prototypeAssignment.right) && some(prototypeAssignment.right.properties, isConstructorAssignment)) {} else { changes.delete(sourceFile, member.valueDeclaration.parent); } return; } - createClassElement( - member, - /*modifiers*/ - void 0, - memberElements - ); + createClassElement(member, /*modifiers*/ + void 0, memberElements); }); } 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; + return every(_target.properties, property => { + if (isMethodDeclaration(property) || isGetOrSetAccessorDeclaration(property)) return true; + if (isPropertyAssignment(property) && isFunctionExpression(property.initializer) && !!property.name) return true; + if (isConstructorAssignment(property)) return true; return false; }); } @@ -146726,7 +131913,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (!shouldConvertDeclaration(memberDeclaration, assignmentExpr)) { return; } - if (some(members, (m) => { + if (some(members, m => { const name = getNameOfDeclaration(m); if (name && isIdentifier(name) && idText(name) === symbolName(symbol2)) { return true; @@ -146738,16 +131925,10 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} const nodeToDelete = assignmentBinaryExpression.parent && assignmentBinaryExpression.parent.kind === 244 /* ExpressionStatement */ ? assignmentBinaryExpression.parent : assignmentBinaryExpression; changes.delete(sourceFile, nodeToDelete); if (!assignmentExpr) { - members.push(factory.createPropertyDeclaration( - modifiers, - symbol2.name, - /*questionOrExclamationToken*/ - void 0, - /*type*/ - void 0, - /*initializer*/ - void 0 - )); + members.push(factory.createPropertyDeclaration(modifiers, symbol2.name, /*questionOrExclamationToken*/ + void 0, /*type*/ + void 0, /*initializer*/ + void 0)); return; } if (isAccessExpression(memberDeclaration) && (isFunctionExpression(assignmentExpr) || isArrowFunction(assignmentExpr))) { @@ -146758,61 +131939,37 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } return; } else if (isObjectLiteralExpression(assignmentExpr)) { - forEach( - assignmentExpr.properties, - (property) => { - if (isMethodDeclaration(property) || isGetOrSetAccessorDeclaration(property)) { - members.push(property); - } - if (isPropertyAssignment(property) && isFunctionExpression(property.initializer)) { - createFunctionLikeExpressionMember(members, property.initializer, property.name); - } - if (isConstructorAssignment(property)) - return; - return; + forEach(assignmentExpr.properties, property => { + if (isMethodDeclaration(property) || isGetOrSetAccessorDeclaration(property)) { + members.push(property); } - ); + if (isPropertyAssignment(property) && isFunctionExpression(property.initializer)) { + createFunctionLikeExpressionMember(members, property.initializer, property.name); + } + if (isConstructorAssignment(property)) return; + return; + }); return; } else { - if (isSourceFileJS(sourceFile)) - return; - if (!isPropertyAccessExpression(memberDeclaration)) - return; - const prop = factory.createPropertyDeclaration( - modifiers, - memberDeclaration.name, - /*questionOrExclamationToken*/ - void 0, - /*type*/ - void 0, - assignmentExpr - ); + if (isSourceFileJS(sourceFile)) return; + if (!isPropertyAccessExpression(memberDeclaration)) return; + const prop = factory.createPropertyDeclaration(modifiers, memberDeclaration.name, /*questionOrExclamationToken*/ + void 0, /*type*/ + void 0, assignmentExpr); copyLeadingComments(assignmentBinaryExpression.parent, prop, sourceFile); members.push(prop); return; } function createFunctionLikeExpressionMember(members2, expression, name) { - if (isFunctionExpression(expression)) - return createFunctionExpressionMember(members2, expression, name); - else - return createArrowFunctionExpressionMember(members2, expression, name); + if (isFunctionExpression(expression)) return createFunctionExpressionMember(members2, expression, name);else return createArrowFunctionExpressionMember(members2, expression, name); } function createFunctionExpressionMember(members2, functionExpression, name) { const fullModifiers = concatenate(modifiers, getModifierKindFromSource(functionExpression, 134 /* AsyncKeyword */)); - const method = factory.createMethodDeclaration( - fullModifiers, - /*asteriskToken*/ - void 0, - name, - /*questionToken*/ - void 0, - /*typeParameters*/ - void 0, - functionExpression.parameters, - /*type*/ - void 0, - functionExpression.body - ); + const method = factory.createMethodDeclaration(fullModifiers, /*asteriskToken*/ + void 0, name, /*questionToken*/ + void 0, /*typeParameters*/ + void 0, functionExpression.parameters, /*type*/ + void 0, functionExpression.body); copyLeadingComments(assignmentBinaryExpression, method, sourceFile); members2.push(method); return; @@ -146826,20 +131983,11 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} bodyBlock = factory.createBlock([factory.createReturnStatement(arrowFunctionBody)]); } const fullModifiers = concatenate(modifiers, getModifierKindFromSource(arrowFunction, 134 /* AsyncKeyword */)); - const method = factory.createMethodDeclaration( - fullModifiers, - /*asteriskToken*/ - void 0, - name, - /*questionToken*/ - void 0, - /*typeParameters*/ - void 0, - arrowFunction.parameters, - /*type*/ - void 0, - bodyBlock - ); + const method = factory.createMethodDeclaration(fullModifiers, /*asteriskToken*/ + void 0, name, /*questionToken*/ + void 0, /*typeParameters*/ + void 0, arrowFunction.parameters, /*type*/ + void 0, bodyBlock); copyLeadingComments(assignmentBinaryExpression, method, sourceFile); members2.push(method); } @@ -146852,56 +132000,34 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } const memberElements = createClassElementsFromSymbol(node.symbol); if (initializer.body) { - memberElements.unshift(factory.createConstructorDeclaration( - /*modifiers*/ - void 0, - initializer.parameters, - initializer.body - )); + memberElements.unshift(factory.createConstructorDeclaration( /*modifiers*/ + void 0, initializer.parameters, initializer.body)); } const modifiers = getModifierKindFromSource(node.parent.parent, 95 /* ExportKeyword */); - const cls = factory.createClassDeclaration( - modifiers, - node.name, - /*typeParameters*/ - void 0, - /*heritageClauses*/ - void 0, - memberElements - ); + const cls = factory.createClassDeclaration(modifiers, node.name, /*typeParameters*/ + void 0, /*heritageClauses*/ + void 0, memberElements); return cls; } function createClassFromFunction(node) { const memberElements = createClassElementsFromSymbol(ctorSymbol); if (node.body) { - memberElements.unshift(factory.createConstructorDeclaration( - /*modifiers*/ - void 0, - node.parameters, - node.body - )); + memberElements.unshift(factory.createConstructorDeclaration( /*modifiers*/ + void 0, node.parameters, node.body)); } const modifiers = getModifierKindFromSource(node, 95 /* ExportKeyword */); - const cls = factory.createClassDeclaration( - modifiers, - node.name, - /*typeParameters*/ - void 0, - /*heritageClauses*/ - void 0, - memberElements - ); + const cls = factory.createClassDeclaration(modifiers, node.name, /*typeParameters*/ + void 0, /*heritageClauses*/ + void 0, memberElements); return cls; } } function getModifierKindFromSource(source, kind) { - return canHaveModifiers(source) ? filter(source.modifiers, (modifier) => modifier.kind === kind) : void 0; + 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) { @@ -146921,6 +132047,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} var init_convertFunctionToEs6Class = __esm({ "src/services/codefixes/convertFunctionToEs6Class.ts"() { "use strict"; + init_ts4(); init_ts_codefix(); fixId9 = "convertFunctionToEs6Class"; @@ -146928,11 +132055,11 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} registerCodeFix({ errorCodes: errorCodes10, getCodeActions(context) { - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange9(t, context.sourceFile, context.span.start, context.program.getTypeChecker(), context.preferences, context.program.getCompilerOptions())); + const changes = ts_textChanges_exports.ChangeTracker.with(context, t => doChange9(t, context.sourceFile, context.span.start, context.program.getTypeChecker(), context.preferences, context.program.getCompilerOptions())); return [createCodeFixAction(fixId9, changes, Diagnostics.Convert_function_to_an_ES2015_class, fixId9, Diagnostics.Convert_all_constructor_functions_to_classes)]; }, fixIds: [fixId9], - getAllCodeActions: (context) => codeFixAll(context, errorCodes10, (changes, err) => doChange9(changes, err.file, err.start, context.program.getTypeChecker(), context.preferences, context.program.getCompilerOptions())) + getAllCodeActions: context => codeFixAll(context, errorCodes10, (changes, err) => doChange9(changes, err.file, err.start, context.program.getTypeChecker(), context.preferences, context.program.getCompilerOptions())) }); } }); @@ -146949,7 +132076,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (!functionToConvert) { return; } - const synthNamesMap = /* @__PURE__ */ new Map(); + const synthNamesMap = /* @__PURE__ */new Map(); const isInJavascript = isInJSFile(functionToConvert); const setOfExpressionsToReturn = getAllPromiseExpressionsToReturn(functionToConvert, checker); const functionToConvertRenamed = renameCollidingVarNames(functionToConvert, checker, synthNamesMap); @@ -146957,22 +132084,24 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return; } const returnStatements = functionToConvertRenamed.body && isBlock(functionToConvertRenamed.body) ? getReturnStatementsWithPromiseHandlers(functionToConvertRenamed.body, checker) : emptyArray; - const transformer = { checker, synthNamesMap, setOfExpressionsToReturn, isInJSFile: isInJavascript }; + const transformer = { + checker, + synthNamesMap, + setOfExpressionsToReturn, + isInJSFile: isInJavascript + }; if (!returnStatements.length) { return; } const pos = skipTrivia(sourceFile.text, moveRangePastModifiers(functionToConvert).pos); - changes.insertModifierAt(sourceFile, pos, 134 /* AsyncKeyword */, { suffix: " " }); + changes.insertModifierAt(sourceFile, pos, 134 /* AsyncKeyword */, { + suffix: " " + }); for (const returnStatement of returnStatements) { forEachChild(returnStatement, function visit(node) { if (isCallExpression(node)) { - const newNodes = transformExpression( - node, - node, - transformer, - /*hasContinuation*/ - false - ); + const newNodes = transformExpression(node, node, transformer, /*hasContinuation*/ + false); if (hasFailed()) { return true; } @@ -146991,17 +132120,16 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } function getReturnStatementsWithPromiseHandlers(body, checker) { const res = []; - forEachReturnStatement(body, (ret) => { - if (isReturnStatementWithFixablePromiseHandler(ret, checker)) - res.push(ret); + forEachReturnStatement(body, ret => { + if (isReturnStatementWithFixablePromiseHandler(ret, checker)) res.push(ret); }); return res; } function getAllPromiseExpressionsToReturn(func, checker) { if (!func.body) { - return /* @__PURE__ */ new Set(); + return /* @__PURE__ */new Set(); } - const setOfExpressionsToReturn = /* @__PURE__ */ new Set(); + const setOfExpressionsToReturn = /* @__PURE__ */new Set(); forEachChild(func.body, function visit(node) { if (isPromiseReturningCallExpression(node, checker, "then")) { setOfExpressionsToReturn.add(getNodeId(node)); @@ -147018,8 +132146,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} 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)); @@ -147045,12 +132172,11 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } } 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) { - const identsToRenameMap = /* @__PURE__ */ new Map(); + const identsToRenameMap = /* @__PURE__ */new Map(); const collidingSymbolMap = createMultiMap(); forEachChild(nodeToRename, function visit(node) { if (!isIdentifier(node)) { @@ -147071,7 +132197,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } else if (node.parent && (isParameter(node.parent) || isVariableDeclaration(node.parent) || isBindingElement(node.parent))) { const originalName = node.text; const collidingSymbols = collidingSymbolMap.get(originalName); - if (collidingSymbols && collidingSymbols.some((prevSymbol) => prevSymbol !== symbol)) { + if (collidingSymbols && collidingSymbols.some(prevSymbol => prevSymbol !== symbol)) { const newName = getNewNameIfConflict(node, collidingSymbolMap); identsToRenameMap.set(symbolIdString, newName.identifier); synthNamesMap.set(symbolIdString, newName); @@ -147084,31 +132210,22 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } } }); - return getSynthesizedDeepCloneWithReplacements( - nodeToRename, - /*includeTrivia*/ - true, - (original) => { - if (isBindingElement(original) && isIdentifier(original.name) && isObjectBindingPattern(original.parent)) { - const symbol = checker.getSymbolAtLocation(original.name); - const renameInfo = symbol && identsToRenameMap.get(String(getSymbolId(symbol))); - if (renameInfo && renameInfo.text !== (original.name || original.propertyName).getText()) { - return factory.createBindingElement( - original.dotDotDotToken, - original.propertyName || original.name, - renameInfo, - original.initializer - ); - } - } else if (isIdentifier(original)) { - const symbol = checker.getSymbolAtLocation(original); - const renameInfo = symbol && identsToRenameMap.get(String(getSymbolId(symbol))); - if (renameInfo) { - return factory.createIdentifier(renameInfo.text); - } + return getSynthesizedDeepCloneWithReplacements(nodeToRename, /*includeTrivia*/ + true, original => { + if (isBindingElement(original) && isIdentifier(original.name) && isObjectBindingPattern(original.parent)) { + const symbol = checker.getSymbolAtLocation(original.name); + const renameInfo = symbol && identsToRenameMap.get(String(getSymbolId(symbol))); + if (renameInfo && renameInfo.text !== (original.name || original.propertyName).getText()) { + return factory.createBindingElement(original.dotDotDotToken, original.propertyName || original.name, renameInfo, original.initializer); + } + } else if (isIdentifier(original)) { + const symbol = checker.getSymbolAtLocation(original); + const renameInfo = symbol && identsToRenameMap.get(String(getSymbolId(symbol))); + if (renameInfo) { + return factory.createIdentifier(renameInfo.text); } } - ); + }); } function getNewNameIfConflict(name, originalNames) { const numVarsSameName = (originalNames.get(name.text) || emptyArray).length; @@ -147142,9 +132259,10 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } return silentFail(); } - function isNullOrUndefined2({ checker }, node) { - if (node.kind === 106 /* NullKeyword */) - return true; + function isNullOrUndefined2({ + checker + }, node) { + if (node.kind === 106 /* NullKeyword */) return true; if (isIdentifier(node) && !isGeneratedIdentifier(node) && idText(node) === "undefined") { const symbol = checker.getSymbolAtLocation(node); return !symbol || checker.isUndefinedSymbol(symbol); @@ -147180,125 +132298,63 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} varDeclIdentifier = getSynthesizedDeepClone(declareSynthIdentifier(possibleNameForVarDecl)); const typeArray = possibleNameForVarDecl.types; const unionType = transformer.checker.getUnionType(typeArray, 2 /* Subtype */); - const unionTypeNode = transformer.isInJSFile ? void 0 : transformer.checker.typeToTypeNode( - unionType, - /*enclosingDeclaration*/ - void 0, - /*flags*/ - void 0 - ); - const varDecl = [factory.createVariableDeclaration( - varDeclIdentifier, - /*exclamationToken*/ - void 0, - unionTypeNode - )]; - const varDeclList = factory.createVariableStatement( - /*modifiers*/ - void 0, - factory.createVariableDeclarationList(varDecl, 1 /* Let */) - ); + const unionTypeNode = transformer.isInJSFile ? void 0 : transformer.checker.typeToTypeNode(unionType, /*enclosingDeclaration*/ + void 0, /*flags*/ + void 0); + const varDecl = [factory.createVariableDeclaration(varDeclIdentifier, /*exclamationToken*/ + void 0, unionTypeNode)]; + const varDeclList = factory.createVariableStatement( /*modifiers*/ + void 0, factory.createVariableDeclarationList(varDecl, 1 /* Let */)); + statements.push(varDeclList); } statements.push(tryStatement); if (continuationArgName && varDeclIdentifier && isSynthBindingPattern(continuationArgName)) { - statements.push(factory.createVariableStatement( - /*modifiers*/ - void 0, - factory.createVariableDeclarationList([ - factory.createVariableDeclaration( - getSynthesizedDeepClone(declareSynthBindingPattern(continuationArgName)), - /*exclamationToken*/ - void 0, - /*type*/ - void 0, - varDeclIdentifier - ) - ], 2 /* Const */) - )); + statements.push(factory.createVariableStatement( /*modifiers*/ + void 0, factory.createVariableDeclarationList([factory.createVariableDeclaration(getSynthesizedDeepClone(declareSynthBindingPattern(continuationArgName)), /*exclamationToken*/ + void 0, /*type*/ + void 0, varDeclIdentifier)], 2 /* Const */))); } + return statements; } function transformFinally(node, onFinally, transformer, hasContinuation, continuationArgName) { if (!onFinally || isNullOrUndefined2(transformer, onFinally)) { - return transformExpression( - /* returnContextNode */ - node, - node.expression.expression, - transformer, - hasContinuation, - continuationArgName - ); + return transformExpression( /* returnContextNode */ + node, node.expression.expression, transformer, hasContinuation, continuationArgName); } const possibleNameForVarDecl = getPossibleNameForVarDecl(node, transformer, continuationArgName); - const inlinedLeftHandSide = transformExpression( - /*returnContextNode*/ - node, - node.expression.expression, - transformer, - /*hasContinuation*/ - true, - possibleNameForVarDecl - ); - if (hasFailed()) - return silentFail(); - const inlinedCallback = transformCallbackArgument( - onFinally, - hasContinuation, - /*continuationArgName*/ - void 0, - /*inputArgName*/ - void 0, - node, - transformer - ); - if (hasFailed()) - return silentFail(); + const inlinedLeftHandSide = transformExpression( /*returnContextNode*/ + node, node.expression.expression, transformer, /*hasContinuation*/ + true, possibleNameForVarDecl); + if (hasFailed()) return silentFail(); + const inlinedCallback = transformCallbackArgument(onFinally, hasContinuation, /*continuationArgName*/ + void 0, /*inputArgName*/ + void 0, node, transformer); + if (hasFailed()) return silentFail(); const tryBlock = factory.createBlock(inlinedLeftHandSide); const finallyBlock = factory.createBlock(inlinedCallback); - const tryStatement = factory.createTryStatement( - tryBlock, - /*catchClause*/ - void 0, - finallyBlock - ); + const tryStatement = factory.createTryStatement(tryBlock, /*catchClause*/ + void 0, finallyBlock); return finishCatchOrFinallyTransform(node, transformer, tryStatement, possibleNameForVarDecl, continuationArgName); } function transformCatch(node, onRejected, transformer, hasContinuation, continuationArgName) { if (!onRejected || isNullOrUndefined2(transformer, onRejected)) { - return transformExpression( - /* returnContextNode */ - node, - node.expression.expression, - transformer, - hasContinuation, - continuationArgName - ); + return transformExpression( /* returnContextNode */ + node, node.expression.expression, transformer, hasContinuation, continuationArgName); } const inputArgName = getArgBindingName(onRejected, transformer); const possibleNameForVarDecl = getPossibleNameForVarDecl(node, transformer, continuationArgName); - const inlinedLeftHandSide = transformExpression( - /*returnContextNode*/ - node, - node.expression.expression, - transformer, - /*hasContinuation*/ - true, - possibleNameForVarDecl - ); - if (hasFailed()) - return silentFail(); + const inlinedLeftHandSide = transformExpression( /*returnContextNode*/ + node, node.expression.expression, transformer, /*hasContinuation*/ + true, possibleNameForVarDecl); + if (hasFailed()) return silentFail(); const inlinedCallback = transformCallbackArgument(onRejected, hasContinuation, possibleNameForVarDecl, inputArgName, node, transformer); - if (hasFailed()) - return silentFail(); + if (hasFailed()) return silentFail(); const tryBlock = factory.createBlock(inlinedLeftHandSide); const catchClause = factory.createCatchClause(inputArgName && getSynthesizedDeepClone(declareSynthBindingName(inputArgName)), factory.createBlock(inlinedCallback)); - const tryStatement = factory.createTryStatement( - tryBlock, - catchClause, - /*finallyBlock*/ - void 0 - ); + const tryStatement = factory.createTryStatement(tryBlock, catchClause, /*finallyBlock*/ + void 0); return finishCatchOrFinallyTransform(node, transformer, tryStatement, possibleNameForVarDecl, continuationArgName); } function transformThen(node, onFulfilled, onRejected, transformer, hasContinuation, continuationArgName) { @@ -147309,19 +132365,11 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return silentFail(); } const inputArgName = getArgBindingName(onFulfilled, transformer); - const inlinedLeftHandSide = transformExpression( - node.expression.expression, - node.expression.expression, - transformer, - /*hasContinuation*/ - true, - inputArgName - ); - if (hasFailed()) - return silentFail(); + const inlinedLeftHandSide = transformExpression(node.expression.expression, node.expression.expression, transformer, /*hasContinuation*/ + true, inputArgName); + if (hasFailed()) return silentFail(); const inlinedCallback = transformCallbackArgument(onFulfilled, hasContinuation, continuationArgName, inputArgName, node, transformer); - if (hasFailed()) - return silentFail(); + if (hasFailed()) return silentFail(); return concatenate(inlinedLeftHandSide, inlinedCallback); } function transformPromiseExpressionOfPropertyAccess(returnContextNode, node, transformer, hasContinuation, continuationArgName) { @@ -147332,12 +132380,8 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } return [factory.createReturnStatement(returnValue)]; } - return createVariableOrAssignmentOrExpressionStatement( - continuationArgName, - factory.createAwaitExpression(node), - /*typeAnnotation*/ - void 0 - ); + return createVariableOrAssignmentOrExpressionStatement(continuationArgName, factory.createAwaitExpression(node), /*typeAnnotation*/ + void 0); } function createVariableOrAssignmentOrExpressionStatement(variableName, rightHandSide, typeAnnotation) { if (!variableName || isEmptyBindingName(variableName)) { @@ -147346,29 +132390,15 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (isSynthIdentifier(variableName) && variableName.hasBeenDeclared) { return [factory.createExpressionStatement(factory.createAssignment(getSynthesizedDeepClone(referenceSynthIdentifier(variableName)), rightHandSide))]; } - return [ - factory.createVariableStatement( - /*modifiers*/ - void 0, - factory.createVariableDeclarationList([ - factory.createVariableDeclaration( - getSynthesizedDeepClone(declareSynthBindingName(variableName)), - /*exclamationToken*/ - void 0, - typeAnnotation, - rightHandSide - ) - ], 2 /* Const */) - ) - ]; + return [factory.createVariableStatement( /*modifiers*/ + void 0, factory.createVariableDeclarationList([factory.createVariableDeclaration(getSynthesizedDeepClone(declareSynthBindingName(variableName)), /*exclamationToken*/ + void 0, typeAnnotation, rightHandSide)], 2 /* Const */))]; } + function maybeAnnotateAndReturn(expressionToReturn, typeAnnotation) { if (typeAnnotation && expressionToReturn) { const name = factory.createUniqueName("result", 16 /* Optimistic */); - return [ - ...createVariableOrAssignmentOrExpressionStatement(createSynthIdentifier(name), expressionToReturn, typeAnnotation), - factory.createReturnStatement(name) - ]; + return [...createVariableOrAssignmentOrExpressionStatement(createSynthIdentifier(name), expressionToReturn, typeAnnotation), factory.createReturnStatement(name)]; } return [factory.createReturnStatement(expressionToReturn)]; } @@ -147382,12 +132412,8 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (!inputArgName) { break; } - const synthCall = factory.createCallExpression( - getSynthesizedDeepClone(func), - /*typeArguments*/ - void 0, - isSynthIdentifier(inputArgName) ? [referenceSynthIdentifier(inputArgName)] : [] - ); + const synthCall = factory.createCallExpression(getSynthesizedDeepClone(func), /*typeArguments*/ + void 0, isSynthIdentifier(inputArgName) ? [referenceSynthIdentifier(inputArgName)] : []); if (shouldReturn(parent2, transformer)) { return maybeAnnotateAndReturn(synthCall, getExplicitPromisedTypeOfPromiseReturningCallExpression(parent2, func, transformer.checker)); } @@ -147403,59 +132429,51 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } return varDeclOrAssignment; case 218 /* FunctionExpression */: - case 219 /* ArrowFunction */: { - const funcBody = func.body; - const returnType2 = (_a = getLastCallSignature(transformer.checker.getTypeAtLocation(func), transformer.checker)) == null ? void 0 : _a.getReturnType(); - if (isBlock(funcBody)) { - let refactoredStmts = []; - let seenReturnStatement = false; - for (const statement of funcBody.statements) { - if (isReturnStatement(statement)) { - seenReturnStatement = true; - if (isReturnStatementWithFixablePromiseHandler(statement, transformer.checker)) { - refactoredStmts = refactoredStmts.concat(transformReturnStatementWithFixablePromiseHandler(transformer, statement, hasContinuation, continuationArgName)); + case 219 /* ArrowFunction */: + { + const funcBody = func.body; + const returnType2 = (_a = getLastCallSignature(transformer.checker.getTypeAtLocation(func), transformer.checker)) == null ? void 0 : _a.getReturnType(); + if (isBlock(funcBody)) { + let refactoredStmts = []; + let seenReturnStatement = false; + for (const statement of funcBody.statements) { + if (isReturnStatement(statement)) { + seenReturnStatement = true; + if (isReturnStatementWithFixablePromiseHandler(statement, transformer.checker)) { + refactoredStmts = refactoredStmts.concat(transformReturnStatementWithFixablePromiseHandler(transformer, statement, hasContinuation, continuationArgName)); + } else { + const possiblyAwaitedRightHandSide = returnType2 && statement.expression ? getPossiblyAwaitedRightHandSide(transformer.checker, returnType2, statement.expression) : statement.expression; + refactoredStmts.push(...maybeAnnotateAndReturn(possiblyAwaitedRightHandSide, getExplicitPromisedTypeOfPromiseReturningCallExpression(parent2, func, transformer.checker))); + } + } else if (hasContinuation && forEachReturnStatement(statement, returnTrue)) { + return silentFail(); } else { - const possiblyAwaitedRightHandSide = returnType2 && statement.expression ? getPossiblyAwaitedRightHandSide(transformer.checker, returnType2, statement.expression) : statement.expression; - refactoredStmts.push(...maybeAnnotateAndReturn(possiblyAwaitedRightHandSide, getExplicitPromisedTypeOfPromiseReturningCallExpression(parent2, func, transformer.checker))); + refactoredStmts.push(statement); } - } else if (hasContinuation && forEachReturnStatement(statement, returnTrue)) { - return silentFail(); - } else { - refactoredStmts.push(statement); - } - } - return shouldReturn(parent2, transformer) ? refactoredStmts.map((s) => getSynthesizedDeepClone(s)) : removeReturns( - refactoredStmts, - continuationArgName, - transformer, - seenReturnStatement - ); - } else { - const inlinedStatements = isFixablePromiseHandler(funcBody, transformer.checker) ? transformReturnStatementWithFixablePromiseHandler(transformer, factory.createReturnStatement(funcBody), hasContinuation, continuationArgName) : emptyArray; - if (inlinedStatements.length > 0) { - return inlinedStatements; - } - if (returnType2) { - const possiblyAwaitedRightHandSide = getPossiblyAwaitedRightHandSide(transformer.checker, returnType2, funcBody); - if (!shouldReturn(parent2, transformer)) { - const transformedStatement = createVariableOrAssignmentOrExpressionStatement( - continuationArgName, - possiblyAwaitedRightHandSide, - /*typeAnnotation*/ - void 0 - ); - if (continuationArgName) { - continuationArgName.types.push(transformer.checker.getAwaitedType(returnType2) || returnType2); - } - return transformedStatement; - } else { - return maybeAnnotateAndReturn(possiblyAwaitedRightHandSide, getExplicitPromisedTypeOfPromiseReturningCallExpression(parent2, func, transformer.checker)); } + return shouldReturn(parent2, transformer) ? refactoredStmts.map(s => getSynthesizedDeepClone(s)) : removeReturns(refactoredStmts, continuationArgName, transformer, seenReturnStatement); } else { - return silentFail(); + const inlinedStatements = isFixablePromiseHandler(funcBody, transformer.checker) ? transformReturnStatementWithFixablePromiseHandler(transformer, factory.createReturnStatement(funcBody), hasContinuation, continuationArgName) : emptyArray; + if (inlinedStatements.length > 0) { + return inlinedStatements; + } + if (returnType2) { + const possiblyAwaitedRightHandSide = getPossiblyAwaitedRightHandSide(transformer.checker, returnType2, funcBody); + if (!shouldReturn(parent2, transformer)) { + const transformedStatement = createVariableOrAssignmentOrExpressionStatement(continuationArgName, possiblyAwaitedRightHandSide, /*typeAnnotation*/ + void 0); + if (continuationArgName) { + continuationArgName.types.push(transformer.checker.getAwaitedType(returnType2) || returnType2); + } + return transformedStatement; + } else { + return maybeAnnotateAndReturn(possiblyAwaitedRightHandSide, getExplicitPromisedTypeOfPromiseReturningCallExpression(parent2, func, transformer.checker)); + } + } else { + return silentFail(); + } } } - } default: return silentFail(); } @@ -147480,18 +132498,10 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } else if (isSynthIdentifier(prevArgName) && prevArgName.hasBeenDeclared) { ret.push(factory.createExpressionStatement(factory.createAssignment(referenceSynthIdentifier(prevArgName), possiblyAwaitedExpression))); } else { - ret.push(factory.createVariableStatement( - /*modifiers*/ - void 0, - factory.createVariableDeclarationList([factory.createVariableDeclaration( - declareSynthBindingName(prevArgName), - /*exclamationToken*/ - void 0, - /*type*/ - void 0, - possiblyAwaitedExpression - )], 2 /* Const */) - )); + ret.push(factory.createVariableStatement( /*modifiers*/ + void 0, factory.createVariableDeclarationList([factory.createVariableDeclaration(declareSynthBindingName(prevArgName), /*exclamationToken*/ + void 0, /*type*/ + void 0, possiblyAwaitedExpression)], 2 /* Const */))); } } } else { @@ -147499,19 +132509,12 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } } if (!seenReturnStatement && prevArgName !== void 0) { - ret.push(factory.createVariableStatement( - /*modifiers*/ - void 0, - factory.createVariableDeclarationList([factory.createVariableDeclaration( - declareSynthBindingName(prevArgName), - /*exclamationToken*/ - void 0, - /*type*/ - void 0, - factory.createIdentifier("undefined") - )], 2 /* Const */) - )); + ret.push(factory.createVariableStatement( /*modifiers*/ + void 0, factory.createVariableDeclarationList([factory.createVariableDeclaration(declareSynthBindingName(prevArgName), /*exclamationToken*/ + void 0, /*type*/ + void 0, factory.createIdentifier("undefined"))], 2 /* Const */))); } + return ret; } function transformReturnStatementWithFixablePromiseHandler(transformer, innerRetStmt, hasContinuation, continuationArgName) { @@ -147547,11 +132550,9 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } return name; function getMappedBindingNameOrDefault(bindingName) { - if (isIdentifier(bindingName)) - return getMapEntryOrDefault(bindingName); - const elements = flatMap(bindingName.elements, (element) => { - if (isOmittedExpression(element)) - return []; + if (isIdentifier(bindingName)) return getMapEntryOrDefault(bindingName); + const elements = flatMap(bindingName.elements, element => { + if (isOmittedExpression(element)) return []; return [getMappedBindingNameOrDefault(element.name)]; }); return createSynthBindingPattern(bindingName, elements); @@ -147566,8 +132567,9 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return mapEntry || createSynthIdentifier(identifier, types); } function getSymbol2(node) { + var _ref43; var _a; - return ((_a = tryCast(node, canHaveSymbol)) == null ? void 0 : _a.symbol) ?? transformer.checker.getSymbolAtLocation(node); + return (_ref43 = (_a = tryCast(node, canHaveSymbol)) == null ? void 0 : _a.symbol) !== null && _ref43 !== void 0 ? _ref43 : transformer.checker.getSymbolAtLocation(node); } function getOriginalNode2(node) { return node.original ? node.original : node; @@ -147583,10 +132585,21 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return every(bindingName.elements, isEmptyBindingName); } function createSynthIdentifier(identifier, types = []) { - return { kind: 0 /* Identifier */, identifier, types, hasBeenDeclared: false, hasBeenReferenced: false }; + return { + kind: 0 /* Identifier */, + identifier, + types, + hasBeenDeclared: false, + hasBeenReferenced: false + }; } function createSynthBindingPattern(bindingPattern, elements = emptyArray, types = []) { - return { kind: 1 /* BindingPattern */, bindingPattern, elements, types }; + return { + kind: 1 /* BindingPattern */, + bindingPattern, + elements, + types + }; } function referenceSynthIdentifier(synthId) { synthId.hasBeenReferenced = true; @@ -147608,9 +132621,11 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} function isSynthIdentifier(bindingName) { return bindingName.kind === 0 /* Identifier */; } + function isSynthBindingPattern(bindingName) { return bindingName.kind === 1 /* BindingPattern */; } + function shouldReturn(expression, transformer) { return !!expression.original && transformer.setOfExpressionsToReturn.has(getNodeId(expression.original)); } @@ -147618,6 +132633,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} var init_convertToAsyncFunction = __esm({ "src/services/codefixes/convertToAsyncFunction.ts"() { "use strict"; + init_ts4(); init_ts_codefix(); fixId10 = "convertToAsyncFunction"; @@ -147627,11 +132643,11 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} errorCodes: errorCodes11, getCodeActions(context) { codeActionSucceeded = true; - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => convertToAsyncFunction(t, context.sourceFile, context.span.start, context.program.getTypeChecker())); + const changes = ts_textChanges_exports.ChangeTracker.with(context, t => convertToAsyncFunction(t, context.sourceFile, context.span.start, context.program.getTypeChecker())); return codeActionSucceeded ? [createCodeFixAction(fixId10, changes, Diagnostics.Convert_to_async_function, fixId10, Diagnostics.Convert_all_to_async_functions)] : []; }, fixIds: [fixId10], - getAllCodeActions: (context) => codeFixAll(context, errorCodes11, (changes, err) => convertToAsyncFunction(changes, err.file, err.start, context.program.getTypeChecker())) + getAllCodeActions: context => codeFixAll(context, errorCodes11, (changes, err) => convertToAsyncFunction(changes, err.file, err.start, context.program.getTypeChecker())) }); } }); @@ -147647,20 +132663,12 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} const importNode = importFromModuleSpecifier(moduleSpecifier); switch (importNode.kind) { case 271 /* ImportEqualsDeclaration */: - changes.replaceNode(importingFile, importNode, makeImport( - importNode.name, - /*namedImports*/ - void 0, - moduleSpecifier, - quotePreference - )); + changes.replaceNode(importingFile, importNode, makeImport(importNode.name, /*namedImports*/ + void 0, moduleSpecifier, quotePreference)); break; case 213 /* CallExpression */: - if (isRequireCall( - importNode, - /*requireStringLiteralLikeArgument*/ - false - )) { + if (isRequireCall(importNode, /*requireStringLiteralLikeArgument*/ + false)) { changes.replaceNode(importingFile, importNode, factory.createPropertyAccessExpression(getSynthesizedDeepClone(importNode), "default")); } break; @@ -147668,7 +132676,10 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } } function convertFileToEsModule(sourceFile, checker, changes, target, quotePreference) { - const identifiers = { original: collectFreeIdentifiers(sourceFile), additional: /* @__PURE__ */ new Set() }; + const identifiers = { + original: collectFreeIdentifiers(sourceFile), + additional: /* @__PURE__ */new Set() + }; const exports = collectExportRenames(sourceFile, checker, identifiers); convertExportsAccesses(sourceFile, exports, changes); let moduleExportsChangedToDefault = false; @@ -147676,10 +132687,11 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} for (const statement of filter(sourceFile.statements, isVariableStatement)) { const newUseSites = convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target, quotePreference); if (newUseSites) { - copyEntries(newUseSites, useSitesToUnqualify ?? (useSitesToUnqualify = /* @__PURE__ */ new Map())); + var _useSitesToUnqualify; + copyEntries(newUseSites, (_useSitesToUnqualify = useSitesToUnqualify) !== null && _useSitesToUnqualify !== void 0 ? _useSitesToUnqualify : useSitesToUnqualify = /* @__PURE__ */new Map()); } } - for (const statement of filter(sourceFile.statements, (s) => !isVariableStatement(s))) { + for (const statement of filter(sourceFile.statements, s => !isVariableStatement(s))) { const moduleExportsChanged = convertStatement(sourceFile, statement, checker, changes, identifiers, target, exports, useSitesToUnqualify, quotePreference); moduleExportsChangedToDefault = moduleExportsChangedToDefault || moduleExportsChanged; } @@ -147689,16 +132701,13 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return moduleExportsChangedToDefault; } function collectExportRenames(sourceFile, checker, identifiers) { - const res = /* @__PURE__ */ new Map(); - forEachExportReference(sourceFile, (node) => { - const { text } = node.name; - if (!res.has(text) && (isIdentifierANonContextualKeyword(node.name) || checker.resolveName( - text, - node, - 111551 /* Value */, - /*excludeGlobals*/ - true - ))) { + const res = /* @__PURE__ */new Map(); + forEachExportReference(sourceFile, node => { + const { + text + } = node.name; + if (!res.has(text) && (isIdentifierANonContextualKeyword(node.name) || checker.resolveName(text, node, 111551 /* Value */, /*excludeGlobals*/ + true))) { res.set(text, makeUniqueName(`_${text}`, identifiers)); } }); @@ -147709,16 +132718,21 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (isAssignmentLhs) { return; } - const { text } = node.name; + const { + text + } = node.name; changes.replaceNode(sourceFile, node, factory.createIdentifier(exports.get(text) || text)); }); } function forEachExportReference(sourceFile, cb) { sourceFile.forEachChild(function recur(node) { if (isPropertyAccessExpression(node) && isExportsOrModuleExportsOrAlias(sourceFile, node.expression) && isIdentifier(node.name)) { - const { parent: parent2 } = node; + const { + parent: parent2 + } = node; cb(node, isBinaryExpression(parent2) && parent2.left === node && parent2.operatorToken.kind === 64 /* EqualsToken */); } + node.forEachChild(recur); }); } @@ -147727,73 +132741,69 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} case 243 /* VariableStatement */: convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target, quotePreference); return false; - case 244 /* ExpressionStatement */: { - const { expression } = statement; - switch (expression.kind) { - case 213 /* CallExpression */: { - if (isRequireCall( - expression, - /*requireStringLiteralLikeArgument*/ - true - )) { - changes.replaceNode(sourceFile, statement, makeImport( - /*defaultImport*/ - void 0, - /*namedImports*/ - void 0, - expression.arguments[0], - quotePreference - )); - } - return false; - } - case 226 /* BinaryExpression */: { - const { operatorToken } = expression; - return operatorToken.kind === 64 /* EqualsToken */ && convertAssignment(sourceFile, checker, expression, changes, exports, useSitesToUnqualify); + case 244 /* ExpressionStatement */: + { + const { + expression + } = statement; + switch (expression.kind) { + case 213 /* CallExpression */: + { + if (isRequireCall(expression, /*requireStringLiteralLikeArgument*/ + true)) { + changes.replaceNode(sourceFile, statement, makeImport( /*defaultImport*/ + void 0, /*namedImports*/ + void 0, expression.arguments[0], quotePreference)); + } + return false; + } + case 226 /* BinaryExpression */: + { + const { + operatorToken + } = expression; + return operatorToken.kind === 64 /* EqualsToken */ && convertAssignment(sourceFile, checker, expression, changes, exports, useSitesToUnqualify); + } } } - } default: return false; } } function convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target, quotePreference) { - const { declarationList } = statement; + const { + declarationList + } = statement; let foundImport = false; - const converted = map(declarationList.declarations, (decl) => { - const { name, initializer } = decl; + const converted = map(declarationList.declarations, decl => { + const { + name, + initializer + } = decl; if (initializer) { if (isExportsOrModuleExportsOrAlias(sourceFile, initializer)) { foundImport = true; return convertedImports([]); - } else if (isRequireCall( - initializer, - /*requireStringLiteralLikeArgument*/ - true - )) { + } else if (isRequireCall(initializer, /*requireStringLiteralLikeArgument*/ + true)) { foundImport = true; return convertSingleImport(name, initializer.arguments[0], checker, identifiers, target, quotePreference); - } else if (isPropertyAccessExpression(initializer) && isRequireCall( - initializer.expression, - /*requireStringLiteralLikeArgument*/ - true - )) { + } else if (isPropertyAccessExpression(initializer) && isRequireCall(initializer.expression, /*requireStringLiteralLikeArgument*/ + true)) { foundImport = true; return convertPropertyAccessImport(name, initializer.name.text, initializer.expression.arguments[0], identifiers, quotePreference); } } - return convertedImports([factory.createVariableStatement( - /*modifiers*/ - void 0, - factory.createVariableDeclarationList([decl], declarationList.flags) - )]); + return convertedImports([factory.createVariableStatement( /*modifiers*/ + void 0, factory.createVariableDeclarationList([decl], declarationList.flags))]); }); if (foundImport) { - changes.replaceNodeWithNodes(sourceFile, statement, flatMap(converted, (c) => c.newImports)); + changes.replaceNodeWithNodes(sourceFile, statement, flatMap(converted, c => c.newImports)); let combinedUseSites; - forEach(converted, (c) => { + forEach(converted, c => { if (c.useSitesToUnqualify) { - copyEntries(c.useSitesToUnqualify, combinedUseSites ?? (combinedUseSites = /* @__PURE__ */ new Map())); + var _combinedUseSites; + copyEntries(c.useSitesToUnqualify, (_combinedUseSites = combinedUseSites) !== null && _combinedUseSites !== void 0 ? _combinedUseSites : combinedUseSites = /* @__PURE__ */new Map()); } }); return combinedUseSites; @@ -147802,18 +132812,12 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} function convertPropertyAccessImport(name, propertyName, moduleSpecifier, identifiers, quotePreference) { switch (name.kind) { case 206 /* ObjectBindingPattern */: - case 207 /* ArrayBindingPattern */: { - const tmp = makeUniqueName(propertyName, identifiers); - return convertedImports([ - makeSingleImport(tmp, propertyName, moduleSpecifier, quotePreference), - makeConst( - /*modifiers*/ - void 0, - name, - factory.createIdentifier(tmp) - ) - ]); - } + case 207 /* ArrayBindingPattern */: + { + const tmp = makeUniqueName(propertyName, identifiers); + return convertedImports([makeSingleImport(tmp, propertyName, moduleSpecifier, quotePreference), makeConst( /*modifiers*/ + void 0, name, factory.createIdentifier(tmp))]); + } case 80 /* Identifier */: return convertedImports([makeSingleImport(name.text, propertyName, moduleSpecifier, quotePreference)]); default: @@ -147821,7 +132825,10 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } } function convertAssignment(sourceFile, checker, assignment, changes, exports, useSitesToUnqualify) { - const { left, right } = assignment; + const { + left, + right + } = assignment; if (!isPropertyAccessExpression(left)) { return false; } @@ -147829,11 +132836,8 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (isExportsOrModuleExportsOrAlias(sourceFile, right)) { changes.delete(sourceFile, assignment.parent); } else { - const replacement = isObjectLiteralExpression(right) ? tryChangeModuleExportsObject(right, useSitesToUnqualify) : isRequireCall( - right, - /*requireStringLiteralLikeArgument*/ - true - ) ? convertReExportAll(right.arguments[0], checker) : void 0; + const replacement = isObjectLiteralExpression(right) ? tryChangeModuleExportsObject(right, useSitesToUnqualify) : isRequireCall(right, /*requireStringLiteralLikeArgument*/ + true) ? convertReExportAll(right.arguments[0], checker) : void 0; if (replacement) { changes.replaceNodeWithNodes(sourceFile, assignment.parent, replacement[0]); return replacement[1]; @@ -147848,7 +132852,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return false; } function tryChangeModuleExportsObject(object, useSitesToUnqualify) { - const statements = mapAllOrFail(object.properties, (prop) => { + const statements = mapAllOrFail(object.properties, prop => { switch (prop.kind) { case 177 /* GetAccessor */: case 178 /* SetAccessor */: @@ -147866,23 +132870,14 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return statements && [statements, false]; } function convertNamedExport(sourceFile, assignment, changes, exports) { - const { text } = assignment.left.name; + const { + text + } = assignment.left.name; const rename = exports.get(text); if (rename !== void 0) { - const newNodes = [ - makeConst( - /*modifiers*/ - void 0, - rename, - assignment.right - ), - makeExportDeclaration([factory.createExportSpecifier( - /*isTypeOnly*/ - false, - rename, - text - )]) - ]; + const newNodes = [makeConst( /*modifiers*/ + void 0, rename, assignment.right), makeExportDeclaration([factory.createExportSpecifier( /*isTypeOnly*/ + false, rename, text)])]; changes.replaceNodeWithNodes(sourceFile, assignment.parent, newNodes); } else { convertExportsPropertyAssignment(assignment, sourceFile, changes); @@ -147892,49 +132887,54 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} const moduleSpecifier = reExported.text; const moduleSymbol = checker.getSymbolAtLocation(reExported); const exports = moduleSymbol ? moduleSymbol.exports : emptyMap; - return exports.has("export=" /* ExportEquals */) ? [[reExportDefault(moduleSpecifier)], true] : !exports.has("default" /* Default */) ? [[reExportStar(moduleSpecifier)], false] : ( - // If there's some non-default export, must include both `export *` and `export default`. - exports.size > 1 ? [[reExportStar(moduleSpecifier), reExportDefault(moduleSpecifier)], true] : [[reExportDefault(moduleSpecifier)], true] - ); + return exports.has("export=" /* ExportEquals */) ? [[reExportDefault(moduleSpecifier)], true] : !exports.has("default" /* Default */) ? [[reExportStar(moduleSpecifier)], false] : + // If there's some non-default export, must include both `export *` and `export default`. + exports.size > 1 ? [[reExportStar(moduleSpecifier), reExportDefault(moduleSpecifier)], true] : [[reExportDefault(moduleSpecifier)], true]; } function reExportStar(moduleSpecifier) { - return makeExportDeclaration( - /*exportSpecifiers*/ - void 0, - moduleSpecifier - ); + return makeExportDeclaration( /*exportSpecifiers*/ + void 0, moduleSpecifier); } function reExportDefault(moduleSpecifier) { - return makeExportDeclaration([factory.createExportSpecifier( - /*isTypeOnly*/ - false, - /*propertyName*/ - void 0, - "default" - )], moduleSpecifier); + return makeExportDeclaration([factory.createExportSpecifier( /*isTypeOnly*/ + false, /*propertyName*/ + void 0, "default")], moduleSpecifier); } - function convertExportsPropertyAssignment({ left, right, parent: parent2 }, sourceFile, changes) { + function convertExportsPropertyAssignment({ + left, + right, + parent: parent2 + }, sourceFile, changes) { const name = left.name.text; if ((isFunctionExpression(right) || isArrowFunction(right) || isClassExpression(right)) && (!right.name || right.name.text === name)) { - changes.replaceRange(sourceFile, { pos: left.getStart(sourceFile), end: right.getStart(sourceFile) }, factory.createToken(95 /* ExportKeyword */), { suffix: " " }); - if (!right.name) - changes.insertName(sourceFile, right, 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); 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: " " }); + changes.replaceNodeRangeWithNodes(sourceFile, left.expression, findChildOfKind(left, 25 /* DotToken */, sourceFile), [factory.createToken(95 /* ExportKeyword */), factory.createToken(87 /* ConstKeyword */)], { + joiner: " ", + suffix: " " + }); } } function convertExportsDotXEquals_replaceNode(name, exported, useSitesToUnqualify) { const modifiers = [factory.createToken(95 /* ExportKeyword */)]; switch (exported.kind) { - case 218 /* FunctionExpression */: { - const { name: expressionName } = exported; - if (expressionName && expressionName.text !== name) { - return exportConst(); + case 218 /* FunctionExpression */: + { + const { + name: expressionName + } = exported; + if (expressionName && expressionName.text !== name) { + return exportConst(); + } } - } case 219 /* ArrowFunction */: return functionExpressionToDeclaration(name, modifiers, exported, useSitesToUnqualify); case 231 /* ClassExpression */: @@ -147947,20 +132947,12 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } } function replaceImportUseSites(nodeOrNodes, useSitesToUnqualify) { - if (!useSitesToUnqualify || !some(arrayFrom(useSitesToUnqualify.keys()), (original) => rangeContainsRange(nodeOrNodes, original))) { + if (!useSitesToUnqualify || !some(arrayFrom(useSitesToUnqualify.keys()), original => rangeContainsRange(nodeOrNodes, original))) { return nodeOrNodes; } - return isArray(nodeOrNodes) ? getSynthesizedDeepClonesWithReplacements( - nodeOrNodes, - /*includeTrivia*/ - true, - replaceNode - ) : getSynthesizedDeepCloneWithReplacements( - nodeOrNodes, - /*includeTrivia*/ - true, - replaceNode - ); + return isArray(nodeOrNodes) ? getSynthesizedDeepClonesWithReplacements(nodeOrNodes, /*includeTrivia*/ + true, replaceNode) : getSynthesizedDeepCloneWithReplacements(nodeOrNodes, /*includeTrivia*/ + true, replaceNode); function replaceNode(original) { if (original.kind === 211 /* PropertyAccessExpression */) { const replacement = useSitesToUnqualify.get(original); @@ -147971,36 +132963,21 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } function convertSingleImport(name, moduleSpecifier, checker, identifiers, target, quotePreference) { switch (name.kind) { - case 206 /* ObjectBindingPattern */: { - const importSpecifiers = mapAllOrFail(name.elements, (e) => e.dotDotDotToken || e.initializer || e.propertyName && !isIdentifier(e.propertyName) || !isIdentifier(e.name) ? void 0 : makeImportSpecifier2(e.propertyName && e.propertyName.text, e.name.text)); - if (importSpecifiers) { - return convertedImports([makeImport( - /*defaultImport*/ - void 0, - importSpecifiers, - moduleSpecifier, - quotePreference - )]); + case 206 /* ObjectBindingPattern */: + { + const importSpecifiers = mapAllOrFail(name.elements, e => e.dotDotDotToken || e.initializer || e.propertyName && !isIdentifier(e.propertyName) || !isIdentifier(e.name) ? void 0 : makeImportSpecifier2(e.propertyName && e.propertyName.text, e.name.text)); + if (importSpecifiers) { + return convertedImports([makeImport( /*defaultImport*/ + void 0, importSpecifiers, moduleSpecifier, quotePreference)]); + } + } + case 207 /* ArrayBindingPattern */: + { + const tmp = makeUniqueName(moduleSpecifierToValidIdentifier(moduleSpecifier.text, target), identifiers); + return convertedImports([makeImport(factory.createIdentifier(tmp), /*namedImports*/ + void 0, moduleSpecifier, quotePreference), makeConst( /*modifiers*/ + void 0, getSynthesizedDeepClone(name), factory.createIdentifier(tmp))]); } - } - case 207 /* ArrayBindingPattern */: { - const tmp = makeUniqueName(moduleSpecifierToValidIdentifier(moduleSpecifier.text, target), identifiers); - return convertedImports([ - makeImport( - factory.createIdentifier(tmp), - /*namedImports*/ - void 0, - moduleSpecifier, - quotePreference - ), - makeConst( - /*modifiers*/ - void 0, - getSynthesizedDeepClone(name), - factory.createIdentifier(tmp) - ) - ]); - } case 80 /* Identifier */: return convertSingleIdentifierImport(name, moduleSpecifier, checker, identifiers, quotePreference); default: @@ -148009,46 +132986,47 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } function convertSingleIdentifierImport(name, moduleSpecifier, checker, identifiers, quotePreference) { const nameSymbol = checker.getSymbolAtLocation(name); - const namedBindingsNames = /* @__PURE__ */ new Map(); + const namedBindingsNames = /* @__PURE__ */new Map(); let needDefaultImport = false; let useSitesToUnqualify; for (const use of identifiers.original.get(name.text)) { if (checker.getSymbolAtLocation(use) !== nameSymbol || use === name) { continue; } - const { parent: parent2 } = use; + const { + parent: parent2 + } = use; if (isPropertyAccessExpression(parent2)) { - const { name: { text: propertyName } } = parent2; + const { + name: { + text: propertyName + } + } = parent2; if (propertyName === "default") { + var _useSitesToUnqualify2; needDefaultImport = true; const importDefaultName = use.getText(); - (useSitesToUnqualify ?? (useSitesToUnqualify = /* @__PURE__ */ new Map())).set(parent2, factory.createIdentifier(importDefaultName)); + ((_useSitesToUnqualify2 = useSitesToUnqualify) !== null && _useSitesToUnqualify2 !== void 0 ? _useSitesToUnqualify2 : useSitesToUnqualify = /* @__PURE__ */new Map()).set(parent2, factory.createIdentifier(importDefaultName)); } else { + var _useSitesToUnqualify3; Debug.assert(parent2.expression === use, "Didn't expect expression === use"); let idName = namedBindingsNames.get(propertyName); if (idName === void 0) { idName = makeUniqueName(propertyName, identifiers); namedBindingsNames.set(propertyName, idName); } - (useSitesToUnqualify ?? (useSitesToUnqualify = /* @__PURE__ */ new Map())).set(parent2, factory.createIdentifier(idName)); + ((_useSitesToUnqualify3 = useSitesToUnqualify) !== null && _useSitesToUnqualify3 !== void 0 ? _useSitesToUnqualify3 : useSitesToUnqualify = /* @__PURE__ */new Map()).set(parent2, factory.createIdentifier(idName)); } } else { needDefaultImport = true; } } - const namedBindings = namedBindingsNames.size === 0 ? void 0 : arrayFrom(mapIterator(namedBindingsNames.entries(), ([propertyName, idName]) => factory.createImportSpecifier( - /*isTypeOnly*/ - false, - propertyName === idName ? void 0 : factory.createIdentifier(propertyName), - factory.createIdentifier(idName) - ))); + const namedBindings = namedBindingsNames.size === 0 ? void 0 : arrayFrom(mapIterator(namedBindingsNames.entries(), ([propertyName, idName]) => factory.createImportSpecifier( /*isTypeOnly*/ + false, propertyName === idName ? void 0 : factory.createIdentifier(propertyName), factory.createIdentifier(idName)))); if (!namedBindings) { needDefaultImport = true; } - return convertedImports( - [makeImport(needDefaultImport ? getSynthesizedDeepClone(name) : void 0, namedBindings, moduleSpecifier, quotePreference)], - useSitesToUnqualify - ); + return convertedImports([makeImport(needDefaultImport ? getSynthesizedDeepClone(name) : void 0, namedBindings, moduleSpecifier, quotePreference)], useSitesToUnqualify); } function makeUniqueName(name, identifiers) { while (identifiers.original.has(name) || identifiers.additional.has(name)) { @@ -148059,16 +133037,17 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } function collectFreeIdentifiers(file) { const map2 = createMultiMap(); - forEachFreeIdentifier(file, (id) => map2.add(id.text, id)); + forEachFreeIdentifier(file, id => map2.add(id.text, id)); return map2; } function forEachFreeIdentifier(node, cb) { - if (isIdentifier(node) && isFreeIdentifier(node)) - cb(node); - node.forEachChild((child) => forEachFreeIdentifier(child, cb)); + if (isIdentifier(node) && isFreeIdentifier(node)) cb(node); + node.forEachChild(child => forEachFreeIdentifier(child, cb)); } function isFreeIdentifier(node) { - const { parent: parent2 } = node; + const { + parent: parent2 + } = node; switch (parent2.kind) { case 211 /* PropertyAccessExpression */: return parent2.name !== node; @@ -148081,73 +133060,30 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } } function functionExpressionToDeclaration(name, additionalModifiers, fn, useSitesToUnqualify) { - return factory.createFunctionDeclaration( - concatenate(additionalModifiers, getSynthesizedDeepClones(fn.modifiers)), - getSynthesizedDeepClone(fn.asteriskToken), - name, - getSynthesizedDeepClones(fn.typeParameters), - getSynthesizedDeepClones(fn.parameters), - getSynthesizedDeepClone(fn.type), - factory.converters.convertToFunctionBlock(replaceImportUseSites(fn.body, useSitesToUnqualify)) - ); + return factory.createFunctionDeclaration(concatenate(additionalModifiers, getSynthesizedDeepClones(fn.modifiers)), getSynthesizedDeepClone(fn.asteriskToken), name, getSynthesizedDeepClones(fn.typeParameters), getSynthesizedDeepClones(fn.parameters), getSynthesizedDeepClone(fn.type), factory.converters.convertToFunctionBlock(replaceImportUseSites(fn.body, useSitesToUnqualify))); } function classExpressionToDeclaration(name, additionalModifiers, cls, useSitesToUnqualify) { - return factory.createClassDeclaration( - concatenate(additionalModifiers, getSynthesizedDeepClones(cls.modifiers)), - name, - getSynthesizedDeepClones(cls.typeParameters), - getSynthesizedDeepClones(cls.heritageClauses), - replaceImportUseSites(cls.members, useSitesToUnqualify) - ); + return factory.createClassDeclaration(concatenate(additionalModifiers, getSynthesizedDeepClones(cls.modifiers)), name, getSynthesizedDeepClones(cls.typeParameters), getSynthesizedDeepClones(cls.heritageClauses), replaceImportUseSites(cls.members, useSitesToUnqualify)); } function makeSingleImport(localName, propertyName, moduleSpecifier, quotePreference) { - return propertyName === "default" ? makeImport( - factory.createIdentifier(localName), - /*namedImports*/ - void 0, - moduleSpecifier, - quotePreference - ) : makeImport( - /*defaultImport*/ - void 0, - [makeImportSpecifier2(propertyName, localName)], - moduleSpecifier, - quotePreference - ); + return propertyName === "default" ? makeImport(factory.createIdentifier(localName), /*namedImports*/ + void 0, moduleSpecifier, quotePreference) : makeImport( /*defaultImport*/ + void 0, [makeImportSpecifier2(propertyName, localName)], moduleSpecifier, quotePreference); } function makeImportSpecifier2(propertyName, name) { - return factory.createImportSpecifier( - /*isTypeOnly*/ - false, - propertyName !== void 0 && propertyName !== name ? factory.createIdentifier(propertyName) : void 0, - factory.createIdentifier(name) - ); + return factory.createImportSpecifier( /*isTypeOnly*/ + false, propertyName !== void 0 && propertyName !== name ? factory.createIdentifier(propertyName) : void 0, factory.createIdentifier(name)); } function makeConst(modifiers, name, init) { - return factory.createVariableStatement( - modifiers, - factory.createVariableDeclarationList( - [factory.createVariableDeclaration( - name, - /*exclamationToken*/ - void 0, - /*type*/ - void 0, - init - )], - 2 /* Const */ - ) - ); + return factory.createVariableStatement(modifiers, factory.createVariableDeclarationList([factory.createVariableDeclaration(name, /*exclamationToken*/ + void 0, /*type*/ + void 0, init)], 2 /* Const */)); } + function makeExportDeclaration(exportSpecifiers, moduleSpecifier) { - return factory.createExportDeclaration( - /*modifiers*/ - void 0, - /*isTypeOnly*/ - false, - exportSpecifiers && factory.createNamedExports(exportSpecifiers), - moduleSpecifier === void 0 ? void 0 : factory.createStringLiteral(moduleSpecifier) - ); + return factory.createExportDeclaration( /*modifiers*/ + void 0, /*isTypeOnly*/ + false, exportSpecifiers && factory.createNamedExports(exportSpecifiers), moduleSpecifier === void 0 ? void 0 : factory.createStringLiteral(moduleSpecifier)); } function convertedImports(newImports, useSitesToUnqualify) { return { @@ -148158,13 +133094,18 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} var init_convertToEsModule = __esm({ "src/services/codefixes/convertToEsModule.ts"() { "use strict"; + init_ts4(); init_ts_codefix(); registerCodeFix({ errorCodes: [Diagnostics.File_is_a_CommonJS_module_it_may_be_converted_to_an_ES_module.code], getCodeActions(context) { - const { sourceFile, program, preferences } = context; - const changes = ts_textChanges_exports.ChangeTracker.with(context, (changes2) => { + const { + sourceFile, + program, + preferences + } = context; + const changes = ts_textChanges_exports.ChangeTracker.with(context, changes2 => { const moduleExportsChangedToDefault = convertFileToEsModule(sourceFile, program.getTypeChecker(), changes2, getEmitScriptTarget(program.getCompilerOptions()), getQuotePreference(sourceFile, preferences)); if (moduleExportsChangedToDefault) { for (const importingFile of program.getSourceFiles()) { @@ -148186,20 +133127,15 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } function doChange10(changeTracker, sourceFile, qualifiedName) { const rightText = qualifiedName.right.text; - const replacement = factory.createIndexedAccessTypeNode( - factory.createTypeReferenceNode( - qualifiedName.left, - /*typeArguments*/ - void 0 - ), - factory.createLiteralTypeNode(factory.createStringLiteral(rightText)) - ); + const replacement = factory.createIndexedAccessTypeNode(factory.createTypeReferenceNode(qualifiedName.left, /*typeArguments*/ + void 0), factory.createLiteralTypeNode(factory.createStringLiteral(rightText))); changeTracker.replaceNode(sourceFile, qualifiedName, replacement); } var fixId11, errorCodes12; var init_correctQualifiedNameToIndexedAccessType = __esm({ "src/services/codefixes/correctQualifiedNameToIndexedAccessType.ts"() { "use strict"; + init_ts4(); init_ts_codefix(); fixId11 = "correctQualifiedNameToIndexedAccessType"; @@ -148208,14 +133144,13 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} errorCodes: errorCodes12, getCodeActions(context) { const qualifiedName = getQualifiedName(context.sourceFile, context.span.start); - if (!qualifiedName) - return void 0; - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange10(t, context.sourceFile, qualifiedName)); + 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)]; }, fixIds: [fixId11], - getAllCodeActions: (context) => codeFixAll(context, errorCodes12, (changes, diag2) => { + getAllCodeActions: context => codeFixAll(context, errorCodes12, (changes, diag2) => { const q = getQualifiedName(diag2.file, diag2.start); if (q) { doChange10(changes, diag2.file, q); @@ -148239,26 +133174,13 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (typeExportSpecifiers.length === exportClause.elements.length) { changes.insertModifierBefore(context.sourceFile, 156 /* TypeKeyword */, exportClause); } else { - const valueExportDeclaration = factory.updateExportDeclaration( - exportDeclaration, - exportDeclaration.modifiers, - /*isTypeOnly*/ - false, - factory.updateNamedExports(exportClause, filter(exportClause.elements, (e) => !contains(typeExportSpecifiers, e))), - exportDeclaration.moduleSpecifier, - /*attributes*/ - void 0 - ); - const typeExportDeclaration = factory.createExportDeclaration( - /*modifiers*/ - void 0, - /*isTypeOnly*/ - true, - factory.createNamedExports(typeExportSpecifiers), - exportDeclaration.moduleSpecifier, - /*attributes*/ - void 0 - ); + const valueExportDeclaration = factory.updateExportDeclaration(exportDeclaration, exportDeclaration.modifiers, /*isTypeOnly*/ + false, factory.updateNamedExports(exportClause, filter(exportClause.elements, e => !contains(typeExportSpecifiers, e))), exportDeclaration.moduleSpecifier, /*attributes*/ + void 0); + const typeExportDeclaration = factory.createExportDeclaration( /*modifiers*/ + void 0, /*isTypeOnly*/ + true, factory.createNamedExports(typeExportSpecifiers), exportDeclaration.moduleSpecifier, /*attributes*/ + void 0); changes.replaceNode(context.sourceFile, exportDeclaration, valueExportDeclaration, { leadingTriviaOption: ts_textChanges_exports.LeadingTriviaOption.IncludeAll, trailingTriviaOption: ts_textChanges_exports.TrailingTriviaOption.Exclude @@ -148271,11 +133193,8 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (exportClause.elements.length === 1) { return exportClause.elements; } - const diagnostics = getDiagnosticsWithinSpan( - createTextSpanFromNode(exportClause), - context.program.getSemanticDiagnostics(context.sourceFile, context.cancellationToken) - ); - return filter(exportClause.elements, (element) => { + const diagnostics = getDiagnosticsWithinSpan(createTextSpanFromNode(exportClause), context.program.getSemanticDiagnostics(context.sourceFile, context.cancellationToken)); + return filter(exportClause.elements, element => { var _a; return element === originExportSpecifier || ((_a = findDiagnosticForNode(element, diagnostics)) == null ? void 0 : _a.code) === errorCodes13[0]; }); @@ -148284,6 +133203,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} var init_convertToTypeOnlyExport = __esm({ "src/services/codefixes/convertToTypeOnlyExport.ts"() { "use strict"; + init_ts4(); init_ts_codefix(); errorCodes13 = [Diagnostics.Re_exporting_a_type_when_0_is_enabled_requires_using_export_type.code]; @@ -148291,14 +133211,14 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} registerCodeFix({ errorCodes: errorCodes13, getCodeActions: function getCodeActionsToConvertToTypeOnlyExport(context) { - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => fixSingleExportDeclaration(t, getExportSpecifierForDiagnosticSpan(context.span, context.sourceFile), context)); + const changes = ts_textChanges_exports.ChangeTracker.with(context, t => fixSingleExportDeclaration(t, getExportSpecifierForDiagnosticSpan(context.span, context.sourceFile), context)); if (changes.length) { return [createCodeFixAction(fixId12, changes, Diagnostics.Convert_to_type_only_export, fixId12, Diagnostics.Convert_all_re_exported_types_to_type_only_exports)]; } }, fixIds: [fixId12], getAllCodeActions: function getAllCodeActionsToConvertToTypeOnlyExport(context) { - const fixedExportDeclarations = /* @__PURE__ */ new Map(); + const fixedExportDeclarations = /* @__PURE__ */new Map(); return codeFixAll(context, errorCodes13, (changes, diag2) => { const exportSpecifier = getExportSpecifierForDiagnosticSpan(diag2, context.sourceFile); if (exportSpecifier && addToSeen(fixedExportDeclarations, getNodeId(exportSpecifier.parent.parent))) { @@ -148312,20 +133232,22 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} // src/services/codefixes/convertToTypeOnlyImport.ts function getDeclaration2(sourceFile, pos) { - const { parent: parent2 } = getTokenAtPosition(sourceFile, pos); + const { + parent: parent2 + } = getTokenAtPosition(sourceFile, pos); return isImportSpecifier(parent2) || isImportDeclaration(parent2) && parent2.importClause ? parent2 : void 0; } function canConvertImportDeclarationForSpecifier(specifier, sourceFile, program) { if (specifier.parent.parent.name) { return false; } - const nonTypeOnlySpecifiers = specifier.parent.elements.filter((e) => !e.isTypeOnly); + const nonTypeOnlySpecifiers = specifier.parent.elements.filter(e => !e.isTypeOnly); if (nonTypeOnlySpecifiers.length === 1) { return true; } const checker = program.getTypeChecker(); for (const specifier2 of nonTypeOnlySpecifiers) { - const isUsedAsValue = ts_FindAllReferences_exports.Core.eachSymbolReferenceInFile(specifier2.name, checker, sourceFile, (usage) => { + const isUsedAsValue = ts_FindAllReferences_exports.Core.eachSymbolReferenceInFile(specifier2.name, checker, sourceFile, usage => { return !isValidTypeOnlyAliasUseSite(usage); }); if (isUsedAsValue) { @@ -148337,92 +133259,29 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} function doChange11(changes, sourceFile, declaration) { var _a; if (isImportSpecifier(declaration)) { - changes.replaceNode(sourceFile, declaration, factory.updateImportSpecifier( - declaration, - /*isTypeOnly*/ - true, - declaration.propertyName, - declaration.name - )); + changes.replaceNode(sourceFile, declaration, factory.updateImportSpecifier(declaration, /*isTypeOnly*/ + true, declaration.propertyName, declaration.name)); } else { const importClause = declaration.importClause; if (importClause.name && importClause.namedBindings) { - changes.replaceNodeWithNodes(sourceFile, declaration, [ - factory.createImportDeclaration( - getSynthesizedDeepClones( - declaration.modifiers, - /*includeTrivia*/ - true - ), - factory.createImportClause( - /*isTypeOnly*/ - true, - getSynthesizedDeepClone( - importClause.name, - /*includeTrivia*/ - true - ), - /*namedBindings*/ - void 0 - ), - getSynthesizedDeepClone( - declaration.moduleSpecifier, - /*includeTrivia*/ - true - ), - getSynthesizedDeepClone( - declaration.attributes, - /*includeTrivia*/ - true - ) - ), - factory.createImportDeclaration( - getSynthesizedDeepClones( - declaration.modifiers, - /*includeTrivia*/ - true - ), - factory.createImportClause( - /*isTypeOnly*/ - true, - /*name*/ - void 0, - getSynthesizedDeepClone( - importClause.namedBindings, - /*includeTrivia*/ - true - ) - ), - getSynthesizedDeepClone( - declaration.moduleSpecifier, - /*includeTrivia*/ - true - ), - getSynthesizedDeepClone( - declaration.attributes, - /*includeTrivia*/ - true - ) - ) - ]); + changes.replaceNodeWithNodes(sourceFile, declaration, [factory.createImportDeclaration(getSynthesizedDeepClones(declaration.modifiers, /*includeTrivia*/ + true), factory.createImportClause( /*isTypeOnly*/ + true, getSynthesizedDeepClone(importClause.name, /*includeTrivia*/ + true), /*namedBindings*/ + void 0), getSynthesizedDeepClone(declaration.moduleSpecifier, /*includeTrivia*/ + true), getSynthesizedDeepClone(declaration.attributes, /*includeTrivia*/ + true)), factory.createImportDeclaration(getSynthesizedDeepClones(declaration.modifiers, /*includeTrivia*/ + true), factory.createImportClause( /*isTypeOnly*/ + true, /*name*/ + void 0, getSynthesizedDeepClone(importClause.namedBindings, /*includeTrivia*/ + true)), getSynthesizedDeepClone(declaration.moduleSpecifier, /*includeTrivia*/ + true), getSynthesizedDeepClone(declaration.attributes, /*includeTrivia*/ + true))]); } else { - const newNamedBindings = ((_a = importClause.namedBindings) == null ? void 0 : _a.kind) === 275 /* NamedImports */ ? factory.updateNamedImports( - importClause.namedBindings, - sameMap(importClause.namedBindings.elements, (e) => factory.updateImportSpecifier( - e, - /*isTypeOnly*/ - false, - e.propertyName, - e.name - )) - ) : importClause.namedBindings; - const importDeclaration = factory.updateImportDeclaration(declaration, declaration.modifiers, factory.updateImportClause( - importClause, - /*isTypeOnly*/ - true, - importClause.name, - newNamedBindings - ), declaration.moduleSpecifier, declaration.attributes); + const newNamedBindings = ((_a = importClause.namedBindings) == null ? void 0 : _a.kind) === 275 /* NamedImports */ ? factory.updateNamedImports(importClause.namedBindings, sameMap(importClause.namedBindings.elements, e => factory.updateImportSpecifier(e, /*isTypeOnly*/ + false, e.propertyName, e.name))) : importClause.namedBindings; + const importDeclaration = factory.updateImportDeclaration(declaration, declaration.modifiers, factory.updateImportClause(importClause, /*isTypeOnly*/ + true, importClause.name, newNamedBindings), declaration.moduleSpecifier, declaration.attributes); changes.replaceNode(sourceFile, declaration, importDeclaration); } } @@ -148431,12 +133290,10 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} var init_convertToTypeOnlyImport = __esm({ "src/services/codefixes/convertToTypeOnlyImport.ts"() { "use strict"; + init_ts4(); init_ts_codefix(); - errorCodes14 = [ - Diagnostics.This_import_is_never_used_as_a_value_and_must_use_import_type_because_importsNotUsedAsValues_is_set_to_error.code, - Diagnostics._0_is_a_type_and_must_be_imported_using_a_type_only_import_when_verbatimModuleSyntax_is_enabled.code - ]; + errorCodes14 = [Diagnostics.This_import_is_never_used_as_a_value_and_must_use_import_type_because_importsNotUsedAsValues_is_set_to_error.code, Diagnostics._0_is_a_type_and_must_be_imported_using_a_type_only_import_when_verbatimModuleSyntax_is_enabled.code]; fixId13 = "convertToTypeOnlyImport"; registerCodeFix({ errorCodes: errorCodes14, @@ -148444,20 +133301,12 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} var _a; const declaration = getDeclaration2(context.sourceFile, context.span.start); if (declaration) { - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange11(t, context.sourceFile, declaration)); - const importDeclarationChanges = declaration.kind === 276 /* ImportSpecifier */ && canConvertImportDeclarationForSpecifier(declaration, context.sourceFile, context.program) ? ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange11(t, context.sourceFile, declaration.parent.parent.parent)) : void 0; - const mainAction = createCodeFixAction( - fixId13, - changes, - declaration.kind === 276 /* ImportSpecifier */ ? [Diagnostics.Use_type_0, ((_a = declaration.propertyName) == null ? void 0 : _a.text) ?? declaration.name.text] : Diagnostics.Use_import_type, - fixId13, - Diagnostics.Fix_all_with_type_only_imports - ); + var _ref44; + const changes = ts_textChanges_exports.ChangeTracker.with(context, t => doChange11(t, context.sourceFile, declaration)); + const importDeclarationChanges = declaration.kind === 276 /* ImportSpecifier */ && canConvertImportDeclarationForSpecifier(declaration, context.sourceFile, context.program) ? ts_textChanges_exports.ChangeTracker.with(context, t => doChange11(t, context.sourceFile, declaration.parent.parent.parent)) : void 0; + const mainAction = createCodeFixAction(fixId13, changes, declaration.kind === 276 /* ImportSpecifier */ ? [Diagnostics.Use_type_0, (_ref44 = (_a = declaration.propertyName) == null ? void 0 : _a.text) !== null && _ref44 !== void 0 ? _ref44 : declaration.name.text] : Diagnostics.Use_import_type, fixId13, Diagnostics.Fix_all_with_type_only_imports); if (some(importDeclarationChanges)) { - return [ - createCodeFixActionWithoutFixAll(fixId13, importDeclarationChanges, Diagnostics.Use_import_type), - mainAction - ]; + return [createCodeFixActionWithoutFixAll(fixId13, importDeclarationChanges, Diagnostics.Use_import_type), mainAction]; } return [mainAction]; } @@ -148465,7 +133314,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} }, fixIds: [fixId13], getAllCodeActions: function getAllCodeActionsToConvertToTypeOnlyImport(context) { - const fixedImportDeclarations = /* @__PURE__ */ new Set(); + const fixedImportDeclarations = /* @__PURE__ */new Set(); return codeFixAll(context, errorCodes14, (changes, diag2) => { const errorDeclaration = getDeclaration2(diag2.file, diag2.start); if ((errorDeclaration == null ? void 0 : errorDeclaration.kind) === 272 /* ImportDeclaration */ && !fixedImportDeclarations.has(errorDeclaration)) { @@ -148485,13 +133334,14 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} // src/services/codefixes/convertTypedefToType.ts 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); + const { + leftSibling, + rightSibling + } = getLeftAndRightSiblings(node); let pos = commentNode.getStart(); let prefix = ""; if (!leftSibling && commentNode.comment) { @@ -148518,17 +133368,24 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} suffix = `${newLine}/**${newLine} * `; } } - changes.replaceRange(sourceFile, { pos, end }, declaration, { prefix, suffix }); + changes.replaceRange(sourceFile, { + pos, + end + }, declaration, { + prefix, + suffix + }); } function getLeftAndRightSiblings(typedefNode) { const commentNode = typedefNode.parent; const maxChildIndex = commentNode.getChildCount() - 1; - const currentNodeIndex = commentNode.getChildren().findIndex( - (n) => n.getStart() === typedefNode.getStart() && n.getEnd() === typedefNode.getEnd() - ); + const currentNodeIndex = commentNode.getChildren().findIndex(n => n.getStart() === typedefNode.getStart() && n.getEnd() === typedefNode.getEnd()); const leftSibling = currentNodeIndex > 0 ? commentNode.getChildAt(currentNodeIndex - 1) : void 0; const rightSibling = currentNodeIndex < maxChildIndex ? commentNode.getChildAt(currentNodeIndex + 1) : void 0; - return { leftSibling, rightSibling }; + return { + leftSibling, + rightSibling + }; } function findEndOfTextBetween(jsDocComment, from, to) { const comment = jsDocComment.getText().substring(from - jsDocComment.getStart(), to - jsDocComment.getStart()); @@ -148541,12 +133398,12 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } function createDeclaration(tag) { var _a; - const { typeExpression } = tag; - if (!typeExpression) - return; + const { + typeExpression + } = tag; + if (!typeExpression) return; const typeName = (_a = tag.name) == null ? void 0 : _a.getText(); - if (!typeName) - return; + if (!typeName) return; if (typeExpression.kind === 329 /* JSDocTypeLiteral */) { return createInterfaceForTypeLiteral(typeName, typeExpression); } @@ -148556,37 +133413,23 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } function createInterfaceForTypeLiteral(typeName, typeLiteral) { const propertySignatures = createSignatureFromTypeLiteral(typeLiteral); - if (!some(propertySignatures)) - return; - return factory.createInterfaceDeclaration( - /*modifiers*/ - void 0, - typeName, - /*typeParameters*/ - void 0, - /*heritageClauses*/ - void 0, - propertySignatures - ); + if (!some(propertySignatures)) return; + return factory.createInterfaceDeclaration( /*modifiers*/ + void 0, typeName, /*typeParameters*/ + void 0, /*heritageClauses*/ + void 0, propertySignatures); } function createTypeAliasForTypeExpression(typeName, typeExpression) { const typeReference = getSynthesizedDeepClone(typeExpression.type); - if (!typeReference) - return; - return factory.createTypeAliasDeclaration( - /*modifiers*/ - void 0, - factory.createIdentifier(typeName), - /*typeParameters*/ - void 0, - typeReference - ); + if (!typeReference) return; + return factory.createTypeAliasDeclaration( /*modifiers*/ + void 0, factory.createIdentifier(typeName), /*typeParameters*/ + void 0, typeReference); } function createSignatureFromTypeLiteral(typeLiteral) { const propertyTags = typeLiteral.jsDocPropertyTags; - if (!some(propertyTags)) - return; - const getSignature = (tag) => { + if (!some(propertyTags)) return; + const getSignature = tag => { var _a; const name = getPropertyName(tag); const type = (_a = tag.typeExpression) == null ? void 0 : _a.type; @@ -148600,13 +133443,8 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } if (typeReference && name) { const questionToken = isOptional ? factory.createToken(58 /* QuestionToken */) : void 0; - return factory.createPropertySignature( - /*modifiers*/ - void 0, - name, - questionToken, - typeReference - ); + return factory.createPropertySignature( /*modifiers*/ + void 0, name, questionToken, typeReference); } }; return mapDefined(propertyTags, getSignature); @@ -148616,9 +133454,9 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } function getJSDocTypedefNodes(node) { if (hasJSDocNodes(node)) { - return flatMap(node.jsDoc, (doc) => { + return flatMap(node.jsDoc, doc => { var _a; - return (_a = doc.tags) == null ? void 0 : _a.filter((tag) => isJSDocTypedefTag(tag)); + return (_a = doc.tags) == null ? void 0 : _a.filter(tag => isJSDocTypedefTag(tag)); }); } return []; @@ -148627,6 +133465,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} var init_convertTypedefToType = __esm({ "src/services/codefixes/convertTypedefToType.ts"() { "use strict"; + init_ts4(); init_ts_codefix(); fixId14 = "convertTypedefToType"; @@ -148636,36 +133475,19 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} errorCodes: errorCodes15, getCodeActions(context) { const newLineCharacter = getNewLineOrDefaultFromHost(context.host, context.formatContext.options); - const node = getTokenAtPosition( - context.sourceFile, - context.span.start - ); - if (!node) - return; - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange12(t, node, context.sourceFile, newLineCharacter)); + const node = getTokenAtPosition(context.sourceFile, context.span.start); + if (!node) return; + const changes = ts_textChanges_exports.ChangeTracker.with(context, t => doChange12(t, node, context.sourceFile, newLineCharacter)); if (changes.length > 0) { - return [ - createCodeFixAction( - fixId14, - changes, - Diagnostics.Convert_typedef_to_TypeScript_type, - fixId14, - Diagnostics.Convert_all_typedef_to_TypeScript_types - ) - ]; + return [createCodeFixAction(fixId14, changes, Diagnostics.Convert_typedef_to_TypeScript_type, fixId14, Diagnostics.Convert_all_typedef_to_TypeScript_types)]; } }, - getAllCodeActions: (context) => codeFixAll( - context, - errorCodes15, - (changes, diag2) => { - const newLineCharacter = getNewLineOrDefaultFromHost(context.host, context.formatContext.options); - const node = getTokenAtPosition(diag2.file, diag2.start); - const fixAll = true; - if (node) - doChange12(changes, node, diag2.file, newLineCharacter, fixAll); - } - ) + getAllCodeActions: context => codeFixAll(context, errorCodes15, (changes, diag2) => { + const newLineCharacter = getNewLineOrDefaultFromHost(context.host, context.formatContext.options); + const node = getTokenAtPosition(diag2.file, diag2.start); + const fixAll = true; + if (node) doChange12(changes, node, diag2.file, newLineCharacter, fixAll); + }) }); } }); @@ -148685,33 +133507,24 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } return void 0; } - function doChange13(changes, sourceFile, { container, typeNode, constraint, name }) { - changes.replaceNode( - sourceFile, - container, - factory.createMappedTypeNode( - /*readonlyToken*/ - void 0, - factory.createTypeParameterDeclaration( - /*modifiers*/ - void 0, - name, - factory.createTypeReferenceNode(constraint) - ), - /*nameType*/ - void 0, - /*questionToken*/ - void 0, - typeNode, - /*members*/ - void 0 - ) - ); + function doChange13(changes, sourceFile, { + container, + typeNode, + constraint, + name + }) { + changes.replaceNode(sourceFile, container, factory.createMappedTypeNode( /*readonlyToken*/ + void 0, factory.createTypeParameterDeclaration( /*modifiers*/ + void 0, name, factory.createTypeReferenceNode(constraint)), /*nameType*/ + void 0, /*questionToken*/ + void 0, typeNode, /*members*/ + void 0)); } var fixId15, errorCodes16; var init_convertLiteralTypeToMappedType = __esm({ "src/services/codefixes/convertLiteralTypeToMappedType.ts"() { "use strict"; + init_ts4(); init_ts_codefix(); fixId15 = "convertLiteralTypeToMappedType"; @@ -148719,17 +133532,23 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} registerCodeFix({ errorCodes: errorCodes16, getCodeActions: function getCodeActionsToConvertLiteralTypeToMappedType(context) { - const { sourceFile, span } = context; + const { + sourceFile, + span + } = context; const info = getInfo5(sourceFile, span.start); if (!info) { return void 0; } - const { name, constraint } = info; - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange13(t, sourceFile, info)); + const { + name, + constraint + } = info; + const changes = ts_textChanges_exports.ChangeTracker.with(context, t => doChange13(t, sourceFile, info)); return [createCodeFixAction(fixId15, changes, [Diagnostics.Convert_0_to_1_in_0, constraint, name], fixId15, Diagnostics.Convert_all_type_literals_to_mapped_type)]; }, fixIds: [fixId15], - getAllCodeActions: (context) => codeFixAll(context, errorCodes16, (changes, diag2) => { + getAllCodeActions: context => codeFixAll(context, errorCodes16, (changes, diag2) => { const info = getInfo5(diag2.file, diag2.start); if (info) { doChange13(changes, diag2.file, info); @@ -148746,33 +133565,31 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} function symbolPointsToNonPrivateMember(symbol) { return !symbol.valueDeclaration || !(getEffectiveModifierFlags(symbol.valueDeclaration) & 2 /* Private */); } + function addMissingDeclarations(context, implementedTypeNode, sourceFile, classDeclaration, changeTracker, preferences) { const checker = context.program.getTypeChecker(); const maybeHeritageClauseSymbol = getHeritageClauseSymbolTable(classDeclaration, checker); const implementedType = checker.getTypeAtLocation(implementedTypeNode); const implementedTypeSymbols = checker.getPropertiesOfType(implementedType); - const nonPrivateAndNotExistedInHeritageClauseMembers = implementedTypeSymbols.filter(and(symbolPointsToNonPrivateMember, (symbol) => !maybeHeritageClauseSymbol.has(symbol.escapedName))); + const nonPrivateAndNotExistedInHeritageClauseMembers = implementedTypeSymbols.filter(and(symbolPointsToNonPrivateMember, symbol => !maybeHeritageClauseSymbol.has(symbol.escapedName))); const classType = checker.getTypeAtLocation(classDeclaration); - const constructor = find(classDeclaration.members, (m) => isConstructorDeclaration(m)); + const constructor = find(classDeclaration.members, m => isConstructorDeclaration(m)); if (!classType.getNumberIndexType()) { createMissingIndexSignatureDeclaration(implementedType, 1 /* Number */); } + if (!classType.getStringIndexType()) { createMissingIndexSignatureDeclaration(implementedType, 0 /* String */); } + const importAdder = createImportAdder(sourceFile, context.program, preferences, context.host); - createMissingMemberNodes(classDeclaration, nonPrivateAndNotExistedInHeritageClauseMembers, sourceFile, context, preferences, importAdder, (member) => insertInterfaceMemberNode(sourceFile, classDeclaration, member)); + createMissingMemberNodes(classDeclaration, nonPrivateAndNotExistedInHeritageClauseMembers, sourceFile, context, preferences, importAdder, member => insertInterfaceMemberNode(sourceFile, classDeclaration, member)); importAdder.writeFixes(changeTracker); function createMissingIndexSignatureDeclaration(type, kind) { const indexInfoOfKind = checker.getIndexInfoOfType(type, kind); if (indexInfoOfKind) { - insertInterfaceMemberNode(sourceFile, classDeclaration, checker.indexInfoToIndexSignatureDeclaration( - indexInfoOfKind, - classDeclaration, - /*flags*/ - void 0, - getNoopSymbolTrackerWithResolver(context) - )); + insertInterfaceMemberNode(sourceFile, classDeclaration, checker.indexInfoToIndexSignatureDeclaration(indexInfoOfKind, classDeclaration, /*flags*/ + void 0, getNoopSymbolTrackerWithResolver(context))); } } function insertInterfaceMemberNode(sourceFile2, cls, newElement) { @@ -148785,8 +133602,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } 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)); @@ -148795,26 +133611,27 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} var init_fixClassIncorrectlyImplementsInterface = __esm({ "src/services/codefixes/fixClassIncorrectlyImplementsInterface.ts"() { "use strict"; + init_ts4(); init_ts_codefix(); - errorCodes17 = [ - Diagnostics.Class_0_incorrectly_implements_interface_1.code, - Diagnostics.Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclass.code - ]; + errorCodes17 = [Diagnostics.Class_0_incorrectly_implements_interface_1.code, Diagnostics.Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclass.code]; fixId16 = "fixClassIncorrectlyImplementsInterface"; registerCodeFix({ errorCodes: errorCodes17, getCodeActions(context) { - const { sourceFile, span } = context; + const { + sourceFile, + span + } = context; const classDeclaration = getClass(sourceFile, span.start); - return mapDefined(getEffectiveImplementsTypeNodes(classDeclaration), (implementedTypeNode) => { - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => addMissingDeclarations(context, implementedTypeNode, sourceFile, classDeclaration, t, context.preferences)); + return mapDefined(getEffectiveImplementsTypeNodes(classDeclaration), implementedTypeNode => { + const changes = ts_textChanges_exports.ChangeTracker.with(context, t => addMissingDeclarations(context, implementedTypeNode, sourceFile, classDeclaration, t, context.preferences)); return changes.length === 0 ? void 0 : createCodeFixAction(fixId16, changes, [Diagnostics.Implement_interface_0, implementedTypeNode.getText(sourceFile)], fixId16, Diagnostics.Implement_all_unimplemented_interfaces); }); }, fixIds: [fixId16], getAllCodeActions(context) { - const seenClassDeclarations = /* @__PURE__ */ new Map(); + const seenClassDeclarations = /* @__PURE__ */new Map(); return codeFixAll(context, errorCodes17, (changes, diag2) => { const classDeclaration = getClass(diag2.file, diag2.start); if (addToSeen(seenClassDeclarations, getNodeId(classDeclaration))) { @@ -148830,27 +133647,24 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} // src/services/codefixes/importFixes.ts function createImportAdder(sourceFile, program, preferences, host, cancellationToken) { - return createImportAdderWorker( - sourceFile, - program, - /*useAutoImportProvider*/ - false, - preferences, - host, - cancellationToken - ); + return createImportAdderWorker(sourceFile, program, /*useAutoImportProvider*/ + false, preferences, host, cancellationToken); } function createImportAdderWorker(sourceFile, program, useAutoImportProvider, preferences, host, cancellationToken) { const compilerOptions = program.getCompilerOptions(); const addToNamespace = []; const importType = []; - const addToExisting = /* @__PURE__ */ new Map(); - const newImports = /* @__PURE__ */ new Map(); - return { addImportFromDiagnostic, addImportFromExportedSymbol, writeFixes, hasFixes }; + const addToExisting = /* @__PURE__ */new Map(); + const newImports = /* @__PURE__ */new Map(); + return { + addImportFromDiagnostic, + addImportFromExportedSymbol, + writeFixes, + hasFixes + }; 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) { @@ -148858,37 +133672,25 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} const symbolName2 = getNameForExportedSymbol(exportedSymbol, getEmitScriptTarget(compilerOptions)); const checker = program.getTypeChecker(); const symbol = checker.getMergedSymbol(skipAlias(exportedSymbol, checker)); - const exportInfo = getAllExportInfoForSymbol( - sourceFile, - symbol, - symbolName2, - moduleSymbol, - /*preferCapitalized*/ - false, - program, - host, - preferences, - cancellationToken - ); + const exportInfo = getAllExportInfoForSymbol(sourceFile, symbol, symbolName2, moduleSymbol, /*preferCapitalized*/ + false, program, host, preferences, cancellationToken); const useRequire = shouldUseRequire(sourceFile, program); - const fix = getImportFixForSymbol( - sourceFile, - Debug.checkDefined(exportInfo), - program, - /*position*/ - void 0, - !!isValidTypeOnlyUseSite, - useRequire, - host, - preferences - ); + const fix = getImportFixForSymbol(sourceFile, Debug.checkDefined(exportInfo), program, /*position*/ + void 0, !!isValidTypeOnlyUseSite, useRequire, host, preferences); if (fix) { - addImport({ fix, symbolName: symbolName2, errorIdentifierText: void 0 }); + addImport({ + fix, + symbolName: symbolName2, + errorIdentifierText: void 0 + }); } } function addImport(info) { var _a, _b; - const { fix, symbolName: symbolName2 } = info; + const { + fix, + symbolName: symbolName2 + } = info; switch (fix.kind) { case 0 /* UseNamespace */: addToNamespace.push(fix); @@ -148896,65 +133698,81 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} case 1 /* JsdocTypeImport */: importType.push(fix); break; - case 2 /* AddToExisting */: { - const { importClauseOrBindingPattern, importKind, addAsTypeOnly } = fix; - const key = String(getNodeId(importClauseOrBindingPattern)); - let entry = addToExisting.get(key); - if (!entry) { - addToExisting.set(key, entry = { importClauseOrBindingPattern, defaultImport: void 0, namedImports: /* @__PURE__ */ new Map() }); - } - if (importKind === 0 /* Named */) { - const prevValue = entry == null ? void 0 : entry.namedImports.get(symbolName2); - entry.namedImports.set(symbolName2, reduceAddAsTypeOnlyValues(prevValue, addAsTypeOnly)); - } else { - Debug.assert(entry.defaultImport === void 0 || entry.defaultImport.name === symbolName2, "(Add to Existing) Default import should be missing or match symbolName"); - entry.defaultImport = { - name: symbolName2, - addAsTypeOnly: reduceAddAsTypeOnlyValues((_a = entry.defaultImport) == null ? void 0 : _a.addAsTypeOnly, addAsTypeOnly) - }; - } - break; - } - case 3 /* AddNew */: { - const { moduleSpecifier, importKind, useRequire, addAsTypeOnly } = fix; - const entry = getNewImportEntry(moduleSpecifier, importKind, useRequire, addAsTypeOnly); - Debug.assert(entry.useRequire === useRequire, "(Add new) Tried to add an `import` and a `require` for the same module"); - switch (importKind) { - case 1 /* Default */: - Debug.assert(entry.defaultImport === void 0 || entry.defaultImport.name === symbolName2, "(Add new) Default import should be missing or match symbolName"); - entry.defaultImport = { name: symbolName2, addAsTypeOnly: reduceAddAsTypeOnlyValues((_b = entry.defaultImport) == null ? void 0 : _b.addAsTypeOnly, addAsTypeOnly) }; - break; - case 0 /* Named */: - const prevValue = (entry.namedImports || (entry.namedImports = /* @__PURE__ */ new Map())).get(symbolName2); + case 2 /* AddToExisting */: + { + const { + importClauseOrBindingPattern, + importKind, + addAsTypeOnly + } = fix; + const key = String(getNodeId(importClauseOrBindingPattern)); + let entry = addToExisting.get(key); + if (!entry) { + addToExisting.set(key, entry = { + importClauseOrBindingPattern, + defaultImport: void 0, + namedImports: /* @__PURE__ */new Map() + }); + } + if (importKind === 0 /* Named */) { + const prevValue = entry == null ? void 0 : entry.namedImports.get(symbolName2); entry.namedImports.set(symbolName2, reduceAddAsTypeOnlyValues(prevValue, addAsTypeOnly)); - break; - case 3 /* CommonJS */: - case 2 /* Namespace */: - Debug.assert(entry.namespaceLikeImport === void 0 || entry.namespaceLikeImport.name === symbolName2, "Namespacelike import shoudl be missing or match symbolName"); - entry.namespaceLikeImport = { importKind, name: symbolName2, addAsTypeOnly }; - break; + } else { + Debug.assert(entry.defaultImport === void 0 || entry.defaultImport.name === symbolName2, "(Add to Existing) Default import should be missing or match symbolName"); + entry.defaultImport = { + name: symbolName2, + addAsTypeOnly: reduceAddAsTypeOnlyValues((_a = entry.defaultImport) == null ? void 0 : _a.addAsTypeOnly, addAsTypeOnly) + }; + } + break; + } + case 3 /* AddNew */: + { + const { + moduleSpecifier, + importKind, + useRequire, + addAsTypeOnly + } = fix; + const entry = getNewImportEntry(moduleSpecifier, importKind, useRequire, addAsTypeOnly); + Debug.assert(entry.useRequire === useRequire, "(Add new) Tried to add an `import` and a `require` for the same module"); + switch (importKind) { + case 1 /* Default */: + Debug.assert(entry.defaultImport === void 0 || entry.defaultImport.name === symbolName2, "(Add new) Default import should be missing or match symbolName"); + entry.defaultImport = { + name: symbolName2, + addAsTypeOnly: reduceAddAsTypeOnlyValues((_b = entry.defaultImport) == null ? void 0 : _b.addAsTypeOnly, addAsTypeOnly) + }; + break; + case 0 /* Named */: + const prevValue = (entry.namedImports || (entry.namedImports = /* @__PURE__ */new Map())).get(symbolName2); + entry.namedImports.set(symbolName2, reduceAddAsTypeOnlyValues(prevValue, addAsTypeOnly)); + break; + case 3 /* CommonJS */: + case 2 /* Namespace */: + Debug.assert(entry.namespaceLikeImport === void 0 || entry.namespaceLikeImport.name === symbolName2, "Namespacelike import shoudl be missing or match symbolName"); + entry.namespaceLikeImport = { + importKind, + name: symbolName2, + addAsTypeOnly + }; + break; + } + break; } - break; - } case 4 /* PromoteTypeOnly */: break; default: Debug.assertNever(fix, `fix wasn't never - got kind ${fix.kind}`); } function reduceAddAsTypeOnlyValues(prevValue, newValue) { - return Math.max(prevValue ?? 0, newValue); + return Math.max(prevValue !== null && prevValue !== void 0 ? prevValue : 0, newValue); } function getNewImportEntry(moduleSpecifier, importKind, useRequire, addAsTypeOnly) { - const typeOnlyKey = newImportsKey( - moduleSpecifier, - /*topLevelTypeOnly*/ - true - ); - const nonTypeOnlyKey = newImportsKey( - moduleSpecifier, - /*topLevelTypeOnly*/ - false - ); + const typeOnlyKey = newImportsKey(moduleSpecifier, /*topLevelTypeOnly*/ + true); + const nonTypeOnlyKey = newImportsKey(moduleSpecifier, /*topLevelTypeOnly*/ + false); const typeOnlyEntry = newImports.get(typeOnlyKey); const nonTypeOnlyEntry = newImports.get(nonTypeOnlyKey); const newEntry = { @@ -148964,8 +133782,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} useRequire }; if (importKind === 1 /* Default */ && addAsTypeOnly === 2 /* Required */) { - if (typeOnlyEntry) - return typeOnlyEntry; + if (typeOnlyEntry) return typeOnlyEntry; newImports.set(typeOnlyKey, newEntry); return newEntry; } @@ -148995,40 +133812,34 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} for (const fix of importType) { addImportType(changeTracker, sourceFile, fix, quotePreference); } - addToExisting.forEach(({ importClauseOrBindingPattern, defaultImport, namedImports }) => { - doAddExistingFix( - changeTracker, - sourceFile, - importClauseOrBindingPattern, - defaultImport, - arrayFrom(namedImports.entries(), ([name, addAsTypeOnly]) => ({ addAsTypeOnly, name })), - preferences - ); + addToExisting.forEach(({ + importClauseOrBindingPattern, + defaultImport, + namedImports + }) => { + doAddExistingFix(changeTracker, sourceFile, importClauseOrBindingPattern, defaultImport, arrayFrom(namedImports.entries(), ([name, addAsTypeOnly]) => ({ + addAsTypeOnly, + name + })), preferences); }); let newDeclarations; - newImports.forEach(({ useRequire, defaultImport, namedImports, namespaceLikeImport }, key) => { + newImports.forEach(({ + useRequire, + defaultImport, + namedImports, + namespaceLikeImport + }, key) => { const moduleSpecifier = key.slice(2); const getDeclarations = useRequire ? getNewRequires : getNewImports; - const declarations = getDeclarations( - moduleSpecifier, - quotePreference, - defaultImport, - namedImports && arrayFrom(namedImports.entries(), ([name, addAsTypeOnly]) => ({ addAsTypeOnly, name })), - namespaceLikeImport, - compilerOptions, - preferences - ); + const declarations = getDeclarations(moduleSpecifier, quotePreference, defaultImport, namedImports && arrayFrom(namedImports.entries(), ([name, addAsTypeOnly]) => ({ + addAsTypeOnly, + name + })), namespaceLikeImport, compilerOptions, preferences); newDeclarations = combine(newDeclarations, declarations); }); if (newDeclarations) { - insertImports( - changeTracker, - sourceFile, - newDeclarations, - /*blankLineBetween*/ - true, - preferences - ); + insertImports(changeTracker, sourceFile, newDeclarations, /*blankLineBetween*/ + true, preferences); } } function hasFixes() { @@ -149038,23 +133849,20 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} function createImportSpecifierResolver(importingFile, program, host, preferences) { const packageJsonImportFilter = createPackageJsonImportFilter(importingFile, preferences, host); const importMap = createExistingImportMap(program.getTypeChecker(), importingFile, program.getCompilerOptions()); - return { getModuleSpecifierForBestExportInfo }; + return { + getModuleSpecifierForBestExportInfo + }; function getModuleSpecifierForBestExportInfo(exportInfo, position, isValidTypeOnlyUseSite, fromCacheOnly) { - const { fixes, computedWithoutCacheCount } = getImportFixes( - exportInfo, - position, - isValidTypeOnlyUseSite, - /*useRequire*/ - false, - program, - importingFile, - host, - preferences, - importMap, - fromCacheOnly - ); + const { + fixes, + computedWithoutCacheCount + } = getImportFixes(exportInfo, position, isValidTypeOnlyUseSite, /*useRequire*/ + false, program, importingFile, host, preferences, importMap, fromCacheOnly); const result = getBestFix(fixes, importingFile, program, packageJsonImportFilter, host); - return result && { ...result, computedWithoutCacheCount }; + return result && { + ...result, + computedWithoutCacheCount + }; } } function getImportCompletionAction(targetSymbol, moduleSymbol, exportMapKey, sourceFile, symbolName2, isJsxTagName, host, program, formatContext, position, preferences, cancellationToken) { @@ -149071,16 +133879,12 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} const fix = Debug.checkDefined(getImportFixForSymbol(sourceFile, exportInfos, program, position, isValidTypeOnlyUseSite, useRequire, host, preferences)); return { moduleSpecifier: fix.moduleSpecifier, - codeAction: codeFixActionToCodeAction(codeActionForFix( - { host, formatContext, preferences }, - sourceFile, - symbolName2, - fix, - /*includeSymbolNameInDescription*/ - false, - program, + codeAction: codeFixActionToCodeAction(codeActionForFix({ + host, + formatContext, preferences - )) + }, sourceFile, symbolName2, fix, /*includeSymbolNameInDescription*/ + false, program, preferences)) }; } function getPromoteTypeOnlyCompletionAction(sourceFile, symbolToken, program, host, formatContext, preferences) { @@ -149088,27 +133892,31 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} const symbolName2 = single(getSymbolNamesToImport(sourceFile, program.getTypeChecker(), symbolToken, compilerOptions)); const fix = getTypeOnlyPromotionFix(sourceFile, symbolToken, symbolName2, program); const includeSymbolNameInDescription = symbolName2 !== symbolToken.text; - return fix && codeFixActionToCodeAction(codeActionForFix( - { host, formatContext, preferences }, - sourceFile, - symbolName2, - fix, - includeSymbolNameInDescription, - program, + return fix && codeFixActionToCodeAction(codeActionForFix({ + host, + formatContext, preferences - )); + }, sourceFile, symbolName2, fix, includeSymbolNameInDescription, program, preferences)); } function getImportFixForSymbol(sourceFile, exportInfos, program, position, isValidTypeOnlyUseSite, useRequire, host, preferences) { const packageJsonImportFilter = createPackageJsonImportFilter(sourceFile, preferences, host); return getBestFix(getImportFixes(exportInfos, position, isValidTypeOnlyUseSite, useRequire, program, sourceFile, host, preferences).fixes, sourceFile, program, packageJsonImportFilter, host); } - function codeFixActionToCodeAction({ description: description3, changes, commands }) { - return { description: description3, changes, commands }; + function codeFixActionToCodeAction({ + description: description3, + changes, + commands + }) { + return { + description: description3, + changes, + commands + }; } function getAllExportInfoForSymbol(importingFile, symbol, symbolName2, moduleSymbol, preferCapitalized, program, host, preferences, cancellationToken) { const getChecker = createGetChecker(program, host); - return getExportInfoMap(importingFile, host, program, preferences, cancellationToken).search(importingFile.path, preferCapitalized, (name) => name === symbolName2, (info) => { - if (skipAlias(info[0].symbol, getChecker(info[0].isFromPackageJson)) === symbol && info.some((i) => i.moduleSymbol === moduleSymbol || i.symbol.parent === moduleSymbol)) { + return getExportInfoMap(importingFile, host, program, preferences, cancellationToken).search(importingFile.path, preferCapitalized, name => name === symbolName2, info => { + if (skipAlias(info[0].symbol, getChecker(info[0].isFromPackageJson)) === symbol && info.some(i => i.moduleSymbol === moduleSymbol || i.symbol.parent === moduleSymbol)) { return info; } }); @@ -149116,28 +133924,36 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} function getSingleExportInfoForSymbol(symbol, symbolName2, moduleSymbol, program, host) { var _a, _b; const compilerOptions = program.getCompilerOptions(); - const mainProgramInfo = getInfoWithChecker( - program.getTypeChecker(), - /*isFromPackageJson*/ - false - ); + const mainProgramInfo = getInfoWithChecker(program.getTypeChecker(), /*isFromPackageJson*/ + false); if (mainProgramInfo) { return mainProgramInfo; } const autoImportProvider = (_b = (_a = host.getPackageJsonAutoImportProvider) == null ? void 0 : _a.call(host)) == null ? void 0 : _b.getTypeChecker(); - return Debug.checkDefined(autoImportProvider && getInfoWithChecker( - autoImportProvider, - /*isFromPackageJson*/ - true - ), `Could not find symbol in specified module for code actions`); + return Debug.checkDefined(autoImportProvider && getInfoWithChecker(autoImportProvider, /*isFromPackageJson*/ + true), `Could not find symbol in specified module for code actions`); function getInfoWithChecker(checker, isFromPackageJson) { const defaultInfo = getDefaultLikeExportInfo(moduleSymbol, checker, compilerOptions); if (defaultInfo && skipAlias(defaultInfo.symbol, checker) === symbol) { - return { symbol: defaultInfo.symbol, moduleSymbol, moduleFileName: void 0, exportKind: defaultInfo.exportKind, targetFlags: skipAlias(symbol, checker).flags, isFromPackageJson }; + return { + symbol: defaultInfo.symbol, + moduleSymbol, + moduleFileName: void 0, + exportKind: defaultInfo.exportKind, + targetFlags: skipAlias(symbol, checker).flags, + isFromPackageJson + }; } const named = checker.tryGetMemberInModuleExportsAndProperties(symbolName2, moduleSymbol); if (named && skipAlias(named, checker) === symbol) { - return { symbol: named, moduleSymbol, moduleFileName: void 0, exportKind: 0 /* Named */, targetFlags: skipAlias(symbol, checker).flags, isFromPackageJson }; + return { + symbol: named, + moduleSymbol, + moduleFileName: void 0, + exportKind: 0 /* Named */, + targetFlags: skipAlias(symbol, checker).flags, + isFromPackageJson + }; } } } @@ -149149,35 +133965,34 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (addToExisting) { return { computedWithoutCacheCount: 0, - fixes: [...useNamespace ? [useNamespace] : emptyArray, addToExisting] + fixes: [...(useNamespace ? [useNamespace] : emptyArray), addToExisting] }; } - const { fixes, computedWithoutCacheCount = 0 } = getFixesForAddImport( - exportInfos, - existingImports, - program, - sourceFile, - usagePosition, - isValidTypeOnlyUseSite, - useRequire, - host, - preferences, - fromCacheOnly - ); + const { + fixes, + computedWithoutCacheCount = 0 + } = getFixesForAddImport(exportInfos, existingImports, program, sourceFile, usagePosition, isValidTypeOnlyUseSite, useRequire, host, preferences, fromCacheOnly); return { computedWithoutCacheCount, - fixes: [...useNamespace ? [useNamespace] : emptyArray, ...fixes] + fixes: [...(useNamespace ? [useNamespace] : emptyArray), ...fixes] }; } function tryUseExistingNamespaceImport(existingImports, position) { - return firstDefined(existingImports, ({ declaration, importKind }) => { + 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, + moduleSpecifier + }; } }); } @@ -149198,52 +134013,66 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (!isValidTypeOnlyUseSite) { return 4 /* NotAllowed */; } + if (isForNewImportDeclaration && compilerOptions.importsNotUsedAsValues === 2 /* Error */) { return 2 /* Required */; } + if (importNameElisionDisabled(compilerOptions) && (!(targetFlags & 111551 /* Value */) || !!checker.getTypeOnlyAliasDeclaration(symbol))) { return 2 /* Required */; } + return 1 /* Allowed */; } + function tryAddToExistingImport(existingImports, isValidTypeOnlyUseSite, checker, compilerOptions) { let best; for (const existingImport of existingImports) { + var _best; 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; } - best ?? (best = fix); + (_best = best) !== null && _best !== void 0 ? _best : best = fix; } return best; - function getAddToExistingImportFix({ declaration, importKind, symbol, targetFlags }) { + function getAddToExistingImportFix({ + declaration, + importKind, + symbol, + targetFlags + }) { if (importKind === 3 /* CommonJS */ || importKind === 2 /* Namespace */ || declaration.kind === 271 /* ImportEqualsDeclaration */) { return void 0; } if (declaration.kind === 260 /* VariableDeclaration */) { - return (importKind === 0 /* Named */ || importKind === 1 /* Default */) && declaration.name.kind === 206 /* ObjectBindingPattern */ ? { kind: 2 /* AddToExisting */, importClauseOrBindingPattern: declaration.name, importKind, 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, + moduleSpecifier: declaration.initializer.arguments[0].text, + addAsTypeOnly: 4 /* NotAllowed */ + } : void 0; } - const { importClause } = declaration; + const { + importClause + } = declaration; if (!importClause || !isStringLiteralLike(declaration.moduleSpecifier)) { return void 0; } - const { name, namedBindings } = importClause; + const { + name, + namedBindings + } = importClause; if (importClause.isTypeOnly && !(importKind === 0 /* Named */ && namedBindings)) { return void 0; } - const addAsTypeOnly = getAddAsTypeOnly( - isValidTypeOnlyUseSite, - /*isForNewImportDeclaration*/ - false, - symbol, - targetFlags, - checker, - compilerOptions - ); - if (importKind === 1 /* Default */ && (name || // Cannot add a default import to a declaration that already has one + const addAsTypeOnly = getAddAsTypeOnly(isValidTypeOnlyUseSite, /*isForNewImportDeclaration*/ + false, symbol, targetFlags, checker, compilerOptions); + if (importKind === 1 /* Default */ && (name || + // Cannot add a default import to a declaration that already has one addAsTypeOnly === 2 /* Required */ && namedBindings)) { return void 0; } @@ -149276,14 +134105,22 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } } return { - getImportsForExportInfo: ({ moduleSymbol, exportKind, targetFlags, symbol }) => { - if (!(targetFlags & 111551 /* Value */) && isSourceFileJS(importingFile)) - return emptyArray; + getImportsForExportInfo: ({ + moduleSymbol, + exportKind, + targetFlags, + symbol + }) => { + if (!(targetFlags & 111551 /* Value */) && isSourceFileJS(importingFile)) return emptyArray; const matchingDeclarations = importMap == null ? void 0 : importMap.get(getSymbolId(moduleSymbol)); - if (!matchingDeclarations) - return emptyArray; + if (!matchingDeclarations) return emptyArray; const importKind = getImportKind(importingFile, exportKind, compilerOptions); - return matchingDeclarations.map((declaration) => ({ declaration, importKind, symbol, targetFlags })); + return matchingDeclarations.map(declaration => ({ + declaration, + importKind, + symbol, + targetFlags + })); } }; } @@ -149291,30 +134128,24 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (!isSourceFileJS(sourceFile)) { 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 (sourceFile.impliedNodeFormat === 1 /* CommonJS */) - return true; - if (sourceFile.impliedNodeFormat === 99 /* ESNext */) - return false; + + if (sourceFile.impliedNodeFormat === 1 /* CommonJS */) return true; + if (sourceFile.impliedNodeFormat === 99 /* ESNext */) return false; for (const otherFile of program.getSourceFiles()) { - if (otherFile === sourceFile || !isSourceFileJS(otherFile) || program.isSourceFileFromExternalLibrary(otherFile)) - continue; - if (otherFile.commonJsModuleIndicator && !otherFile.externalModuleIndicator) - return true; - if (otherFile.externalModuleIndicator && !otherFile.commonJsModuleIndicator) - return false; + if (otherFile === sourceFile || !isSourceFileJS(otherFile) || program.isSourceFileFromExternalLibrary(otherFile)) continue; + if (otherFile.commonJsModuleIndicator && !otherFile.externalModuleIndicator) return true; + if (otherFile.externalModuleIndicator && !otherFile.commonJsModuleIndicator) return false; } return true; } function createGetChecker(program, host) { - return memoizeOne((isFromPackageJson) => isFromPackageJson ? host.getPackageJsonAutoImportProvider().getTypeChecker() : program.getTypeChecker()); + return memoizeOne(isFromPackageJson => isFromPackageJson ? host.getPackageJsonAutoImportProvider().getTypeChecker() : program.getTypeChecker()); } function getNewImportFixes(program, sourceFile, usagePosition, isValidTypeOnlyUseSite, useRequire, exportInfo, host, preferences, fromCacheOnly) { const isJs = isSourceFileJS(sourceFile); @@ -149323,40 +134154,36 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} const getChecker = createGetChecker(program, host); const moduleResolution = getEmitModuleResolutionKind(compilerOptions); const rejectNodeModulesRelativePaths = moduleResolutionUsesNodeModules(moduleResolution); - const getModuleSpecifiers2 = fromCacheOnly ? (moduleSymbol) => ({ moduleSpecifiers: ts_moduleSpecifiers_exports.tryGetModuleSpecifiersFromCache(moduleSymbol, sourceFile, moduleSpecifierResolutionHost, preferences), computedWithoutCache: false }) : (moduleSymbol, checker) => ts_moduleSpecifiers_exports.getModuleSpecifiersWithCacheInfo( - moduleSymbol, - checker, - compilerOptions, - sourceFile, - moduleSpecifierResolutionHost, - preferences, - /*options*/ - void 0, - /*forAutoImport*/ - true - ); + const getModuleSpecifiers2 = fromCacheOnly ? moduleSymbol => ({ + moduleSpecifiers: ts_moduleSpecifiers_exports.tryGetModuleSpecifiersFromCache(moduleSymbol, sourceFile, moduleSpecifierResolutionHost, preferences), + computedWithoutCache: false + }) : (moduleSymbol, checker) => ts_moduleSpecifiers_exports.getModuleSpecifiersWithCacheInfo(moduleSymbol, checker, compilerOptions, sourceFile, moduleSpecifierResolutionHost, preferences, /*options*/ + void 0, /*forAutoImport*/ + true); let computedWithoutCacheCount = 0; const fixes = flatMap(exportInfo, (exportInfo2, i) => { const checker = getChecker(exportInfo2.isFromPackageJson); - const { computedWithoutCache, moduleSpecifiers } = getModuleSpecifiers2(exportInfo2.moduleSymbol, checker); + const { + computedWithoutCache, + moduleSpecifiers + } = getModuleSpecifiers2(exportInfo2.moduleSymbol, checker); const importedSymbolHasValueMeaning = !!(exportInfo2.targetFlags & 111551 /* Value */); - const addAsTypeOnly = getAddAsTypeOnly( - isValidTypeOnlyUseSite, - /*isForNewImportDeclaration*/ - true, - exportInfo2.symbol, - exportInfo2.targetFlags, - checker, - compilerOptions - ); + const addAsTypeOnly = getAddAsTypeOnly(isValidTypeOnlyUseSite, /*isForNewImportDeclaration*/ + true, exportInfo2.symbol, exportInfo2.targetFlags, checker, compilerOptions); computedWithoutCacheCount += computedWithoutCache ? 1 : 0; - return mapDefined(moduleSpecifiers, (moduleSpecifier) => { + 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 */, + moduleSpecifier, + usagePosition, + exportInfo: exportInfo2, + isReExport: i > 0 + }; } const importKind = getImportKind(sourceFile, exportInfo2.exportKind, compilerOptions); let qualification; @@ -149366,13 +134193,12 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (exportEquals !== exportInfo2.moduleSymbol) { namespacePrefix = (_a = getDefaultExportInfoWorker(exportEquals, checker, compilerOptions)) == null ? void 0 : _a.name; } - namespacePrefix || (namespacePrefix = moduleSymbolToValidIdentifier( - exportInfo2.moduleSymbol, - getEmitScriptTarget(compilerOptions), - /*forceCapitalize*/ - false - )); - qualification = { namespacePrefix, usagePosition }; + namespacePrefix || (namespacePrefix = moduleSymbolToValidIdentifier(exportInfo2.moduleSymbol, getEmitScriptTarget(compilerOptions), /*forceCapitalize*/ + false)); + qualification = { + namespacePrefix, + usagePosition + }; } return { kind: 3 /* AddNew */, @@ -149386,26 +134212,35 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} }; }); }); - return { computedWithoutCacheCount, fixes }; + return { + computedWithoutCacheCount, + fixes + }; } function getFixesForAddImport(exportInfos, existingImports, program, sourceFile, usagePosition, isValidTypeOnlyUseSite, useRequire, host, preferences, fromCacheOnly) { - const existingDeclaration = firstDefined(existingImports, (info) => newImportInfoFromExistingSpecifier(info, isValidTypeOnlyUseSite, useRequire, program.getTypeChecker(), program.getCompilerOptions())); - return existingDeclaration ? { fixes: [existingDeclaration] } : getNewImportFixes(program, sourceFile, usagePosition, isValidTypeOnlyUseSite, useRequire, exportInfos, host, preferences, fromCacheOnly); + const existingDeclaration = firstDefined(existingImports, info => newImportInfoFromExistingSpecifier(info, isValidTypeOnlyUseSite, useRequire, program.getTypeChecker(), program.getCompilerOptions())); + return existingDeclaration ? { + fixes: [existingDeclaration] + } : getNewImportFixes(program, sourceFile, usagePosition, isValidTypeOnlyUseSite, useRequire, exportInfos, host, preferences, fromCacheOnly); } - function newImportInfoFromExistingSpecifier({ declaration, importKind, symbol, targetFlags }, isValidTypeOnlyUseSite, useRequire, checker, compilerOptions) { + function newImportInfoFromExistingSpecifier({ + declaration, + importKind, + symbol, + targetFlags + }, isValidTypeOnlyUseSite, useRequire, checker, compilerOptions) { var _a; const moduleSpecifier = (_a = tryGetModuleSpecifierFromDeclaration(declaration)) == null ? void 0 : _a.text; if (moduleSpecifier) { - const addAsTypeOnly = useRequire ? 4 /* NotAllowed */ : getAddAsTypeOnly( - isValidTypeOnlyUseSite, - /*isForNewImportDeclaration*/ - true, - symbol, - targetFlags, - checker, - compilerOptions - ); - return { kind: 3 /* AddNew */, moduleSpecifier, importKind, addAsTypeOnly, useRequire }; + const addAsTypeOnly = useRequire ? 4 /* NotAllowed */ : getAddAsTypeOnly(isValidTypeOnlyUseSite, /*isForNewImportDeclaration*/ + true, symbol, targetFlags, checker, compilerOptions); + return { + kind: 3 /* AddNew */, + moduleSpecifier, + importKind, + addAsTypeOnly, + useRequire + }; } } function getFixInfos(context, errorCode, pos, useAutoImportProvider) { @@ -149418,7 +134253,11 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } else if (errorCode === Diagnostics._0_cannot_be_used_as_a_value_because_it_was_imported_using_import_type.code) { const symbolName2 = single(getSymbolNamesToImport(context.sourceFile, context.program.getTypeChecker(), symbolToken, context.program.getCompilerOptions())); const fix = getTypeOnlyPromotionFix(context.sourceFile, symbolToken, symbolName2, context.program); - return fix && [{ fix, symbolName: symbolName2, errorIdentifierText: symbolToken.text }]; + return fix && [{ + fix, + symbolName: symbolName2, + errorIdentifierText: symbolToken.text + }]; } else { info = getFixesInfoForNonUMDImport(context, symbolToken, useAutoImportProvider); } @@ -149426,38 +134265,25 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return info && sortFixInfo(info, context.sourceFile, context.program, packageJsonImportFilter, context.host); } function sortFixInfo(fixes, sourceFile, program, packageJsonImportFilter, host) { - const _toPath = (fileName) => toPath(fileName, host.getCurrentDirectory(), hostGetCanonicalFileName(host)); + const _toPath = fileName => toPath(fileName, host.getCurrentDirectory(), hostGetCanonicalFileName(host)); return sort(fixes, (a, b) => compareBooleans(!!a.isJsxNamespaceFix, !!b.isJsxNamespaceFix) || compareValues(a.fix.kind, b.fix.kind) || compareModuleSpecifiers(a.fix, b.fix, sourceFile, program, packageJsonImportFilter.allowsImportingSpecifier, _toPath)); } function getBestFix(fixes, sourceFile, program, packageJsonImportFilter, host) { - if (!some(fixes)) - return; + if (!some(fixes)) return; if (fixes[0].kind === 0 /* UseNamespace */ || fixes[0].kind === 2 /* AddToExisting */) { return fixes[0]; } - return fixes.reduce( - (best, fix) => ( - // Takes true branch of conditional if `fix` is better than `best` - compareModuleSpecifiers( - fix, - best, - sourceFile, - program, - packageJsonImportFilter.allowsImportingSpecifier, - (fileName) => toPath(fileName, host.getCurrentDirectory(), hostGetCanonicalFileName(host)) - ) === -1 /* LessThan */ ? fix : best - ) - ); + return fixes.reduce((best, fix) => + // Takes true branch of conditional if `fix` is better than `best` + compareModuleSpecifiers(fix, best, sourceFile, program, packageJsonImportFilter.allowsImportingSpecifier, fileName => toPath(fileName, host.getCurrentDirectory(), hostGetCanonicalFileName(host))) === -1 /* LessThan */ ? fix : best); } function compareModuleSpecifiers(a, b, importingFile, program, allowsImportingSpecifier, toPath3) { if (a.kind !== 0 /* UseNamespace */ && b.kind !== 0 /* UseNamespace */) { - return compareBooleans(allowsImportingSpecifier(b.moduleSpecifier), allowsImportingSpecifier(a.moduleSpecifier)) || compareNodeCoreModuleSpecifiers(a.moduleSpecifier, b.moduleSpecifier, importingFile, program) || compareBooleans( - isFixPossiblyReExportingImportingFile(a, importingFile, program.getCompilerOptions(), toPath3), - isFixPossiblyReExportingImportingFile(b, importingFile, program.getCompilerOptions(), toPath3) - ) || compareNumberOfDirectorySeparators(a.moduleSpecifier, b.moduleSpecifier); + return compareBooleans(allowsImportingSpecifier(b.moduleSpecifier), allowsImportingSpecifier(a.moduleSpecifier)) || compareNodeCoreModuleSpecifiers(a.moduleSpecifier, b.moduleSpecifier, importingFile, program) || compareBooleans(isFixPossiblyReExportingImportingFile(a, importingFile, program.getCompilerOptions(), toPath3), isFixPossiblyReExportingImportingFile(b, importingFile, program.getCompilerOptions(), toPath3)) || compareNumberOfDirectorySeparators(a.moduleSpecifier, b.moduleSpecifier); } return 0 /* EqualTo */; } + function isFixPossiblyReExportingImportingFile(fix, importingFile, compilerOptions, toPath3) { var _a; if (fix.isReExport && ((_a = fix.exportInfo) == null ? void 0 : _a.moduleFileName) && getEmitModuleResolutionKind(compilerOptions) === 2 /* Node10 */ && isIndexFileName(fix.exportInfo.moduleFileName)) { @@ -149467,59 +134293,56 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return false; } function isIndexFileName(fileName) { - return getBaseFileName( - fileName, - [".js", ".jsx", ".d.ts", ".ts", ".tsx"], - /*ignoreCase*/ - true - ) === "index"; + return getBaseFileName(fileName, [".js", ".jsx", ".d.ts", ".ts", ".tsx"], /*ignoreCase*/ + true) === "index"; } function compareNodeCoreModuleSpecifiers(a, b, importingFile, program) { - if (startsWith(a, "node:") && !startsWith(b, "node:")) - return shouldUseUriStyleNodeCoreModules(importingFile, program) ? -1 /* LessThan */ : 1 /* GreaterThan */; - if (startsWith(b, "node:") && !startsWith(a, "node:")) - return shouldUseUriStyleNodeCoreModules(importingFile, program) ? 1 /* GreaterThan */ : -1 /* LessThan */; + 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) { + + 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 }]; + const exportInfo = [{ + symbol: umdSymbol, + moduleSymbol: symbol, + moduleFileName: void 0, + exportKind: 3 /* UMD */, + targetFlags: symbol.flags, + isFromPackageJson: false + }]; const useRequire = shouldUseRequire(sourceFile, program); - const fixes = getImportFixes( - exportInfo, - /*usagePosition*/ - void 0, - /*isValidTypeOnlyUseSite*/ - false, - useRequire, - program, - sourceFile, - host, - preferences - ).fixes; - return fixes.map((fix) => { + const fixes = getImportFixes(exportInfo, /*usagePosition*/ + void 0, /*isValidTypeOnlyUseSite*/ + false, useRequire, program, sourceFile, host, preferences).fixes; + return fixes.map(fix => { var _a; - return { fix, symbolName: symbolName2, errorIdentifierText: (_a = tryCast(token, isIdentifier)) == null ? void 0 : _a.text }; + return { + fix, + symbolName: symbolName2, + errorIdentifierText: (_a = tryCast(token, isIdentifier)) == null ? void 0 : _a.text + }; }); } function getUmdSymbol(token, checker) { const umdSymbol = isIdentifier(token) ? checker.getSymbolAtLocation(token) : void 0; - if (isUMDExportSymbol(umdSymbol)) - return umdSymbol; - const { parent: parent2 } = token; + if (isUMDExportSymbol(umdSymbol)) return umdSymbol; + const { + parent: parent2 + } = token; if (isJsxOpeningLikeElement(parent2) && parent2.tagName === token || isJsxOpeningFragment(parent2)) { - const parentSymbol = checker.resolveName( - checker.getJsxNamespace(parent2), - isJsxOpeningLikeElement(parent2) ? token : parent2, - 111551 /* Value */, - /*excludeGlobals*/ - false - ); + const parentSymbol = checker.resolveName(checker.getJsxNamespace(parent2), isJsxOpeningLikeElement(parent2) ? token : parent2, 111551 /* Value */, /*excludeGlobals*/ + false); if (isUMDExportSymbol(parentSymbol)) { return parentSymbol; } @@ -149530,6 +134353,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (compilerOptions.verbatimModuleSyntax && (getEmitModuleKind(compilerOptions) === 1 /* CommonJS */ || importingFile.impliedNodeFormat === 1 /* CommonJS */)) { return 3 /* CommonJS */; } + switch (exportKind) { case 0 /* Named */: return 0 /* Named */; @@ -149547,6 +134371,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (getAllowSyntheticDefaultImports(compilerOptions)) { return 1 /* Default */; } + const moduleKind = getEmitModuleKind(compilerOptions); switch (moduleKind) { case 2 /* AMD */: @@ -149555,6 +134380,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (isInJSFile(importingFile)) { return isExternalModule(importingFile) || forceImportKeyword ? 2 /* Namespace */ : 3 /* CommonJS */; } + return 3 /* CommonJS */; case 4 /* System */: case 5 /* ES2015 */: @@ -149570,80 +134396,81 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return Debug.assertNever(moduleKind, `Unexpected moduleKind ${moduleKind}`); } } - function getFixesInfoForNonUMDImport({ sourceFile, program, cancellationToken, host, preferences }, symbolToken, useAutoImportProvider) { + function getFixesInfoForNonUMDImport({ + sourceFile, + program, + cancellationToken, + host, + preferences + }, symbolToken, useAutoImportProvider) { const checker = program.getTypeChecker(); const compilerOptions = program.getCompilerOptions(); - return flatMap(getSymbolNamesToImport(sourceFile, checker, symbolToken, compilerOptions), (symbolName2) => { + return flatMap(getSymbolNamesToImport(sourceFile, checker, symbolToken, compilerOptions), symbolName2 => { if (symbolName2 === "default" /* Default */) { return void 0; } const isValidTypeOnlyUseSite = isValidTypeOnlyAliasUseSite(symbolToken); const useRequire = shouldUseRequire(sourceFile, program); const exportInfo = getExportInfos(symbolName2, isJSXTagName(symbolToken), getMeaningFromLocation(symbolToken), cancellationToken, sourceFile, program, useAutoImportProvider, host, preferences); - return arrayFrom( - flatMapIterator(exportInfo.values(), (exportInfos) => getImportFixes(exportInfos, symbolToken.getStart(sourceFile), isValidTypeOnlyUseSite, useRequire, program, sourceFile, host, preferences).fixes), - (fix) => ({ fix, symbolName: symbolName2, errorIdentifierText: symbolToken.text, isJsxNamespaceFix: symbolName2 !== symbolToken.text }) - ); + return arrayFrom(flatMapIterator(exportInfo.values(), exportInfos => getImportFixes(exportInfos, symbolToken.getStart(sourceFile), isValidTypeOnlyUseSite, useRequire, program, sourceFile, host, preferences).fixes), fix => ({ + fix, + symbolName: symbolName2, + errorIdentifierText: symbolToken.text, + isJsxNamespaceFix: symbolName2 !== symbolToken.text + })); }); } function getTypeOnlyPromotionFix(sourceFile, symbolToken, symbolName2, program) { const checker = program.getTypeChecker(); - const symbol = checker.resolveName( - symbolName2, - symbolToken, - 111551 /* Value */, - /*excludeGlobals*/ - true - ); - if (!symbol) - return void 0; + const symbol = checker.resolveName(symbolName2, symbolToken, 111551 /* Value */, /*excludeGlobals*/ + true); + if (!symbol) return void 0; const typeOnlyAliasDeclaration = checker.getTypeOnlyAliasDeclaration(symbol); - if (!typeOnlyAliasDeclaration || getSourceFileOfNode(typeOnlyAliasDeclaration) !== sourceFile) - return void 0; - return { kind: 4 /* PromoteTypeOnly */, typeOnlyAliasDeclaration }; + if (!typeOnlyAliasDeclaration || getSourceFileOfNode(typeOnlyAliasDeclaration) !== sourceFile) return void 0; + return { + kind: 4 /* PromoteTypeOnly */, + typeOnlyAliasDeclaration + }; } function getSymbolNamesToImport(sourceFile, checker, symbolToken, compilerOptions) { const parent2 = symbolToken.parent; if ((isJsxOpeningLikeElement(parent2) || isJsxClosingElement(parent2)) && parent2.tagName === symbolToken && jsxModeNeedsExplicitImport(compilerOptions.jsx)) { const jsxNamespace = checker.getJsxNamespace(sourceFile); if (needsJsxNamespaceFix(jsxNamespace, symbolToken, checker)) { - const needsComponentNameFix = !isIntrinsicJsxName(symbolToken.text) && !checker.resolveName( - symbolToken.text, - symbolToken, - 111551 /* Value */, - /*excludeGlobals*/ - false - ); + const needsComponentNameFix = !isIntrinsicJsxName(symbolToken.text) && !checker.resolveName(symbolToken.text, symbolToken, 111551 /* Value */, /*excludeGlobals*/ + false); return needsComponentNameFix ? [symbolToken.text, jsxNamespace] : [jsxNamespace]; } } return [symbolToken.text]; } function needsJsxNamespaceFix(jsxNamespace, symbolToken, checker) { - if (isIntrinsicJsxName(symbolToken.text)) - return true; - const namespaceSymbol = checker.resolveName( - jsxNamespace, - symbolToken, - 111551 /* Value */, - /*excludeGlobals*/ - true - ); + if (isIntrinsicJsxName(symbolToken.text)) return true; + const namespaceSymbol = checker.resolveName(jsxNamespace, symbolToken, 111551 /* Value */, /*excludeGlobals*/ + true); return !namespaceSymbol || some(namespaceSymbol.declarations, isTypeOnlyImportOrExportDeclaration) && !(namespaceSymbol.flags & 111551 /* Value */); } + function getExportInfos(symbolName2, isJsxTagName, currentTokenMeaning, cancellationToken, fromFile, program, useAutoImportProvider, host, preferences) { var _a; const originalSymbolToExportInfos = createMultiMap(); const packageJsonFilter = createPackageJsonImportFilter(fromFile, preferences, host); const moduleSpecifierCache = (_a = host.getModuleSpecifierCache) == null ? void 0 : _a.call(host); - const getModuleSpecifierResolutionHost = memoizeOne((isFromPackageJson) => { + const getModuleSpecifierResolutionHost = memoizeOne(isFromPackageJson => { return createModuleSpecifierResolutionHost(isFromPackageJson ? host.getPackageJsonAutoImportProvider() : program, host); }); function addSymbol(moduleSymbol, toFile, exportedSymbol, exportKind, program2, isFromPackageJson) { const moduleSpecifierResolutionHost = getModuleSpecifierResolutionHost(isFromPackageJson); if (toFile && isImportableFile(program2, fromFile, toFile, preferences, packageJsonFilter, moduleSpecifierResolutionHost, moduleSpecifierCache) || !toFile && packageJsonFilter.allowsImportingAmbientModule(moduleSymbol, moduleSpecifierResolutionHost)) { const checker = program2.getTypeChecker(); - originalSymbolToExportInfos.add(getUniqueSymbolId(exportedSymbol, checker).toString(), { symbol: exportedSymbol, moduleSymbol, moduleFileName: toFile == null ? void 0 : toFile.fileName, exportKind, targetFlags: skipAlias(exportedSymbol, checker).flags, isFromPackageJson }); + originalSymbolToExportInfos.add(getUniqueSymbolId(exportedSymbol, checker).toString(), { + symbol: exportedSymbol, + moduleSymbol, + moduleFileName: toFile == null ? void 0 : toFile.fileName, + exportKind, + targetFlags: skipAlias(exportedSymbol, checker).flags, + isFromPackageJson + }); } } forEachExternalModuleToImportFrom(program, host, preferences, useAutoImportProvider, (moduleSymbol, sourceFile, program2, isFromPackageJson) => { @@ -149667,19 +134494,23 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (!isJS && getEmitModuleKind(compilerOptions) >= 5 /* ES2015 */) { return allowSyntheticDefaults ? 1 /* Default */ : 2 /* Namespace */; } + if (isJS) { return isExternalModule(importingFile) || forceImportKeyword ? allowSyntheticDefaults ? 1 /* Default */ : 2 /* Namespace */ : 3 /* CommonJS */; } + for (const statement of importingFile.statements) { if (isImportEqualsDeclaration(statement) && !nodeIsMissing(statement.moduleReference)) { return 3 /* CommonJS */; } } + return allowSyntheticDefaults ? 1 /* Default */ : 3 /* CommonJS */; } + function codeActionForFix(context, sourceFile, symbolName2, fix, includeSymbolNameInDescription, program, preferences) { let diag2; - const changes = ts_textChanges_exports.ChangeTracker.with(context, (tracker) => { + const changes = ts_textChanges_exports.ChangeTracker.with(context, tracker => { diag2 = codeActionForFixWorker(tracker, sourceFile, symbolName2, fix, includeSymbolNameInDescription, program, preferences); }); return createCodeFixAction(importFixName, changes, diag2, importFixId, Diagnostics.Add_all_missing_imports); @@ -149693,51 +134524,62 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} case 1 /* JsdocTypeImport */: addImportType(changes, sourceFile, fix, quotePreference); return [Diagnostics.Change_0_to_1, symbolName2, getImportTypePrefix(fix.moduleSpecifier, quotePreference) + symbolName2]; - case 2 /* AddToExisting */: { - const { importClauseOrBindingPattern, importKind, addAsTypeOnly, moduleSpecifier } = fix; - doAddExistingFix( - changes, - sourceFile, - importClauseOrBindingPattern, - importKind === 1 /* Default */ ? { name: symbolName2, addAsTypeOnly } : void 0, - importKind === 0 /* Named */ ? [{ name: symbolName2, addAsTypeOnly }] : emptyArray, - preferences - ); - const moduleSpecifierWithoutQuotes = stripQuotes(moduleSpecifier); - return includeSymbolNameInDescription ? [Diagnostics.Import_0_from_1, symbolName2, moduleSpecifierWithoutQuotes] : [Diagnostics.Update_import_from_0, moduleSpecifierWithoutQuotes]; - } - case 3 /* AddNew */: { - const { importKind, moduleSpecifier, addAsTypeOnly, useRequire, qualification } = fix; - const getDeclarations = useRequire ? getNewRequires : getNewImports; - const defaultImport = importKind === 1 /* Default */ ? { name: symbolName2, addAsTypeOnly } : void 0; - const namedImports = importKind === 0 /* Named */ ? [{ name: symbolName2, addAsTypeOnly }] : void 0; - const namespaceLikeImport = importKind === 2 /* Namespace */ || importKind === 3 /* CommonJS */ ? { importKind, name: (qualification == null ? void 0 : qualification.namespacePrefix) || symbolName2, addAsTypeOnly } : void 0; - insertImports( - changes, - sourceFile, - getDeclarations( - moduleSpecifier, - quotePreference, - defaultImport, - namedImports, - namespaceLikeImport, - program.getCompilerOptions(), - preferences - ), - /*blankLineBetween*/ - true, - preferences - ); - if (qualification) { - addNamespaceQualifier(changes, sourceFile, qualification); + case 2 /* AddToExisting */: + { + const { + importClauseOrBindingPattern, + importKind, + addAsTypeOnly, + moduleSpecifier + } = fix; + doAddExistingFix(changes, sourceFile, importClauseOrBindingPattern, importKind === 1 /* Default */ ? { + name: symbolName2, + addAsTypeOnly + } : void 0, importKind === 0 /* Named */ ? [{ + name: symbolName2, + addAsTypeOnly + }] : emptyArray, preferences); + const moduleSpecifierWithoutQuotes = stripQuotes(moduleSpecifier); + return includeSymbolNameInDescription ? [Diagnostics.Import_0_from_1, symbolName2, moduleSpecifierWithoutQuotes] : [Diagnostics.Update_import_from_0, moduleSpecifierWithoutQuotes]; + } + case 3 /* AddNew */: + { + const { + importKind, + moduleSpecifier, + addAsTypeOnly, + useRequire, + qualification + } = fix; + const getDeclarations = useRequire ? getNewRequires : getNewImports; + const defaultImport = importKind === 1 /* Default */ ? { + name: symbolName2, + addAsTypeOnly + } : void 0; + const namedImports = importKind === 0 /* Named */ ? [{ + name: symbolName2, + addAsTypeOnly + }] : void 0; + const namespaceLikeImport = importKind === 2 /* Namespace */ || importKind === 3 /* CommonJS */ ? { + importKind, + name: (qualification == null ? void 0 : qualification.namespacePrefix) || symbolName2, + addAsTypeOnly + } : void 0; + insertImports(changes, sourceFile, getDeclarations(moduleSpecifier, quotePreference, defaultImport, namedImports, namespaceLikeImport, program.getCompilerOptions(), preferences), /*blankLineBetween*/ + true, preferences); + if (qualification) { + addNamespaceQualifier(changes, sourceFile, qualification); + } + return includeSymbolNameInDescription ? [Diagnostics.Import_0_from_1, symbolName2, moduleSpecifier] : [Diagnostics.Add_import_from_0, moduleSpecifier]; + } + case 4 /* PromoteTypeOnly */: + { + const { + typeOnlyAliasDeclaration + } = fix; + const promotedDeclaration = promoteFromTypeOnly(changes, typeOnlyAliasDeclaration, program, sourceFile, preferences); + return promotedDeclaration.kind === 276 /* ImportSpecifier */ ? [Diagnostics.Remove_type_from_import_of_0_from_1, symbolName2, getModuleSpecifierText(promotedDeclaration.parent.parent)] : [Diagnostics.Remove_type_from_import_declaration_from_0, getModuleSpecifierText(promotedDeclaration)]; } - return includeSymbolNameInDescription ? [Diagnostics.Import_0_from_1, symbolName2, moduleSpecifier] : [Diagnostics.Add_import_from_0, moduleSpecifier]; - } - case 4 /* PromoteTypeOnly */: { - const { typeOnlyAliasDeclaration } = fix; - const promotedDeclaration = promoteFromTypeOnly(changes, typeOnlyAliasDeclaration, program, sourceFile, preferences); - return promotedDeclaration.kind === 276 /* ImportSpecifier */ ? [Diagnostics.Remove_type_from_import_of_0_from_1, symbolName2, getModuleSpecifierText(promotedDeclaration.parent.parent)] : [Diagnostics.Remove_type_from_import_declaration_from_0, getModuleSpecifierText(promotedDeclaration)]; - } default: return Debug.assertNever(fix, `Unexpected fix kind ${fix.kind}`); } @@ -149754,13 +134596,8 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (aliasDeclaration.isTypeOnly) { const sortKind = ts_OrganizeImports_exports.detectImportSpecifierSorting(aliasDeclaration.parent.elements, preferences); if (aliasDeclaration.parent.elements.length > 1 && sortKind) { - const newSpecifier = factory.updateImportSpecifier( - aliasDeclaration, - /*isTypeOnly*/ - false, - aliasDeclaration.propertyName, - aliasDeclaration.name - ); + const newSpecifier = factory.updateImportSpecifier(aliasDeclaration, /*isTypeOnly*/ + false, aliasDeclaration.propertyName, aliasDeclaration.name); const comparer = ts_OrganizeImports_exports.getOrganizeImportsComparer(preferences, sortKind === 2 /* CaseInsensitive */); const insertionIndex = ts_OrganizeImports_exports.getImportSpecifierInsertionIndex(aliasDeclaration.parent.elements, newSpecifier, comparer); if (aliasDeclaration.parent.elements.indexOf(aliasDeclaration) !== insertionIndex) { @@ -149822,20 +134659,18 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} addElementToBindingPattern(clause, defaultImport.name, "default"); } for (const specifier of namedImports) { - addElementToBindingPattern( - clause, - specifier.name, - /*propertyName*/ - void 0 - ); + addElementToBindingPattern(clause, specifier.name, /*propertyName*/ + void 0); } return; } - const promoteFromTypeOnly2 = clause.isTypeOnly && some([defaultImport, ...namedImports], (i) => (i == null ? void 0 : i.addAsTypeOnly) === 4 /* NotAllowed */); + const promoteFromTypeOnly2 = clause.isTypeOnly && some([defaultImport, ...namedImports], i => (i == null ? void 0 : i.addAsTypeOnly) === 4 /* NotAllowed */); const existingSpecifiers = clause.namedBindings && ((_a = tryCast(clause.namedBindings, isNamedImports)) == null ? void 0 : _a.elements); if (defaultImport) { Debug.assert(!clause.name, "Cannot add a default import to an import clause that already has one"); - changes.insertNodeAt(sourceFile, clause.getStart(sourceFile), factory.createIdentifier(defaultImport.name), { suffix: ", " }); + changes.insertNodeAt(sourceFile, clause.getStart(sourceFile), factory.createIdentifier(defaultImport.name), { + suffix: ", " + }); } if (namedImports.length) { let ignoreCaseForSorting; @@ -149847,21 +134682,14 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} ignoreCaseForSorting = targetImportSorting === 2 /* CaseInsensitive */; } } + if (ignoreCaseForSorting === void 0) { ignoreCaseForSorting = ts_OrganizeImports_exports.detectSorting(sourceFile, preferences) === 2 /* CaseInsensitive */; } + const comparer = ts_OrganizeImports_exports.getOrganizeImportsComparer(preferences, ignoreCaseForSorting); - const newSpecifiers = stableSort( - namedImports.map( - (namedImport) => factory.createImportSpecifier( - (!clause.isTypeOnly || promoteFromTypeOnly2) && shouldUseTypeOnly(namedImport, preferences), - /*propertyName*/ - void 0, - factory.createIdentifier(namedImport.name) - ) - ), - (s1, s2) => ts_OrganizeImports_exports.compareImportOrExportSpecifiers(s1, s2, comparer) - ); + const newSpecifiers = stableSort(namedImports.map(namedImport => factory.createImportSpecifier((!clause.isTypeOnly || promoteFromTypeOnly2) && shouldUseTypeOnly(namedImport, preferences), /*propertyName*/ + void 0, factory.createIdentifier(namedImport.name))), (s1, s2) => ts_OrganizeImports_exports.compareImportOrExportSpecifiers(s1, s2, comparer)); const specifierSort = (existingSpecifiers == null ? void 0 : existingSpecifiers.length) && ts_OrganizeImports_exports.detectImportSpecifierSorting(existingSpecifiers, preferences); if (specifierSort && !(ignoreCaseForSorting && specifierSort === 1 /* CaseSensitive */)) { for (const spec of newSpecifiers) { @@ -149892,12 +134720,8 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } } function addElementToBindingPattern(bindingPattern, name, propertyName) { - const element = factory.createBindingElement( - /*dotDotDotToken*/ - void 0, - propertyName, - name - ); + const element = factory.createBindingElement( /*dotDotDotToken*/ + void 0, propertyName, name); if (bindingPattern.elements.length) { changes.insertNodeInListAfter(sourceFile, last(bindingPattern.elements), element); } else { @@ -149905,65 +134729,46 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } } } - function addNamespaceQualifier(changes, sourceFile, { namespacePrefix, usagePosition }) { + function addNamespaceQualifier(changes, sourceFile, { + namespacePrefix, + usagePosition + }) { changes.insertText(sourceFile, usagePosition, namespacePrefix + "."); } - function addImportType(changes, sourceFile, { moduleSpecifier, usagePosition: position }, quotePreference) { + function addImportType(changes, sourceFile, { + moduleSpecifier, + usagePosition: position + }, quotePreference) { changes.insertText(sourceFile, position, getImportTypePrefix(moduleSpecifier, quotePreference)); } function getImportTypePrefix(moduleSpecifier, quotePreference) { const quote2 = getQuoteFromPreference(quotePreference); return `import(${quote2}${moduleSpecifier}${quote2}).`; } - function needsTypeOnly({ addAsTypeOnly }) { + function needsTypeOnly({ + addAsTypeOnly + }) { return addAsTypeOnly === 2 /* Required */; } + function shouldUseTypeOnly(info, preferences) { return needsTypeOnly(info) || !!preferences.preferTypeOnlyAutoImports && info.addAsTypeOnly !== 4 /* NotAllowed */; } + function getNewImports(moduleSpecifier, quotePreference, defaultImport, namedImports, namespaceLikeImport, compilerOptions, preferences) { const quotedModuleSpecifier = makeStringLiteral(moduleSpecifier, quotePreference); let statements; if (defaultImport !== void 0 || (namedImports == null ? void 0 : namedImports.length)) { - const topLevelTypeOnly = (!defaultImport || needsTypeOnly(defaultImport)) && every(namedImports, needsTypeOnly) || (compilerOptions.verbatimModuleSyntax || preferences.preferTypeOnlyAutoImports) && (defaultImport == null ? void 0 : defaultImport.addAsTypeOnly) !== 4 /* NotAllowed */ && !some(namedImports, (i) => i.addAsTypeOnly === 4 /* NotAllowed */); - statements = combine( - statements, - makeImport( - defaultImport && factory.createIdentifier(defaultImport.name), - namedImports == null ? void 0 : namedImports.map( - (namedImport) => factory.createImportSpecifier( - !topLevelTypeOnly && shouldUseTypeOnly(namedImport, preferences), - /*propertyName*/ - void 0, - factory.createIdentifier(namedImport.name) - ) - ), - moduleSpecifier, - quotePreference, - topLevelTypeOnly - ) - ); + const topLevelTypeOnly = (!defaultImport || needsTypeOnly(defaultImport)) && every(namedImports, needsTypeOnly) || (compilerOptions.verbatimModuleSyntax || preferences.preferTypeOnlyAutoImports) && (defaultImport == null ? void 0 : defaultImport.addAsTypeOnly) !== 4 /* NotAllowed */ && !some(namedImports, i => i.addAsTypeOnly === 4 /* NotAllowed */); + statements = combine(statements, makeImport(defaultImport && factory.createIdentifier(defaultImport.name), namedImports == null ? void 0 : namedImports.map(namedImport => factory.createImportSpecifier(!topLevelTypeOnly && shouldUseTypeOnly(namedImport, preferences), /*propertyName*/ + void 0, factory.createIdentifier(namedImport.name))), moduleSpecifier, quotePreference, topLevelTypeOnly)); } if (namespaceLikeImport) { - const declaration = namespaceLikeImport.importKind === 3 /* CommonJS */ ? factory.createImportEqualsDeclaration( - /*modifiers*/ - void 0, - shouldUseTypeOnly(namespaceLikeImport, preferences), - factory.createIdentifier(namespaceLikeImport.name), - factory.createExternalModuleReference(quotedModuleSpecifier) - ) : factory.createImportDeclaration( - /*modifiers*/ - void 0, - factory.createImportClause( - shouldUseTypeOnly(namespaceLikeImport, preferences), - /*name*/ - void 0, - factory.createNamespaceImport(factory.createIdentifier(namespaceLikeImport.name)) - ), - quotedModuleSpecifier, - /*attributes*/ - void 0 - ); + const declaration = namespaceLikeImport.importKind === 3 /* CommonJS */ ? factory.createImportEqualsDeclaration( /*modifiers*/ + void 0, shouldUseTypeOnly(namespaceLikeImport, preferences), factory.createIdentifier(namespaceLikeImport.name), factory.createExternalModuleReference(quotedModuleSpecifier)) : factory.createImportDeclaration( /*modifiers*/ + void 0, factory.createImportClause(shouldUseTypeOnly(namespaceLikeImport, preferences), /*name*/ + void 0, factory.createNamespaceImport(factory.createIdentifier(namespaceLikeImport.name))), quotedModuleSpecifier, /*attributes*/ + void 0); statements = combine(statements, declaration); } return Debug.checkDefined(statements); @@ -149972,20 +134777,14 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} const quotedModuleSpecifier = makeStringLiteral(moduleSpecifier, quotePreference); let statements; if (defaultImport || (namedImports == null ? void 0 : namedImports.length)) { - const bindingElements = (namedImports == null ? void 0 : namedImports.map(({ name }) => factory.createBindingElement( - /*dotDotDotToken*/ - void 0, - /*propertyName*/ - void 0, + const bindingElements = (namedImports == null ? void 0 : namedImports.map(({ name - ))) || []; + }) => factory.createBindingElement( /*dotDotDotToken*/ + void 0, /*propertyName*/ + void 0, name))) || []; if (defaultImport) { - bindingElements.unshift(factory.createBindingElement( - /*dotDotDotToken*/ - void 0, - "default", - defaultImport.name - )); + bindingElements.unshift(factory.createBindingElement( /*dotDotDotToken*/ + void 0, "default", defaultImport.name)); } const declaration = createConstEqualsRequireDeclaration(factory.createObjectBindingPattern(bindingElements), quotedModuleSpecifier); statements = combine(statements, declaration); @@ -149997,28 +134796,17 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return Debug.checkDefined(statements); } function createConstEqualsRequireDeclaration(name, quotedModuleSpecifier) { - return factory.createVariableStatement( - /*modifiers*/ - void 0, - factory.createVariableDeclarationList([ - factory.createVariableDeclaration( - typeof name === "string" ? factory.createIdentifier(name) : name, - /*exclamationToken*/ - void 0, - /*type*/ - void 0, - factory.createCallExpression( - factory.createIdentifier("require"), - /*typeArguments*/ - void 0, - [quotedModuleSpecifier] - ) - ) - ], 2 /* Const */) - ); + return factory.createVariableStatement( /*modifiers*/ + void 0, factory.createVariableDeclarationList([factory.createVariableDeclaration(typeof name === "string" ? factory.createIdentifier(name) : name, /*exclamationToken*/ + void 0, /*type*/ + void 0, factory.createCallExpression(factory.createIdentifier("require"), /*typeArguments*/ + void 0, [quotedModuleSpecifier]))], 2 /* Const */)); } - function symbolHasMeaning({ declarations }, meaning) { - return some(declarations, (decl) => !!(getMeaningFromDeclaration(decl) & meaning)); + + function symbolHasMeaning({ + declarations + }, meaning) { + return some(declarations, decl => !!(getMeaningFromDeclaration(decl) & meaning)); } function moduleSymbolToValidIdentifier(moduleSymbol, target, forceCapitalize) { return moduleSpecifierToValidIdentifier(removeFileExtension(stripQuotes(moduleSymbol.name)), target, forceCapitalize); @@ -150054,60 +134842,44 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} var init_importFixes = __esm({ "src/services/codefixes/importFixes.ts"() { "use strict"; + init_ts4(); init_ts_codefix(); importFixName = "import"; importFixId = "fixMissingImport"; - errorCodes18 = [ - Diagnostics.Cannot_find_name_0.code, - Diagnostics.Cannot_find_name_0_Did_you_mean_1.code, - Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0.code, - Diagnostics.Cannot_find_name_0_Did_you_mean_the_static_member_1_0.code, - Diagnostics.Cannot_find_namespace_0.code, - Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code, - Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here.code, - Diagnostics.No_value_exists_in_scope_for_the_shorthand_property_0_Either_declare_one_or_provide_an_initializer.code, - Diagnostics._0_cannot_be_used_as_a_value_because_it_was_imported_using_import_type.code - ]; + errorCodes18 = [Diagnostics.Cannot_find_name_0.code, Diagnostics.Cannot_find_name_0_Did_you_mean_1.code, Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0.code, Diagnostics.Cannot_find_name_0_Did_you_mean_the_static_member_1_0.code, Diagnostics.Cannot_find_namespace_0.code, Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code, Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here.code, Diagnostics.No_value_exists_in_scope_for_the_shorthand_property_0_Either_declare_one_or_provide_an_initializer.code, Diagnostics._0_cannot_be_used_as_a_value_because_it_was_imported_using_import_type.code]; registerCodeFix({ errorCodes: errorCodes18, getCodeActions(context) { - const { errorCode, preferences, sourceFile, span, program } = context; - const info = getFixInfos( - context, + const { errorCode, - span.start, - /*useAutoImportProvider*/ - true - ); - if (!info) - return void 0; - return info.map( - ({ fix, symbolName: symbolName2, errorIdentifierText }) => codeActionForFix( - context, - sourceFile, - symbolName2, - fix, - /*includeSymbolNameInDescription*/ - symbolName2 !== errorIdentifierText, - program, - preferences - ) - ); + preferences, + sourceFile, + span, + program + } = context; + const info = getFixInfos(context, errorCode, span.start, /*useAutoImportProvider*/ + true); + if (!info) return void 0; + return info.map(({ + fix, + symbolName: symbolName2, + errorIdentifierText + }) => codeActionForFix(context, sourceFile, symbolName2, fix, /*includeSymbolNameInDescription*/ + symbolName2 !== errorIdentifierText, program, preferences)); }, fixIds: [importFixId], - getAllCodeActions: (context) => { - const { sourceFile, program, preferences, host, cancellationToken } = context; - const importAdder = createImportAdderWorker( + getAllCodeActions: context => { + const { sourceFile, program, - /*useAutoImportProvider*/ - true, preferences, host, cancellationToken - ); - eachDiagnostic(context, errorCodes18, (diag2) => importAdder.addImportFromDiagnostic(diag2, context)); + } = context; + const importAdder = createImportAdderWorker(sourceFile, program, /*useAutoImportProvider*/ + true, preferences, host, cancellationToken); + eachDiagnostic(context, errorCodes18, diag2 => importAdder.addImportFromDiagnostic(diag2, context)); return createCombinedCodeActions(ts_textChanges_exports.ChangeTracker.with(context, importAdder.writeFixes)); } }); @@ -150116,57 +134888,49 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} // src/services/codefixes/fixAddMissingConstraint.ts function getInfo6(program, sourceFile, span) { - const diag2 = find(program.getSemanticDiagnostics(sourceFile), (diag3) => diag3.start === span.start && diag3.length === span.length); - if (diag2 === void 0 || diag2.relatedInformation === void 0) - return; - const related = find(diag2.relatedInformation, (related2) => related2.code === Diagnostics.This_type_parameter_might_need_an_extends_0_constraint.code); - if (related === void 0 || related.file === void 0 || related.start === void 0 || related.length === void 0) - return; + const diag2 = find(program.getSemanticDiagnostics(sourceFile), diag3 => diag3.start === span.start && diag3.length === span.length); + if (diag2 === void 0 || diag2.relatedInformation === void 0) return; + const related = find(diag2.relatedInformation, related2 => related2.code === Diagnostics.This_type_parameter_might_need_an_extends_0_constraint.code); + if (related === void 0 || related.file === void 0 || related.start === void 0 || related.length === void 0) return; let declaration = findAncestorMatchingSpan(related.file, createTextSpan(related.start, related.length)); - if (declaration === void 0) - return; + if (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); - return { constraint, declaration, token }; + return { + constraint, + declaration, + token + }; } return void 0; } function addMissingConstraint(changes, program, preferences, host, sourceFile, info) { - const { declaration, constraint } = info; + const { + declaration, + constraint + } = info; const checker = program.getTypeChecker(); if (isString(constraint)) { changes.insertText(sourceFile, declaration.name.end, ` extends ${constraint}`); } else { const scriptTarget = getEmitScriptTarget(program.getCompilerOptions()); - const tracker = getNoopSymbolTrackerWithResolver({ program, host }); + const tracker = getNoopSymbolTrackerWithResolver({ + program, + host + }); const importAdder = createImportAdder(sourceFile, program, preferences, host); - const typeNode = typeToAutoImportableTypeNode( - checker, - importAdder, - constraint, - /*contextNode*/ - void 0, - scriptTarget, - /*flags*/ - void 0, - tracker - ); + const typeNode = typeToAutoImportableTypeNode(checker, importAdder, constraint, /*contextNode*/ + void 0, scriptTarget, /*flags*/ + void 0, tracker); if (typeNode) { - changes.replaceNode(sourceFile, declaration, factory.updateTypeParameterDeclaration( - declaration, - /*modifiers*/ - void 0, - declaration.name, - typeNode, - declaration.default - )); + changes.replaceNode(sourceFile, declaration, factory.updateTypeParameterDeclaration(declaration, /*modifiers*/ + void 0, declaration.name, typeNode, declaration.default)); importAdder.writeFixes(changes); } } @@ -150186,37 +134950,39 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} var init_fixAddMissingConstraint = __esm({ "src/services/codefixes/fixAddMissingConstraint.ts"() { "use strict"; + init_ts4(); init_ts_codefix(); fixId17 = "addMissingConstraint"; errorCodes19 = [ - // We want errors this could be attached to: - // Diagnostics.This_type_parameter_probably_needs_an_extends_0_constraint - Diagnostics.Type_0_is_not_comparable_to_type_1.code, - Diagnostics.Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated.code, - Diagnostics.Type_0_is_not_assignable_to_type_1_with_exactOptionalPropertyTypes_Colon_true_Consider_adding_undefined_to_the_types_of_the_target_s_properties.code, - Diagnostics.Type_0_is_not_assignable_to_type_1.code, - Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1_with_exactOptionalPropertyTypes_Colon_true_Consider_adding_undefined_to_the_types_of_the_target_s_properties.code, - Diagnostics.Property_0_is_incompatible_with_index_signature.code, - Diagnostics.Property_0_in_type_1_is_not_assignable_to_type_2.code, - Diagnostics.Type_0_does_not_satisfy_the_constraint_1.code - ]; + // We want errors this could be attached to: + // Diagnostics.This_type_parameter_probably_needs_an_extends_0_constraint + Diagnostics.Type_0_is_not_comparable_to_type_1.code, Diagnostics.Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated.code, Diagnostics.Type_0_is_not_assignable_to_type_1_with_exactOptionalPropertyTypes_Colon_true_Consider_adding_undefined_to_the_types_of_the_target_s_properties.code, Diagnostics.Type_0_is_not_assignable_to_type_1.code, Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1_with_exactOptionalPropertyTypes_Colon_true_Consider_adding_undefined_to_the_types_of_the_target_s_properties.code, Diagnostics.Property_0_is_incompatible_with_index_signature.code, Diagnostics.Property_0_in_type_1_is_not_assignable_to_type_2.code, Diagnostics.Type_0_does_not_satisfy_the_constraint_1.code]; registerCodeFix({ errorCodes: errorCodes19, getCodeActions(context) { - const { sourceFile, span, program, preferences, host } = context; + const { + sourceFile, + span, + program, + preferences, + host + } = context; const info = getInfo6(program, sourceFile, span); - if (info === void 0) - return; - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => addMissingConstraint(t, program, preferences, host, sourceFile, info)); + 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)]; }, fixIds: [fixId17], - getAllCodeActions: (context) => { - const { program, preferences, host } = context; - const seen = /* @__PURE__ */ new Map(); - return createCombinedCodeActions(ts_textChanges_exports.ChangeTracker.with(context, (changes) => { - eachDiagnostic(context, errorCodes19, (diag2) => { + getAllCodeActions: context => { + const { + program, + preferences, + host + } = context; + const seen = /* @__PURE__ */new Map(); + return createCombinedCodeActions(ts_textChanges_exports.ChangeTracker.with(context, changes => { + eachDiagnostic(context, errorCodes19, diag2 => { const info = getInfo6(program, diag2.file, createTextSpan(diag2.start, diag2.length)); if (info) { if (addToSeen(seen, getNodeId(info.declaration))) { @@ -150258,10 +135024,14 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} const modifiers = classElement.modifiers || emptyArray; const staticModifier = find(modifiers, isStaticModifier); const abstractModifier = find(modifiers, isAbstractModifier); - const accessibilityModifier = find(modifiers, (m) => isAccessibilityModifier(m.kind)); + const accessibilityModifier = find(modifiers, m => isAccessibilityModifier(m.kind)); const lastDecorator = findLast(modifiers, isDecorator); const modifierPos = abstractModifier ? abstractModifier.end : staticModifier ? staticModifier.end : accessibilityModifier ? accessibilityModifier.end : lastDecorator ? skipTrivia(sourceFile.text, lastDecorator.end) : classElement.getStart(sourceFile); - const options = accessibilityModifier || staticModifier || abstractModifier ? { prefix: " " } : { suffix: " " }; + const options = accessibilityModifier || staticModifier || abstractModifier ? { + prefix: " " + } : { + suffix: " " + }; changeTracker.insertModifierAt(sourceFile, modifierPos, 164 /* OverrideKeyword */, options); } function doRemoveOverrideModifierChange(changeTracker, sourceFile, pos) { @@ -150290,9 +135060,8 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } function findContainerClassElementLike(sourceFile, pos) { const token = getTokenAtPosition(sourceFile, pos); - const classElement = findAncestor(token, (node) => { - if (isClassLike(node)) - return "quit"; + const classElement = findAncestor(token, node => { + if (isClassLike(node)) return "quit"; return isClassElementLikeHasJSDoc(node); }); Debug.assert(classElement && isClassElementLikeHasJSDoc(classElement)); @@ -150302,22 +135071,13 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} var init_fixOverrideModifier = __esm({ "src/services/codefixes/fixOverrideModifier.ts"() { "use strict"; + init_ts4(); init_ts_codefix(); fixName = "fixOverrideModifier"; fixAddOverrideId = "fixAddOverrideModifier"; fixRemoveOverrideId = "fixRemoveOverrideModifier"; - errorCodes20 = [ - Diagnostics.This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0.code, - Diagnostics.This_member_cannot_have_an_override_modifier_because_its_containing_class_0_does_not_extend_another_class.code, - Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_an_abstract_method_that_is_declared_in_the_base_class_0.code, - Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_a_member_in_the_base_class_0.code, - Diagnostics.This_parameter_property_must_have_an_override_modifier_because_it_overrides_a_member_in_base_class_0.code, - Diagnostics.This_member_must_have_a_JSDoc_comment_with_an_override_tag_because_it_overrides_a_member_in_the_base_class_0.code, - Diagnostics.This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_its_containing_class_0_does_not_extend_another_class.code, - Diagnostics.This_parameter_property_must_have_a_JSDoc_comment_with_an_override_tag_because_it_overrides_a_member_in_the_base_class_0.code, - Diagnostics.This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_it_is_not_declared_in_the_base_class_0.code - ]; + errorCodes20 = [Diagnostics.This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0.code, Diagnostics.This_member_cannot_have_an_override_modifier_because_its_containing_class_0_does_not_extend_another_class.code, Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_an_abstract_method_that_is_declared_in_the_base_class_0.code, Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_a_member_in_the_base_class_0.code, Diagnostics.This_parameter_property_must_have_an_override_modifier_because_it_overrides_a_member_in_base_class_0.code, Diagnostics.This_member_must_have_a_JSDoc_comment_with_an_override_tag_because_it_overrides_a_member_in_the_base_class_0.code, Diagnostics.This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_its_containing_class_0_does_not_extend_another_class.code, Diagnostics.This_parameter_property_must_have_a_JSDoc_comment_with_an_override_tag_because_it_overrides_a_member_in_the_base_class_0.code, Diagnostics.This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_it_is_not_declared_in_the_base_class_0.code]; errorCodeFixIdMap = { // case #1: [Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_a_member_in_the_base_class_0.code]: { @@ -150373,19 +135133,26 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} registerCodeFix({ errorCodes: errorCodes20, getCodeActions: function getCodeActionsToFixOverrideModifierIssues(context) { - const { errorCode, span } = context; + const { + errorCode, + span + } = context; const info = errorCodeFixIdMap[errorCode]; - if (!info) - return emptyArray; - const { descriptions, fixId: fixId52, fixAllDescriptions } = info; - const changes = ts_textChanges_exports.ChangeTracker.with(context, (changes2) => dispatchChanges(changes2, context, errorCode, span.start)); - return [ - createCodeFixActionMaybeFixAll(fixName, changes, descriptions, fixId52, fixAllDescriptions) - ]; + if (!info) return emptyArray; + const { + descriptions, + fixId: fixId52, + fixAllDescriptions + } = info; + const changes = ts_textChanges_exports.ChangeTracker.with(context, changes2 => dispatchChanges(changes2, context, errorCode, span.start)); + return [createCodeFixActionMaybeFixAll(fixName, changes, descriptions, fixId52, fixAllDescriptions)]; }, fixIds: [fixName, fixAddOverrideId, fixRemoveOverrideId], - getAllCodeActions: (context) => codeFixAll(context, errorCodes20, (changes, diag2) => { - const { code, start } = diag2; + getAllCodeActions: context => codeFixAll(context, errorCodes20, (changes, diag2) => { + const { + code, + start + } = diag2; const info = errorCodeFixIdMap[code]; if (!info || info.fixId !== context.fixId) { return; @@ -150400,11 +135167,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} function doChange14(changes, sourceFile, node, preferences) { const quotePreference = getQuotePreference(sourceFile, preferences); const argumentsExpression = factory.createStringLiteral(node.name.text, quotePreference === 0 /* Single */); - changes.replaceNode( - sourceFile, - node, - isPropertyAccessChain(node) ? factory.createElementAccessChain(node.expression, node.questionDotToken, argumentsExpression) : factory.createElementAccessExpression(node.expression, argumentsExpression) - ); + changes.replaceNode(sourceFile, node, isPropertyAccessChain(node) ? factory.createElementAccessChain(node.expression, node.questionDotToken, argumentsExpression) : factory.createElementAccessExpression(node.expression, argumentsExpression)); } function getPropertyAccessExpression(sourceFile, pos) { return cast(getTokenAtPosition(sourceFile, pos).parent, isPropertyAccessExpression); @@ -150413,22 +135176,25 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} var init_fixNoPropertyAccessFromIndexSignature = __esm({ "src/services/codefixes/fixNoPropertyAccessFromIndexSignature.ts"() { "use strict"; + init_ts4(); init_ts_codefix(); fixId18 = "fixNoPropertyAccessFromIndexSignature"; - errorCodes21 = [ - Diagnostics.Property_0_comes_from_an_index_signature_so_it_must_be_accessed_with_0.code - ]; + errorCodes21 = [Diagnostics.Property_0_comes_from_an_index_signature_so_it_must_be_accessed_with_0.code]; registerCodeFix({ errorCodes: errorCodes21, fixIds: [fixId18], getCodeActions(context) { - const { sourceFile, span, preferences } = context; + const { + sourceFile, + span, + preferences + } = context; const property = getPropertyAccessExpression(sourceFile, span.start); - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange14(t, context.sourceFile, property, preferences)); + const changes = ts_textChanges_exports.ChangeTracker.with(context, t => doChange14(t, context.sourceFile, property, preferences)); return [createCodeFixAction(fixId18, changes, [Diagnostics.Use_element_access_for_0, property.name.text], fixId18, Diagnostics.Use_element_access_for_all_undeclared_properties)]; }, - getAllCodeActions: (context) => codeFixAll(context, errorCodes21, (changes, diag2) => doChange14(changes, diag2.file, getPropertyAccessExpression(diag2.file, diag2.start), context.preferences)) + getAllCodeActions: context => codeFixAll(context, errorCodes21, (changes, diag2) => doChange14(changes, diag2.file, getPropertyAccessExpression(diag2.file, diag2.start), context.preferences)) }); } }); @@ -150436,26 +135202,18 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} // src/services/codefixes/fixImplicitThis.ts function doChange15(changes, sourceFile, pos, checker) { const token = getTokenAtPosition(sourceFile, pos); - if (!isThis(token)) - return void 0; - const fn = getThisContainer( - token, - /*includeArrowFunctions*/ - false, - /*includeClassComputedPropertyName*/ - false - ); - if (!isFunctionDeclaration(fn) && !isFunctionExpression(fn)) - return void 0; - if (!isSourceFile(getThisContainer( - fn, - /*includeArrowFunctions*/ - false, - /*includeClassComputedPropertyName*/ - false - ))) { + if (!isThis(token)) return void 0; + const fn = getThisContainer(token, /*includeArrowFunctions*/ + false, /*includeClassComputedPropertyName*/ + false); + if (!isFunctionDeclaration(fn) && !isFunctionExpression(fn)) return void 0; + if (!isSourceFile(getThisContainer(fn, /*includeArrowFunctions*/ + false, /*includeClassComputedPropertyName*/ + false))) { const fnKeyword = Debug.checkDefined(findChildOfKind(fn, 100 /* FunctionKeyword */, sourceFile)); - const { name } = fn; + const { + name + } = fn; const body = Debug.checkDefined(fn.body); if (isFunctionExpression(fn)) { if (name && ts_FindAllReferences_exports.Core.isSymbolReferencedInFile(name, checker, sourceFile, body)) { @@ -150479,6 +135237,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} var init_fixImplicitThis = __esm({ "src/services/codefixes/fixImplicitThis.ts"() { "use strict"; + init_ts4(); init_ts_codefix(); fixId19 = "fixImplicitThis"; @@ -150486,15 +135245,19 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} registerCodeFix({ errorCodes: errorCodes22, getCodeActions: function getCodeActionsToFixImplicitThis(context) { - const { sourceFile, program, span } = context; + const { + sourceFile, + program, + span + } = context; let diagnostic; - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => { + const changes = ts_textChanges_exports.ChangeTracker.with(context, t => { diagnostic = doChange15(t, sourceFile, span.start, program.getTypeChecker()); }); return diagnostic ? [createCodeFixAction(fixId19, changes, diagnostic, fixId19, Diagnostics.Fix_all_implicit_this_errors)] : emptyArray; }, fixIds: [fixId19], - getAllCodeActions: (context) => codeFixAll(context, errorCodes22, (changes, diag2) => { + getAllCodeActions: context => codeFixAll(context, errorCodes22, (changes, diag2) => { doChange15(changes, diag2.file, diag2.start, context.program.getTypeChecker()); }) }); @@ -150507,38 +135270,39 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} 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.text : void 0; - if (moduleSpecifier === void 0) - return void 0; - const resolvedModule = (_a = program.getResolvedModule( - sourceFile, - moduleSpecifier, - /*mode*/ - void 0 - )) == null ? void 0 : _a.resolvedModule; - if (resolvedModule === void 0) - return void 0; + if (moduleSpecifier === void 0) return void 0; + const resolvedModule = (_a = program.getResolvedModule(sourceFile, moduleSpecifier, /*mode*/ + void 0)) == 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; - const exportName = { node: token, isTypeOnly: isTypeDeclaration(node) }; - return { exportName, node, moduleSourceFile, moduleSpecifier }; + if (node === void 0) return void 0; + const exportName = { + node: token, + isTypeOnly: isTypeDeclaration(node) + }; + return { + exportName, + node, + moduleSourceFile, + moduleSpecifier + }; } return void 0; } - function doChange16(changes, program, { exportName, node, moduleSourceFile }) { + function doChange16(changes, program, { + exportName, + node, + moduleSourceFile + }) { const exportDeclaration = tryGetExportDeclaration(moduleSourceFile, exportName.isTypeOnly); if (exportDeclaration) { updateExport(changes, program, moduleSourceFile, exportDeclaration, [exportName]); @@ -150558,55 +135322,26 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } } function tryGetExportDeclaration(sourceFile, isTypeOnly) { - const predicate = (node) => isExportDeclaration(node) && (isTypeOnly && node.isTypeOnly || !node.isTypeOnly); + const predicate = node => isExportDeclaration(node) && (isTypeOnly && node.isTypeOnly || !node.isTypeOnly); return findLast(sourceFile.statements, predicate); } function updateExport(changes, program, sourceFile, node, names) { const namedExports = node.exportClause && isNamedExports(node.exportClause) ? node.exportClause.elements : factory.createNodeArray([]); - const allowTypeModifier = !node.isTypeOnly && !!(getIsolatedModules(program.getCompilerOptions()) || find(namedExports, (e) => e.isTypeOnly)); - changes.replaceNode( - sourceFile, - node, - factory.updateExportDeclaration( - node, - node.modifiers, - node.isTypeOnly, - factory.createNamedExports( - factory.createNodeArray( - [...namedExports, ...createExportSpecifiers(names, allowTypeModifier)], - /*hasTrailingComma*/ - namedExports.hasTrailingComma - ) - ), - node.moduleSpecifier, - node.attributes - ) - ); + const allowTypeModifier = !node.isTypeOnly && !!(getIsolatedModules(program.getCompilerOptions()) || find(namedExports, e => e.isTypeOnly)); + changes.replaceNode(sourceFile, node, factory.updateExportDeclaration(node, node.modifiers, node.isTypeOnly, factory.createNamedExports(factory.createNodeArray([...namedExports, ...createExportSpecifiers(names, allowTypeModifier)], /*hasTrailingComma*/ + namedExports.hasTrailingComma)), node.moduleSpecifier, node.attributes)); } function createExport(changes, program, sourceFile, names) { - changes.insertNodeAtEndOfScope(sourceFile, sourceFile, factory.createExportDeclaration( - /*modifiers*/ - void 0, - /*isTypeOnly*/ - false, - factory.createNamedExports(createExportSpecifiers( - names, - /*allowTypeModifier*/ - getIsolatedModules(program.getCompilerOptions()) - )), - /*moduleSpecifier*/ - void 0, - /*attributes*/ - void 0 - )); + changes.insertNodeAtEndOfScope(sourceFile, sourceFile, factory.createExportDeclaration( /*modifiers*/ + void 0, /*isTypeOnly*/ + false, factory.createNamedExports(createExportSpecifiers(names, /*allowTypeModifier*/ + getIsolatedModules(program.getCompilerOptions()))), /*moduleSpecifier*/ + void 0, /*attributes*/ + void 0)); } function createExportSpecifiers(names, allowTypeModifier) { - return factory.createNodeArray(map(names, (n) => factory.createExportSpecifier( - allowTypeModifier && n.isTypeOnly, - /*propertyName*/ - void 0, - n.node - ))); + return factory.createNodeArray(map(names, n => factory.createExportSpecifier(allowTypeModifier && n.isTypeOnly, /*propertyName*/ + void 0, n.node))); } function getNodeOfSymbol(symbol) { if (symbol.valueDeclaration === void 0) { @@ -150620,36 +135355,46 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} var init_fixImportNonExportedMember = __esm({ "src/services/codefixes/fixImportNonExportedMember.ts"() { "use strict"; + init_ts4(); init_ts_codefix(); fixId20 = "fixImportNonExportedMember"; - errorCodes23 = [ - Diagnostics.Module_0_declares_1_locally_but_it_is_not_exported.code - ]; + errorCodes23 = [Diagnostics.Module_0_declares_1_locally_but_it_is_not_exported.code]; registerCodeFix({ errorCodes: errorCodes23, fixIds: [fixId20], getCodeActions(context) { - const { sourceFile, span, program } = context; + const { + sourceFile, + span, + program + } = context; const info = getInfo7(sourceFile, span.start, program); - if (info === void 0) - return void 0; - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange16(t, program, info)); + if (info === void 0) return void 0; + const changes = ts_textChanges_exports.ChangeTracker.with(context, t => doChange16(t, program, info)); return [createCodeFixAction(fixId20, changes, [Diagnostics.Export_0_from_module_1, info.exportName.node.text, info.moduleSpecifier], fixId20, Diagnostics.Export_all_referenced_locals)]; }, getAllCodeActions(context) { - const { program } = context; - return createCombinedCodeActions(ts_textChanges_exports.ChangeTracker.with(context, (changes) => { - const exports = /* @__PURE__ */ new Map(); - eachDiagnostic(context, errorCodes23, (diag2) => { + const { + program + } = context; + return createCombinedCodeActions(ts_textChanges_exports.ChangeTracker.with(context, changes => { + const exports = /* @__PURE__ */new Map(); + eachDiagnostic(context, errorCodes23, diag2 => { const info = getInfo7(diag2.file, diag2.start, program); - if (info === void 0) - return void 0; - const { exportName, node, moduleSourceFile } = info; + 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); } else { - const moduleExports = exports.get(moduleSourceFile) || { typeOnlyExports: [], exports: [] }; + const moduleExports = exports.get(moduleSourceFile) || { + typeOnlyExports: [], + exports: [] + }; if (exportName.isTypeOnly) { moduleExports.typeOnlyExports.push(exportName); } else { @@ -150659,18 +135404,12 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } }); exports.forEach((moduleExports, moduleSourceFile) => { - const exportDeclaration = tryGetExportDeclaration( - moduleSourceFile, - /*isTypeOnly*/ - true - ); + const exportDeclaration = tryGetExportDeclaration(moduleSourceFile, /*isTypeOnly*/ + true); if (exportDeclaration && exportDeclaration.isTypeOnly) { doChanges(changes, program, moduleSourceFile, moduleExports.typeOnlyExports, exportDeclaration); - doChanges(changes, program, moduleSourceFile, moduleExports.exports, tryGetExportDeclaration( - moduleSourceFile, - /*isTypeOnly*/ - false - )); + doChanges(changes, program, moduleSourceFile, moduleExports.exports, tryGetExportDeclaration(moduleSourceFile, /*isTypeOnly*/ + false)); } else { doChanges(changes, program, moduleSourceFile, [...moduleExports.exports, ...moduleExports.typeOnlyExports], exportDeclaration); } @@ -150684,8 +135423,9 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} // src/services/codefixes/fixIncorrectNamedTupleSyntax.ts function getNamedTupleMember(sourceFile, pos) { const token = getTokenAtPosition(sourceFile, pos); - return findAncestor(token, (t) => t.kind === 202 /* NamedTupleMember */); + return findAncestor(token, t => t.kind === 202 /* NamedTupleMember */); } + function doChange17(changes, sourceFile, namedTupleMember) { if (!namedTupleMember) { return; @@ -150701,13 +135441,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } unwrappedType = unwrappedType.type; } - const updated = factory.updateNamedTupleMember( - namedTupleMember, - namedTupleMember.dotDotDotToken || (sawRest ? factory.createToken(26 /* DotDotDotToken */) : void 0), - namedTupleMember.name, - namedTupleMember.questionToken || (sawOptional ? factory.createToken(58 /* QuestionToken */) : void 0), - unwrappedType - ); + const updated = factory.updateNamedTupleMember(namedTupleMember, namedTupleMember.dotDotDotToken || (sawRest ? factory.createToken(26 /* DotDotDotToken */) : void 0), namedTupleMember.name, namedTupleMember.questionToken || (sawOptional ? factory.createToken(58 /* QuestionToken */) : void 0), unwrappedType); if (updated === namedTupleMember) { return; } @@ -150717,19 +135451,20 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} var init_fixIncorrectNamedTupleSyntax = __esm({ "src/services/codefixes/fixIncorrectNamedTupleSyntax.ts"() { "use strict"; + init_ts4(); init_ts_codefix(); fixId21 = "fixIncorrectNamedTupleSyntax"; - errorCodes24 = [ - Diagnostics.A_labeled_tuple_element_is_declared_as_optional_with_a_question_mark_after_the_name_and_before_the_colon_rather_than_after_the_type.code, - Diagnostics.A_labeled_tuple_element_is_declared_as_rest_with_a_before_the_name_rather_than_before_the_type.code - ]; + errorCodes24 = [Diagnostics.A_labeled_tuple_element_is_declared_as_optional_with_a_question_mark_after_the_name_and_before_the_colon_rather_than_after_the_type.code, Diagnostics.A_labeled_tuple_element_is_declared_as_rest_with_a_before_the_name_rather_than_before_the_type.code]; registerCodeFix({ errorCodes: errorCodes24, getCodeActions: function getCodeActionsToFixIncorrectNamedTupleSyntax(context) { - const { sourceFile, span } = context; + const { + sourceFile, + span + } = context; const namedTupleMember = getNamedTupleMember(sourceFile, span.start); - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange17(t, sourceFile, namedTupleMember)); + const changes = ts_textChanges_exports.ChangeTracker.with(context, t => doChange17(t, sourceFile, namedTupleMember)); return [createCodeFixAction(fixId21, changes, Diagnostics.Move_labeled_tuple_element_modifiers_to_labels, fixId21, Diagnostics.Move_labeled_tuple_element_modifiers_to_labels)]; }, fixIds: [fixId21] @@ -150741,8 +135476,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} 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) { @@ -150785,7 +135519,10 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} Debug.assert(name !== void 0, "name should be defined"); suggestedSymbol = checker.getSuggestedSymbolForNonexistentSymbol(node, name, convertSemanticMeaningToSymbolFlags(meaning)); } - return suggestedSymbol === void 0 ? void 0 : { node, suggestedSymbol }; + return suggestedSymbol === void 0 ? void 0 : { + node, + suggestedSymbol + }; } function doChange18(changes, sourceFile, node, suggestedSymbol, target) { const suggestion = symbolName(suggestedSymbol); @@ -150805,64 +135542,59 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (meaning & 4 /* Namespace */) { flags |= 1920 /* Namespace */; } + if (meaning & 2 /* Type */) { flags |= 788968 /* Type */; } + if (meaning & 1 /* Value */) { flags |= 111551 /* Value */; } + return flags; } function getResolvedSourceFileFromImportDeclaration(sourceFile, context, importDeclaration) { var _a; - if (!importDeclaration || !isStringLiteralLike(importDeclaration.moduleSpecifier)) - return void 0; + if (!importDeclaration || !isStringLiteralLike(importDeclaration.moduleSpecifier)) return void 0; const resolvedModule = (_a = context.program.getResolvedModule(sourceFile, importDeclaration.moduleSpecifier.text, getModeForUsageLocation(sourceFile, importDeclaration.moduleSpecifier))) == null ? void 0 : _a.resolvedModule; - if (!resolvedModule) - return void 0; + if (!resolvedModule) return void 0; return context.program.getSourceFile(resolvedModule.resolvedFileName); } var fixId22, errorCodes25; var init_fixSpelling = __esm({ "src/services/codefixes/fixSpelling.ts"() { "use strict"; + init_ts4(); init_ts_codefix(); fixId22 = "fixSpelling"; - errorCodes25 = [ - Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2.code, - Diagnostics.Property_0_may_not_exist_on_type_1_Did_you_mean_2.code, - Diagnostics.Cannot_find_name_0_Did_you_mean_1.code, - Diagnostics.Could_not_find_name_0_Did_you_mean_1.code, - Diagnostics.Cannot_find_namespace_0_Did_you_mean_1.code, - Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0.code, - Diagnostics.Cannot_find_name_0_Did_you_mean_the_static_member_1_0.code, - Diagnostics._0_has_no_exported_member_named_1_Did_you_mean_2.code, - Diagnostics.This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0_Did_you_mean_1.code, - Diagnostics.This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_it_is_not_declared_in_the_base_class_0_Did_you_mean_1.code, - // for JSX class components - Diagnostics.No_overload_matches_this_call.code, - // for JSX FC - Diagnostics.Type_0_is_not_assignable_to_type_1.code - ]; + errorCodes25 = [Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2.code, Diagnostics.Property_0_may_not_exist_on_type_1_Did_you_mean_2.code, Diagnostics.Cannot_find_name_0_Did_you_mean_1.code, Diagnostics.Could_not_find_name_0_Did_you_mean_1.code, Diagnostics.Cannot_find_namespace_0_Did_you_mean_1.code, Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0.code, Diagnostics.Cannot_find_name_0_Did_you_mean_the_static_member_1_0.code, Diagnostics._0_has_no_exported_member_named_1_Did_you_mean_2.code, Diagnostics.This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0_Did_you_mean_1.code, Diagnostics.This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_it_is_not_declared_in_the_base_class_0_Did_you_mean_1.code, + // for JSX class components + Diagnostics.No_overload_matches_this_call.code, + // for JSX FC + Diagnostics.Type_0_is_not_assignable_to_type_1.code]; registerCodeFix({ errorCodes: errorCodes25, getCodeActions(context) { - const { sourceFile, errorCode } = context; + const { + sourceFile, + errorCode + } = context; const info = getInfo8(sourceFile, context.span.start, context, errorCode); - if (!info) - return void 0; - const { node, suggestedSymbol } = info; + 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)); + const changes = ts_textChanges_exports.ChangeTracker.with(context, t => doChange18(t, sourceFile, node, suggestedSymbol, target)); return [createCodeFixAction("spelling", changes, [Diagnostics.Change_spelling_to_0, symbolName(suggestedSymbol)], fixId22, Diagnostics.Fix_all_detected_spelling_errors)]; }, fixIds: [fixId22], - getAllCodeActions: (context) => codeFixAll(context, errorCodes25, (changes, diag2) => { + 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); }) }); } @@ -150873,18 +135605,11 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} const member = checker.createSymbol(4 /* Property */, label.escapedText); member.links.type = checker.getTypeAtLocation(expression); const members = createSymbolTable([member]); - return checker.createAnonymousType( - /*symbol*/ - void 0, - members, - [], - [], - [] - ); + return checker.createAnonymousType( /*symbol*/ + void 0, members, [], [], []); } function getFixInfo(checker, declaration, expectType, isFunctionType) { - if (!declaration.body || !isBlock(declaration.body) || length(declaration.body.statements) !== 1) - return void 0; + 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 { @@ -150937,25 +135662,10 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (hasSyntacticModifier(declaration, 1024 /* Async */)) { exprType = checker.createPromiseType(exprType); } - const newSig = checker.createSignature( - declaration, - sig.typeParameters, - sig.thisParameter, - sig.parameters, - exprType, - /*typePredicate*/ - void 0, - sig.minArgumentCount, - sig.flags - ); - exprType = checker.createAnonymousType( - /*symbol*/ - void 0, - createSymbolTable(), - [newSig], - [], - [] - ); + const newSig = checker.createSignature(declaration, sig.typeParameters, sig.thisParameter, sig.parameters, exprType, /*typePredicate*/ + void 0, sig.minArgumentCount, sig.flags); + exprType = checker.createAnonymousType( /*symbol*/ + void 0, createSymbolTable(), [newSig], [], []); } else { exprType = checker.getAnyType(); } @@ -150964,49 +135674,27 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } 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; - return getFixInfo( - checker, - declaration, - checker.getTypeFromTypeNode(declaration.type), - /*isFunctionType*/ - false - ); + if (!declaration || !declaration.body || !declaration.type || !rangeContainsRange(declaration.type, node)) return void 0; + return getFixInfo(checker, declaration, checker.getTypeFromTypeNode(declaration.type), /*isFunctionType*/ + false); case Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1.code: - if (!declaration || !isCallExpression(declaration.parent) || !declaration.body) - return void 0; + 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; - return getFixInfo( - checker, - declaration, - type, - /*isFunctionType*/ - true - ); + if (!type) return void 0; + return getFixInfo(checker, declaration, type, /*isFunctionType*/ + true); case Diagnostics.Type_0_is_not_assignable_to_type_1.code: - if (!isDeclarationName(node) || !isVariableLike(node.parent) && !isJsxAttribute(node.parent)) - return void 0; + if (!isDeclarationName(node) || !isVariableLike(node.parent) && !isJsxAttribute(node.parent)) return void 0; const initializer = getVariableLikeInitializer(node.parent); - if (!initializer || !isFunctionLikeDeclaration(initializer) || !initializer.body) - return void 0; - return getFixInfo( - checker, - initializer, - checker.getTypeAtLocation(node.parent), - /*isFunctionType*/ - true - ); + if (!initializer || !isFunctionLikeDeclaration(initializer) || !initializer.body) return void 0; + return getFixInfo(checker, initializer, checker.getTypeAtLocation(node.parent), /*isFunctionType*/ + true); } return void 0; } @@ -151047,81 +135735,64 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} changes.replaceNode(sourceFile, declaration.body, factory.createParenthesizedExpression(expression)); } function getActionForfixAddReturnStatement(context, expression, statement) { - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => addReturnStatement(t, context.sourceFile, expression, statement)); + const changes = ts_textChanges_exports.ChangeTracker.with(context, t => addReturnStatement(t, context.sourceFile, expression, statement)); return createCodeFixAction(fixId23, changes, Diagnostics.Add_a_return_statement, fixIdAddReturnStatement, Diagnostics.Add_all_missing_return_statement); } function getActionForFixRemoveBracesFromArrowFunctionBody(context, declaration, expression, commentSource) { - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => removeBlockBodyBrace( - t, - context.sourceFile, - declaration, - expression, - commentSource, - /*withParen*/ - false - )); + const changes = ts_textChanges_exports.ChangeTracker.with(context, t => removeBlockBodyBrace(t, context.sourceFile, declaration, expression, commentSource, /*withParen*/ + false)); return createCodeFixAction(fixId23, changes, Diagnostics.Remove_braces_from_arrow_function_body, fixRemoveBracesFromArrowFunctionBody, Diagnostics.Remove_braces_from_all_arrow_function_bodies_with_relevant_issues); } function getActionForfixWrapTheBlockWithParen(context, declaration, expression) { - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => wrapBlockWithParen(t, context.sourceFile, declaration, expression)); + const changes = ts_textChanges_exports.ChangeTracker.with(context, t => wrapBlockWithParen(t, context.sourceFile, declaration, expression)); return createCodeFixAction(fixId23, changes, Diagnostics.Wrap_the_following_body_with_parentheses_which_should_be_an_object_literal, fixIdWrapTheBlockWithParen, Diagnostics.Wrap_all_object_literal_with_parentheses); } var fixId23, fixIdAddReturnStatement, fixRemoveBracesFromArrowFunctionBody, fixIdWrapTheBlockWithParen, errorCodes26; var init_returnValueCorrect = __esm({ "src/services/codefixes/returnValueCorrect.ts"() { "use strict"; + init_ts4(); init_ts_codefix(); fixId23 = "returnValueCorrect"; fixIdAddReturnStatement = "fixAddReturnStatement"; fixRemoveBracesFromArrowFunctionBody = "fixRemoveBracesFromArrowFunctionBody"; fixIdWrapTheBlockWithParen = "fixWrapTheBlockWithParen"; - errorCodes26 = [ - Diagnostics.A_function_whose_declared_type_is_neither_undefined_void_nor_any_must_return_a_value.code, - Diagnostics.Type_0_is_not_assignable_to_type_1.code, - Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1.code - ]; + errorCodes26 = [Diagnostics.A_function_whose_declared_type_is_neither_undefined_void_nor_any_must_return_a_value.code, Diagnostics.Type_0_is_not_assignable_to_type_1.code, Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1.code]; registerCodeFix({ errorCodes: errorCodes26, fixIds: [fixIdAddReturnStatement, fixRemoveBracesFromArrowFunctionBody, fixIdWrapTheBlockWithParen], getCodeActions: function getCodeActionsToCorrectReturnValue(context) { - const { program, sourceFile, span: { start }, errorCode } = 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)], - isArrowFunction(info.declaration) ? getActionForFixRemoveBracesFromArrowFunctionBody(context, info.declaration, info.expression, info.commentSource) : void 0 - ); + return append([getActionForfixAddReturnStatement(context, info.expression, info.statement)], isArrowFunction(info.declaration) ? getActionForFixRemoveBracesFromArrowFunctionBody(context, info.declaration, info.expression, info.commentSource) : void 0); } else { return [getActionForfixWrapTheBlockWithParen(context, info.declaration, info.expression)]; } }, - getAllCodeActions: (context) => codeFixAll(context, errorCodes26, (changes, diag2) => { + 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; - removeBlockBodyBrace( - changes, - diag2.file, - info.declaration, - info.expression, - info.commentSource, - /*withParen*/ - false - ); + if (!isArrowFunction(info.declaration)) return void 0; + removeBlockBodyBrace(changes, diag2.file, info.declaration, info.expression, info.commentSource, /*withParen*/ + false); break; case fixIdWrapTheBlockWithParen: - if (!isArrowFunction(info.declaration)) - return void 0; + if (!isArrowFunction(info.declaration)) return void 0; wrapBlockWithParen(changes, diag2.file, info.declaration, info.expression); break; default: @@ -151138,111 +135809,146 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} const token = getTokenAtPosition(sourceFile, tokenPos); const parent2 = token.parent; if (errorCode === Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1.code) { - if (!(token.kind === 19 /* OpenBraceToken */ && isObjectLiteralExpression(parent2) && isCallExpression(parent2.parent))) - return void 0; - const argIndex = findIndex(parent2.parent.arguments, (arg) => arg === parent2); - if (argIndex < 0) - return void 0; + if (!(token.kind === 19 /* OpenBraceToken */ && isObjectLiteralExpression(parent2) && isCallExpression(parent2.parent))) return void 0; + const argIndex = findIndex(parent2.parent.arguments, arg => arg === parent2); + if (argIndex < 0) return void 0; const signature = checker.getResolvedSignature(parent2.parent); - if (!(signature && signature.declaration && signature.parameters[argIndex])) - return void 0; + if (!(signature && signature.declaration && signature.parameters[argIndex])) return void 0; const param = signature.parameters[argIndex].valueDeclaration; - if (!(param && isParameter(param) && isIdentifier(param.name))) - return void 0; - const properties = arrayFrom(checker.getUnmatchedProperties( - checker.getTypeAtLocation(parent2), - checker.getParameterType(signature, argIndex), - /*requireOptionalProperties*/ - false, - /*matchDiscriminantProperties*/ - false - )); - if (!length(properties)) - return void 0; - return { kind: 3 /* ObjectLiteral */, token: param.name, properties, parentDeclaration: parent2 }; + if (!(param && isParameter(param) && isIdentifier(param.name))) return void 0; + const properties = arrayFrom(checker.getUnmatchedProperties(checker.getTypeAtLocation(parent2), checker.getParameterType(signature, argIndex), /*requireOptionalProperties*/ + false, /*matchDiscriminantProperties*/ + false)); + if (!length(properties)) return void 0; + return { + kind: 3 /* ObjectLiteral */, + token: param.name, + properties, + 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( - checker.getTypeAtLocation(parent2.initializer), - targetType, - /*requireOptionalProperties*/ - false, - /*matchDiscriminantProperties*/ - false - )); - if (!length(properties)) - return void 0; - return { kind: 3 /* ObjectLiteral */, token, properties, parentDeclaration: parent2.initializer }; + const properties = arrayFrom(checker.getUnmatchedProperties(checker.getTypeAtLocation(parent2.initializer), targetType, /*requireOptionalProperties*/ + false, /*matchDiscriminantProperties*/ + false)); + if (!length(properties)) return void 0; + return { + kind: 3 /* ObjectLiteral */, + token, + properties, + parentDeclaration: parent2.initializer + }; } if (isIdentifier(token) && isJsxOpeningLikeElement(token.parent)) { const target = getEmitScriptTarget(program.getCompilerOptions()); const attributes = getUnmatchedAttributes(checker, target, token.parent); - if (!length(attributes)) - return void 0; - return { kind: 4 /* JsxAttributes */, token, attributes, parentDeclaration: token.parent }; + 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; - return { kind: 5 /* Signature */, token, signature, sourceFile, parentDeclaration: findScope(token) }; + 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) }; + 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(); if (moduleDeclaration && moduleDeclarationSourceFile && !isSourceFileFromLibrary(program, moduleDeclarationSourceFile)) { - return { kind: 2 /* Function */, token, call: parent2.parent, sourceFile, modifierFlags: 32 /* Export */, parentDeclaration: moduleDeclaration }; + 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 }; + 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; - const declaration = classDeclaration || find(symbol.declarations, (d) => isInterfaceDeclaration(d) || isTypeLiteralNode(d)); + 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); const call = tryCast(parent2.parent, isCallExpression); - return { kind: 0 /* TypeLikeDeclaration */, token, call, modifierFlags, parentDeclaration: declaration, declSourceFile, isJSFile }; + return { + kind: 0 /* TypeLikeDeclaration */, + token, + call, + modifierFlags, + parentDeclaration: declaration, + declSourceFile, + isJSFile + }; } const enumDeclaration = find(symbol.declarations, isEnumDeclaration); if (enumDeclaration && !(leftExpressionType.flags & 1056 /* EnumLike */) && !isPrivateIdentifier(token) && !isSourceFileFromLibrary(program, enumDeclaration.getSourceFile())) { - return { kind: 1 /* Enum */, token, parentDeclaration: enumDeclaration }; + return { + kind: 1 /* Enum */, + token, + parentDeclaration: enumDeclaration + }; } return void 0; } function getActionsForMissingMemberDeclaration(context, info) { return info.isJSFile ? singleElementArray(createActionForAddMissingMemberInJavascriptFile(context, info)) : createActionsForAddMissingMemberInTypeScriptFile(context, info); } - function createActionForAddMissingMemberInJavascriptFile(context, { parentDeclaration, declSourceFile, modifierFlags, token }) { + function createActionForAddMissingMemberInJavascriptFile(context, { + parentDeclaration, + declSourceFile, + modifierFlags, + token + }) { if (isInterfaceDeclaration(parentDeclaration) || isTypeLiteralNode(parentDeclaration)) { return void 0; } - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => addMissingMemberInJs(t, declSourceFile, parentDeclaration, token, !!(modifierFlags & 256 /* Static */))); + const changes = ts_textChanges_exports.ChangeTracker.with(context, t => addMissingMemberInJs(t, declSourceFile, parentDeclaration, token, !!(modifierFlags & 256 /* Static */))); if (changes.length === 0) { return void 0; } @@ -151259,17 +135965,11 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} const staticInitialization = initializePropertyToUndefined(factory.createIdentifier(className), tokenName); changeTracker.insertNodeAfter(sourceFile, classDeclaration, staticInitialization); } else if (isPrivateIdentifier(token)) { - const property = factory.createPropertyDeclaration( - /*modifiers*/ - void 0, - tokenName, - /*questionOrExclamationToken*/ - void 0, - /*type*/ - void 0, - /*initializer*/ - void 0 - ); + const property = factory.createPropertyDeclaration( /*modifiers*/ + void 0, tokenName, /*questionOrExclamationToken*/ + void 0, /*type*/ + void 0, /*initializer*/ + void 0); const lastProp = getNodeToInsertPropertyAfter(classDeclaration); if (lastProp) { changeTracker.insertNodeAfter(sourceFile, lastProp, property); @@ -151288,11 +135988,16 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} function initializePropertyToUndefined(obj, propertyName) { return factory.createExpressionStatement(factory.createAssignment(factory.createPropertyAccessExpression(obj, propertyName), createUndefined())); } - function createActionsForAddMissingMemberInTypeScriptFile(context, { parentDeclaration, declSourceFile, modifierFlags, token }) { + function createActionsForAddMissingMemberInTypeScriptFile(context, { + parentDeclaration, + declSourceFile, + modifierFlags, + token + }) { const memberName = token.text; const isStatic2 = modifierFlags & 256 /* Static */; const typeNode = getTypeNode2(context.program.getTypeChecker(), parentDeclaration, token); - const addPropertyDeclarationChanges = (modifierFlags2) => ts_textChanges_exports.ChangeTracker.with(context, (t) => addPropertyDeclaration(t, declSourceFile, parentDeclaration, memberName, typeNode, modifierFlags2)); + const addPropertyDeclarationChanges = modifierFlags2 => ts_textChanges_exports.ChangeTracker.with(context, t => addPropertyDeclaration(t, declSourceFile, parentDeclaration, memberName, typeNode, modifierFlags2)); const actions2 = [createCodeFixAction(fixMissingMember, addPropertyDeclarationChanges(modifierFlags & 256 /* Static */), [isStatic2 ? Diagnostics.Declare_static_property_0 : Diagnostics.Declare_property_0, memberName], fixMissingMember, Diagnostics.Add_all_missing_members)]; if (isStatic2 || isPrivateIdentifier(token)) { return actions2; @@ -151312,33 +136017,19 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} typeNode = checker.typeToTypeNode(widenedType, node, 1 /* NoTruncation */); } else { const contextualType = checker.getContextualType(token.parent); - typeNode = contextualType ? checker.typeToTypeNode( - contextualType, - /*enclosingDeclaration*/ - void 0, - 1 /* NoTruncation */ - ) : void 0; + typeNode = contextualType ? checker.typeToTypeNode(contextualType, /*enclosingDeclaration*/ + void 0, 1 /* NoTruncation */) : void 0; } return typeNode || factory.createKeywordTypeNode(133 /* AnyKeyword */); } + function addPropertyDeclaration(changeTracker, sourceFile, node, tokenName, typeNode, modifierFlags) { const modifiers = modifierFlags ? factory.createNodeArray(factory.createModifiersFromModifierFlags(modifierFlags)) : void 0; - const property = isClassLike(node) ? factory.createPropertyDeclaration( - modifiers, - tokenName, - /*questionOrExclamationToken*/ - void 0, - typeNode, - /*initializer*/ - void 0 - ) : factory.createPropertySignature( - /*modifiers*/ - void 0, - tokenName, - /*questionToken*/ - void 0, - typeNode - ); + const property = isClassLike(node) ? factory.createPropertyDeclaration(modifiers, tokenName, /*questionOrExclamationToken*/ + void 0, typeNode, /*initializer*/ + void 0) : factory.createPropertySignature( /*modifiers*/ + void 0, tokenName, /*questionToken*/ + void 0, typeNode); const lastProp = getNodeToInsertPropertyAfter(node); if (lastProp) { changeTracker.insertNodeAfter(sourceFile, lastProp, property); @@ -151349,42 +136040,36 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} function getNodeToInsertPropertyAfter(node) { let res; for (const member of node.members) { - if (!isPropertyDeclaration(member)) - break; + if (!isPropertyDeclaration(member)) break; res = member; } return res; } function createAddIndexSignatureAction(context, sourceFile, node, tokenName, typeNode) { const stringTypeNode = factory.createKeywordTypeNode(154 /* StringKeyword */); - const indexingParameter = factory.createParameterDeclaration( - /*modifiers*/ - void 0, - /*dotDotDotToken*/ - void 0, - "x", - /*questionToken*/ - void 0, - stringTypeNode, - /*initializer*/ - void 0 - ); - const indexSignature = factory.createIndexSignature( - /*modifiers*/ - void 0, - [indexingParameter], - typeNode - ); - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => t.insertMemberAtStart(sourceFile, node, indexSignature)); + const indexingParameter = factory.createParameterDeclaration( /*modifiers*/ + void 0, /*dotDotDotToken*/ + void 0, "x", /*questionToken*/ + void 0, stringTypeNode, /*initializer*/ + void 0); + const indexSignature = factory.createIndexSignature( /*modifiers*/ + void 0, [indexingParameter], typeNode); + const changes = ts_textChanges_exports.ChangeTracker.with(context, t => t.insertMemberAtStart(sourceFile, node, indexSignature)); return createCodeFixActionWithoutFixAll(fixMissingMember, changes, [Diagnostics.Add_index_signature_for_property_0, tokenName]); } function getActionsForMissingMethodDeclaration(context, info) { - const { parentDeclaration, declSourceFile, modifierFlags, token, call } = info; + const { + parentDeclaration, + declSourceFile, + modifierFlags, + token, + call + } = info; if (call === void 0) { return void 0; } const methodName = token.text; - const addMethodDeclarationChanges = (modifierFlags2) => ts_textChanges_exports.ChangeTracker.with(context, (t) => addMethodDeclaration(context, t, call, token, modifierFlags2, parentDeclaration, declSourceFile)); + const addMethodDeclarationChanges = modifierFlags2 => ts_textChanges_exports.ChangeTracker.with(context, t => addMethodDeclaration(context, t, call, token, modifierFlags2, parentDeclaration, declSourceFile)); const actions2 = [createCodeFixAction(fixMissingMember, addMethodDeclarationChanges(modifierFlags & 256 /* Static */), [modifierFlags & 256 /* Static */ ? Diagnostics.Declare_static_method_0 : Diagnostics.Declare_method_0, methodName], fixMissingMember, Diagnostics.Add_all_missing_members)]; if (modifierFlags & 2 /* Private */) { actions2.unshift(createCodeFixActionWithoutFixAll(fixMissingMember, addMethodDeclarationChanges(2 /* Private */), [Diagnostics.Declare_private_method_0, methodName])); @@ -151403,55 +136088,33 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } importAdder.writeFixes(changes); } - function addEnumMemberDeclaration(changes, checker, { token, parentDeclaration }) { - const hasStringInitializer = some(parentDeclaration.members, (member) => { + function addEnumMemberDeclaration(changes, checker, { + token, + parentDeclaration + }) { + const hasStringInitializer = some(parentDeclaration.members, member => { const type = checker.getTypeAtLocation(member); return !!(type && type.flags & 402653316 /* StringLike */); }); + const enumMember = factory.createEnumMember(token, hasStringInitializer ? factory.createStringLiteral(token.text) : void 0); - changes.replaceNode( - parentDeclaration.getSourceFile(), - parentDeclaration, - factory.updateEnumDeclaration( - parentDeclaration, - parentDeclaration.modifiers, - parentDeclaration.name, - concatenate(parentDeclaration.members, singleElementArray(enumMember)) - ), - { - leadingTriviaOption: ts_textChanges_exports.LeadingTriviaOption.IncludeAll, - trailingTriviaOption: ts_textChanges_exports.TrailingTriviaOption.Exclude - } - ); + changes.replaceNode(parentDeclaration.getSourceFile(), parentDeclaration, factory.updateEnumDeclaration(parentDeclaration, parentDeclaration.modifiers, parentDeclaration.name, concatenate(parentDeclaration.members, singleElementArray(enumMember))), { + leadingTriviaOption: ts_textChanges_exports.LeadingTriviaOption.IncludeAll, + trailingTriviaOption: ts_textChanges_exports.TrailingTriviaOption.Exclude + }); } function addFunctionDeclaration(changes, context, info) { const quotePreference = getQuotePreference(context.sourceFile, context.preferences); const importAdder = createImportAdder(context.sourceFile, context.program, context.preferences, context.host); - const functionDeclaration = info.kind === 2 /* Function */ ? createSignatureDeclarationFromCallExpression(262 /* FunctionDeclaration */, context, importAdder, info.call, idText(info.token), info.modifierFlags, info.parentDeclaration) : createSignatureDeclarationFromSignature( - 262 /* FunctionDeclaration */, - context, - quotePreference, - info.signature, - createStubbedBody(Diagnostics.Function_not_implemented.message, quotePreference), - info.token, - /*modifiers*/ - void 0, - /*optional*/ - void 0, - /*enclosingDeclaration*/ - void 0, - importAdder - ); + const functionDeclaration = info.kind === 2 /* Function */ ? createSignatureDeclarationFromCallExpression(262 /* FunctionDeclaration */, context, importAdder, info.call, idText(info.token), info.modifierFlags, info.parentDeclaration) : createSignatureDeclarationFromSignature(262 /* FunctionDeclaration */, context, quotePreference, info.signature, createStubbedBody(Diagnostics.Function_not_implemented.message, quotePreference), info.token, /*modifiers*/ + void 0, /*optional*/ + void 0, /*enclosingDeclaration*/ + void 0, importAdder); if (functionDeclaration === void 0) { Debug.fail("fixMissingFunctionDeclaration codefix got unexpected error."); } - isReturnStatement(info.parentDeclaration) ? changes.insertNodeBefore( - info.sourceFile, - info.parentDeclaration, - functionDeclaration, - /*blankLineBetween*/ - true - ) : changes.insertNodeAtEndOfScope(info.sourceFile, info.parentDeclaration, functionDeclaration); + isReturnStatement(info.parentDeclaration) ? changes.insertNodeBefore(info.sourceFile, info.parentDeclaration, functionDeclaration, /*blankLineBetween*/ + true) : changes.insertNodeAtEndOfScope(info.sourceFile, info.parentDeclaration, functionDeclaration); importAdder.writeFixes(changes); } function addJsxAttributes(changes, context, info) { @@ -151460,19 +136123,18 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} const checker = context.program.getTypeChecker(); const jsxAttributesNode = info.parentDeclaration.attributes; const hasSpreadAttribute = some(jsxAttributesNode.properties, isJsxSpreadAttribute); - const attrs = map(info.attributes, (attr) => { + const attrs = map(info.attributes, attr => { const value = tryGetValueFromType(context, checker, importAdder, quotePreference, checker.getTypeOfSymbol(attr), info.parentDeclaration); const name = factory.createIdentifier(attr.name); - const jsxAttribute = factory.createJsxAttribute(name, factory.createJsxExpression( - /*dotDotDotToken*/ - void 0, - value - )); + const jsxAttribute = factory.createJsxAttribute(name, factory.createJsxExpression( /*dotDotDotToken*/ + void 0, value)); setParent(name, jsxAttribute); return jsxAttribute; }); const jsxAttributes = factory.createJsxAttributes(hasSpreadAttribute ? [...attrs, ...jsxAttributesNode.properties] : [...jsxAttributesNode.properties, ...attrs]); - const options = { prefix: jsxAttributesNode.pos === jsxAttributesNode.end ? " " : void 0 }; + const options = { + prefix: jsxAttributesNode.pos === jsxAttributesNode.end ? " " : void 0 + }; changes.replaceNode(context.sourceFile, jsxAttributesNode, jsxAttributes, options); importAdder.writeFixes(changes); } @@ -151481,7 +136143,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} const quotePreference = getQuotePreference(context.sourceFile, context.preferences); const target = getEmitScriptTarget(context.program.getCompilerOptions()); const checker = context.program.getTypeChecker(); - const props = map(info.properties, (prop) => { + const props = map(info.properties, prop => { const initializer = tryGetValueFromType(context, checker, importAdder, quotePreference, checker.getTypeOfSymbol(prop), info.parentDeclaration); return factory.createPropertyAssignment(createPropertyNameFromSymbol(prop, target, quotePreference, checker), initializer); }); @@ -151490,11 +136152,8 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} trailingTriviaOption: ts_textChanges_exports.TrailingTriviaOption.Exclude, indentation: info.indentation }; - changes.replaceNode(context.sourceFile, info.parentDeclaration, factory.createObjectLiteralExpression( - [...info.parentDeclaration.properties, ...props], - /*multiLine*/ - true - ), options); + changes.replaceNode(context.sourceFile, info.parentDeclaration, factory.createObjectLiteralExpression([...info.parentDeclaration.properties, ...props], /*multiLine*/ + true), options); importAdder.writeFixes(changes); } function tryGetValueFromType(context, checker, importAdder, quotePreference, type, enclosingDeclaration) { @@ -151502,12 +136161,10 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return createUndefined(); } if (type.flags & (4 /* String */ | 134217728 /* TemplateLiteral */)) { - return factory.createStringLiteral( - "", - /* isSingleQuote */ - quotePreference === 0 /* Single */ - ); + return factory.createStringLiteral("", /* isSingleQuote */ + quotePreference === 0 /* Single */); } + if (type.flags & 8 /* Number */) { return factory.createNumericLiteral(0); } @@ -151519,14 +136176,9 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } if (type.flags & 1056 /* EnumLike */) { const enumMember = type.symbol.exports ? firstOrUndefinedIterator(type.symbol.exports.values()) : type.symbol; - const name = checker.symbolToExpression( - type.symbol.parent ? type.symbol.parent : type.symbol, - 111551 /* Value */, - /*enclosingDeclaration*/ - void 0, - /*flags*/ - void 0 - ); + const name = checker.symbolToExpression(type.symbol.parent ? type.symbol.parent : type.symbol, 111551 /* Value */, /*enclosingDeclaration*/ + void 0, /*flags*/ + void 0); return enumMember === void 0 || name === void 0 ? factory.createNumericLiteral(0) : factory.createPropertyAccessExpression(name, checker.symbolToString(enumMember)); } if (type.flags & 256 /* NumberLiteral */) { @@ -151536,78 +136188,52 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return factory.createBigIntLiteral(type.value); } if (type.flags & 128 /* StringLiteral */) { - return factory.createStringLiteral( - type.value, - /* isSingleQuote */ - quotePreference === 0 /* Single */ - ); + return factory.createStringLiteral(type.value, /* isSingleQuote */ + quotePreference === 0 /* Single */); } + if (type.flags & 512 /* BooleanLiteral */) { - return type === checker.getFalseType() || type === checker.getFalseType( - /*fresh*/ - true - ) ? factory.createFalse() : factory.createTrue(); + return type === checker.getFalseType() || type === checker.getFalseType( /*fresh*/ + true) ? factory.createFalse() : factory.createTrue(); } if (type.flags & 65536 /* Null */) { return factory.createNull(); } if (type.flags & 1048576 /* Union */) { - const expression = firstDefined(type.types, (t) => tryGetValueFromType(context, checker, importAdder, quotePreference, t, enclosingDeclaration)); - return expression ?? createUndefined(); + const expression = firstDefined(type.types, t => tryGetValueFromType(context, checker, importAdder, quotePreference, t, enclosingDeclaration)); + return expression !== null && expression !== void 0 ? expression : createUndefined(); } if (checker.isArrayLikeType(type)) { return factory.createArrayLiteralExpression(); } if (isObjectLiteralType(type)) { - const props = map(checker.getPropertiesOfType(type), (prop) => { + const props = map(checker.getPropertiesOfType(type), prop => { const initializer = tryGetValueFromType(context, checker, importAdder, quotePreference, checker.getTypeOfSymbol(prop), enclosingDeclaration); return factory.createPropertyAssignment(prop.name, initializer); }); - return factory.createObjectLiteralExpression( - props, - /*multiLine*/ - true - ); + return factory.createObjectLiteralExpression(props, /*multiLine*/ + true); } 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(); - const func = createSignatureDeclarationFromSignature( - 218 /* FunctionExpression */, - context, - quotePreference, - signature[0], - createStubbedBody(Diagnostics.Function_not_implemented.message, quotePreference), - /*name*/ - void 0, - /*modifiers*/ - void 0, - /*optional*/ - void 0, - /*enclosingDeclaration*/ - enclosingDeclaration, - importAdder - ); - return func ?? createUndefined(); + if (signature === void 0) return createUndefined(); + const func = createSignatureDeclarationFromSignature(218 /* FunctionExpression */, context, quotePreference, signature[0], createStubbedBody(Diagnostics.Function_not_implemented.message, quotePreference), /*name*/ + void 0, /*modifiers*/ + void 0, /*optional*/ + void 0, /*enclosingDeclaration*/ + enclosingDeclaration, importAdder); + return func !== null && func !== void 0 ? func : createUndefined(); } 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(); - return factory.createNewExpression( - factory.createIdentifier(type.symbol.name), - /*typeArguments*/ - void 0, - /*argumentsArray*/ - void 0 - ); + if (constructorDeclaration && length(constructorDeclaration.parameters)) return createUndefined(); + return factory.createNewExpression(factory.createIdentifier(type.symbol.name), /*typeArguments*/ + void 0, /*argumentsArray*/ + void 0); } return createUndefined(); } @@ -151619,12 +136245,10 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } 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; - const seenNames = /* @__PURE__ */ new Set(); + if (!length(targetProps)) return emptyArray; + const seenNames = /* @__PURE__ */new Set(); for (const sourceProp of source.attributes.properties) { if (isJsxAttribute(sourceProp)) { seenNames.add(getEscapedTextOfJsxAttributeName(sourceProp.name)); @@ -151636,42 +136260,30 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } } } - return filter(targetProps, (targetProp) => isIdentifierText(targetProp.name, target, 1 /* JSX */) && !(targetProp.flags & 16777216 /* Optional */ || getCheckFlags(targetProp) & 48 /* Partial */ || seenNames.has(targetProp.escapedName))); + return filter(targetProps, targetProp => isIdentifierText(targetProp.name, target, 1 /* JSX */) && !(targetProp.flags & 16777216 /* Optional */ || getCheckFlags(targetProp) & 48 /* Partial */ || seenNames.has(targetProp.escapedName))); } function tryGetContainingMethodDeclaration(node, callExpression) { if (isTypeLiteralNode(node)) { return void 0; } - const declaration = findAncestor(callExpression, (n) => isMethodDeclaration(n) || isConstructorDeclaration(n)); + const declaration = findAncestor(callExpression, n => isMethodDeclaration(n) || isConstructorDeclaration(n)); return declaration && declaration.parent === node ? declaration : void 0; } function createPropertyNameFromSymbol(symbol, target, quotePreference, checker) { if (isTransientSymbol(symbol)) { - const prop = checker.symbolToNode( - symbol, - 111551 /* Value */, - /*enclosingDeclaration*/ - void 0, - 1073741824 /* WriteComputedProps */ - ); - if (prop && isComputedPropertyName(prop)) - return prop; + const prop = checker.symbolToNode(symbol, 111551 /* Value */, /*enclosingDeclaration*/ + void 0, 1073741824 /* WriteComputedProps */); + + if (prop && isComputedPropertyName(prop)) return prop; } - return createPropertyNameNodeForIdentifierOrLiteral( - symbol.name, - target, - quotePreference === 0 /* Single */, - /*stringNamed*/ - false, - /*isMethod*/ - false - ); + return createPropertyNameNodeForIdentifierOrLiteral(symbol.name, target, quotePreference === 0 /* Single */, /*stringNamed*/ + false, /*isMethod*/ + false); } function findScope(node) { if (findAncestor(node, isJsxExpression)) { const returnStatement = findAncestor(node.parent, isReturnStatement); - if (returnStatement) - return returnStatement; + if (returnStatement) return returnStatement; } return getSourceFileOfNode(node); } @@ -151679,21 +136291,14 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} var init_fixAddMissingMember = __esm({ "src/services/codefixes/fixAddMissingMember.ts"() { "use strict"; + init_ts4(); init_ts_codefix(); fixMissingMember = "fixMissingMember"; fixMissingProperties = "fixMissingProperties"; fixMissingAttributes = "fixMissingAttributes"; fixMissingFunctionDeclaration = "fixMissingFunctionDeclaration"; - errorCodes27 = [ - Diagnostics.Property_0_does_not_exist_on_type_1.code, - Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2.code, - Diagnostics.Property_0_is_missing_in_type_1_but_required_in_type_2.code, - Diagnostics.Type_0_is_missing_the_following_properties_from_type_1_Colon_2.code, - Diagnostics.Type_0_is_missing_the_following_properties_from_type_1_Colon_2_and_3_more.code, - Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1.code, - Diagnostics.Cannot_find_name_0.code - ]; + errorCodes27 = [Diagnostics.Property_0_does_not_exist_on_type_1.code, Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2.code, Diagnostics.Property_0_is_missing_in_type_1_but_required_in_type_2.code, Diagnostics.Type_0_is_missing_the_following_properties_from_type_1_Colon_2.code, Diagnostics.Type_0_is_missing_the_following_properties_from_type_1_Colon_2_and_3_more.code, Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1.code, Diagnostics.Cannot_find_name_0.code]; registerCodeFix({ errorCodes: errorCodes27, getCodeActions(context) { @@ -151703,31 +136308,34 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return void 0; } if (info.kind === 3 /* ObjectLiteral */) { - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => addObjectLiteralProperties(t, context, info)); + const changes = ts_textChanges_exports.ChangeTracker.with(context, t => addObjectLiteralProperties(t, context, info)); return [createCodeFixAction(fixMissingProperties, changes, Diagnostics.Add_missing_properties, fixMissingProperties, Diagnostics.Add_all_missing_properties)]; } if (info.kind === 4 /* JsxAttributes */) { - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => addJsxAttributes(t, context, info)); + const changes = ts_textChanges_exports.ChangeTracker.with(context, t => addJsxAttributes(t, context, info)); return [createCodeFixAction(fixMissingAttributes, changes, Diagnostics.Add_missing_attributes, fixMissingAttributes, Diagnostics.Add_all_missing_attributes)]; } if (info.kind === 2 /* Function */ || info.kind === 5 /* Signature */) { - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => addFunctionDeclaration(t, context, info)); + const changes = ts_textChanges_exports.ChangeTracker.with(context, t => addFunctionDeclaration(t, context, info)); return [createCodeFixAction(fixMissingFunctionDeclaration, changes, [Diagnostics.Add_missing_function_declaration_0, info.token.text], fixMissingFunctionDeclaration, Diagnostics.Add_all_missing_function_declarations)]; } if (info.kind === 1 /* Enum */) { - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => addEnumMemberDeclaration(t, context.program.getTypeChecker(), info)); + const changes = ts_textChanges_exports.ChangeTracker.with(context, t => addEnumMemberDeclaration(t, context.program.getTypeChecker(), info)); return [createCodeFixAction(fixMissingMember, changes, [Diagnostics.Add_missing_enum_member_0, info.token.text], fixMissingMember, Diagnostics.Add_all_missing_members)]; } return concatenate(getActionsForMissingMethodDeclaration(context, info), getActionsForMissingMemberDeclaration(context, info)); }, fixIds: [fixMissingMember, fixMissingFunctionDeclaration, fixMissingProperties, fixMissingAttributes], - getAllCodeActions: (context) => { - const { program, fixId: fixId52 } = context; + getAllCodeActions: context => { + const { + program, + fixId: fixId52 + } = context; const checker = program.getTypeChecker(); - const seen = /* @__PURE__ */ new Map(); - const typeDeclToMembers = /* @__PURE__ */ new Map(); - return createCombinedCodeActions(ts_textChanges_exports.ChangeTracker.with(context, (changes) => { - eachDiagnostic(context, errorCodes27, (diag2) => { + const seen = /* @__PURE__ */new Map(); + const typeDeclToMembers = /* @__PURE__ */new Map(); + return createCombinedCodeActions(ts_textChanges_exports.ChangeTracker.with(context, changes => { + eachDiagnostic(context, errorCodes27, diag2 => { const info = getInfo10(diag2.file, diag2.start, diag2.code, checker, context.program); if (!info || !addToSeen(seen, getNodeId(info.parentDeclaration) + "#" + info.token.text)) { return; @@ -151743,9 +136351,12 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} addEnumMemberDeclaration(changes, checker, info); } if (info.kind === 0 /* TypeLikeDeclaration */) { - const { parentDeclaration, token } = info; + const { + parentDeclaration, + token + } = info; const infos = getOrUpdate(typeDeclToMembers, parentDeclaration, () => []); - if (!infos.some((i) => i.token.text === token.text)) { + if (!infos.some(i => i.token.text === token.text)) { infos.push(info); } } @@ -151754,12 +136365,20 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} typeDeclToMembers.forEach((infos, declaration) => { const supers = isTypeLiteralNode(declaration) ? void 0 : getAllSupers(declaration, checker); for (const info of infos) { - if (supers == null ? void 0 : supers.some((superClassOrInterface) => { + if (supers == null ? void 0 : supers.some(superClassOrInterface => { const superInfos = typeDeclToMembers.get(superClassOrInterface); - return !!superInfos && superInfos.some(({ token: token2 }) => token2.text === info.token.text); - })) - continue; - const { parentDeclaration, declSourceFile, modifierFlags, token, call, isJSFile } = info; + return !!superInfos && superInfos.some(({ + token: token2 + }) => token2.text === info.token.text); + })) continue; + const { + parentDeclaration, + declSourceFile, + modifierFlags, + token, + call, + isJSFile + } = info; if (call && !isPrivateIdentifier(token)) { addMethodDeclaration(context, changes, call, token, modifierFlags & 256 /* Static */, parentDeclaration, declSourceFile); } else { @@ -151796,6 +136415,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} var init_fixAddMissingNewOperator = __esm({ "src/services/codefixes/fixAddMissingNewOperator.ts"() { "use strict"; + init_ts4(); init_ts_codefix(); fixId24 = "addMissingNewOperator"; @@ -151803,26 +136423,34 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} registerCodeFix({ errorCodes: errorCodes28, getCodeActions(context) { - const { sourceFile, span } = context; - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => addMissingNewOperator(t, sourceFile, span)); + const { + sourceFile, + span + } = context; + const changes = ts_textChanges_exports.ChangeTracker.with(context, t => addMissingNewOperator(t, sourceFile, span)); return [createCodeFixAction(fixId24, changes, Diagnostics.Add_missing_new_operator_to_call, fixId24, Diagnostics.Add_missing_new_operator_to_all_calls)]; }, fixIds: [fixId24], - getAllCodeActions: (context) => codeFixAll(context, errorCodes28, (changes, diag2) => addMissingNewOperator(changes, context.sourceFile, diag2)) + getAllCodeActions: context => codeFixAll(context, errorCodes28, (changes, diag2) => addMissingNewOperator(changes, context.sourceFile, diag2)) }); } }); // src/services/codefixes/fixCannotFindModule.ts function getInstallCommand(fileName, packageName) { - return { type: "install package", file: fileName, packageName }; + return { + type: "install package", + file: 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); + const { + packageName + } = parsePackageName(moduleName); return isExternalModuleNameRelative(packageName) ? void 0 : packageName; } function getTypesPackageNameToInstall(packageName, host, diagCode) { @@ -151833,47 +136461,43 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} var init_fixCannotFindModule = __esm({ "src/services/codefixes/fixCannotFindModule.ts"() { "use strict"; + init_ts4(); init_ts_codefix(); fixName2 = "fixCannotFindModule"; fixIdInstallTypesPackage = "installTypesPackage"; errorCodeCannotFindModule = Diagnostics.Cannot_find_module_0_or_its_corresponding_type_declarations.code; - errorCodes29 = [ - errorCodeCannotFindModule, - Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type.code - ]; + errorCodes29 = [errorCodeCannotFindModule, Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type.code]; registerCodeFix({ errorCodes: errorCodes29, getCodeActions: function getCodeActionsToFixNotFoundModule(context) { - const { host, sourceFile, span: { start } } = 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, - /*changes*/ - [], - [Diagnostics.Install_0, typesPackageName], - fixIdInstallTypesPackage, - Diagnostics.Install_all_missing_types_packages, - getInstallCommand(sourceFile.fileName, typesPackageName) - )]; + return typesPackageName === void 0 ? [] : [createCodeFixAction(fixName2, /*changes*/ + [], [Diagnostics.Install_0, typesPackageName], fixIdInstallTypesPackage, Diagnostics.Install_all_missing_types_packages, getInstallCommand(sourceFile.fileName, typesPackageName))]; }, fixIds: [fixIdInstallTypesPackage], - getAllCodeActions: (context) => { + getAllCodeActions: context => { return codeFixAll(context, errorCodes29, (_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); - if (pkg) { - commands.push(getInstallCommand(diag2.file.fileName, pkg)); + case fixIdInstallTypesPackage: + { + const pkg = getTypesPackageNameToInstall(packageName, context.host, diag2.code); + if (pkg) { + commands.push(getInstallCommand(diag2.file.fileName, pkg)); + } + break; } - break; - } default: Debug.fail(`Bad fixId: ${context.fixId}`); } @@ -151894,33 +136518,36 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} const instantiatedExtendsType = checker.getTypeAtLocation(extendsNode); const abstractAndNonPrivateExtendsSymbols = checker.getPropertiesOfType(instantiatedExtendsType).filter(symbolPointsToNonPrivateAndAbstractMember); const importAdder = createImportAdder(sourceFile, context.program, preferences, context.host); - createMissingMemberNodes(classDeclaration, abstractAndNonPrivateExtendsSymbols, sourceFile, context, preferences, importAdder, (member) => changeTracker.insertMemberAtStart(sourceFile, classDeclaration, member)); + createMissingMemberNodes(classDeclaration, abstractAndNonPrivateExtendsSymbols, sourceFile, context, preferences, importAdder, member => changeTracker.insertMemberAtStart(sourceFile, classDeclaration, member)); importAdder.writeFixes(changeTracker); } function symbolPointsToNonPrivateAndAbstractMember(symbol) { const flags = getSyntacticModifierFlags(first(symbol.getDeclarations())); return !(flags & 2 /* Private */) && !!(flags & 64 /* Abstract */); } + var errorCodes30, fixId25; var init_fixClassDoesntImplementInheritedAbstractMember = __esm({ "src/services/codefixes/fixClassDoesntImplementInheritedAbstractMember.ts"() { "use strict"; + init_ts4(); init_ts_codefix(); - errorCodes30 = [ - Diagnostics.Non_abstract_class_0_does_not_implement_all_abstract_members_of_1.code - ]; + errorCodes30 = [Diagnostics.Non_abstract_class_0_does_not_implement_all_abstract_members_of_1.code]; fixId25 = "fixClassDoesntImplementInheritedAbstractMember"; registerCodeFix({ errorCodes: errorCodes30, getCodeActions: function getCodeActionsToFixClassNotImplementingInheritedMembers(context) { - const { sourceFile, span } = context; - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => addMissingMembers(getClass2(sourceFile, span.start), sourceFile, context, t, context.preferences)); + const { + sourceFile, + span + } = context; + const changes = ts_textChanges_exports.ChangeTracker.with(context, t => addMissingMembers(getClass2(sourceFile, span.start), sourceFile, context, t, context.preferences)); return changes.length === 0 ? void 0 : [createCodeFixAction(fixId25, changes, Diagnostics.Implement_inherited_abstract_class, fixId25, Diagnostics.Implement_all_inherited_abstract_classes)]; }, fixIds: [fixId25], getAllCodeActions: function getAllCodeActionsToFixClassDoesntImplementInheritedAbstractMember(context) { - const seenClassDeclarations = /* @__PURE__ */ new Map(); + const seenClassDeclarations = /* @__PURE__ */new Map(); return codeFixAll(context, errorCodes30, (changes, diag2) => { const classDeclaration = getClass2(diag2.file, diag2.start); if (addToSeen(seenClassDeclarations, getNodeId(classDeclaration))) { @@ -151939,11 +136566,13 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } 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; + return superCall && !superCall.expression.arguments.some(arg => isPropertyAccessExpression(arg) && arg.expression === token) ? { + constructor, + superCall + } : void 0; } function findSuperCall(n) { return isExpressionStatement(n) && isSuperCall(n.expression) ? n : isFunctionLike(n) ? void 0 : forEachChild(n, findSuperCall); @@ -151952,6 +136581,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} var init_fixClassSuperMustPrecedeThisAccess = __esm({ "src/services/codefixes/fixClassSuperMustPrecedeThisAccess.ts"() { "use strict"; + init_ts4(); init_ts_codefix(); fixId26 = "classSuperMustPrecedeThisAccess"; @@ -151959,23 +136589,32 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} registerCodeFix({ errorCodes: errorCodes31, getCodeActions(context) { - const { sourceFile, span } = context; + const { + sourceFile, + span + } = context; const nodes = getNodes(sourceFile, span.start); - if (!nodes) - return void 0; - const { constructor, superCall } = nodes; - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange19(t, sourceFile, constructor, superCall)); + if (!nodes) return void 0; + const { + constructor, + superCall + } = nodes; + const changes = ts_textChanges_exports.ChangeTracker.with(context, t => doChange19(t, sourceFile, constructor, superCall)); return [createCodeFixAction(fixId26, changes, Diagnostics.Make_super_call_the_first_statement_in_the_constructor, fixId26, Diagnostics.Make_all_super_calls_the_first_statement_in_their_constructor)]; }, fixIds: [fixId26], getAllCodeActions(context) { - const { sourceFile } = context; - const seenClasses = /* @__PURE__ */ new Map(); + const { + sourceFile + } = context; + const seenClasses = /* @__PURE__ */new Map(); return codeFixAll(context, errorCodes31, (changes, diag2) => { const nodes = getNodes(diag2.file, diag2.start); - if (!nodes) - return; - const { constructor, superCall } = nodes; + if (!nodes) return; + const { + constructor, + superCall + } = nodes; if (addToSeen(seenClasses, getNodeId(constructor.parent))) { doChange19(changes, sourceFile, constructor, superCall); } @@ -151992,19 +136631,16 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return token.parent; } function doChange20(changes, sourceFile, ctr) { - const superCall = factory.createExpressionStatement(factory.createCallExpression( - factory.createSuper(), - /*typeArguments*/ - void 0, - /*argumentsArray*/ - emptyArray - )); + const superCall = factory.createExpressionStatement(factory.createCallExpression(factory.createSuper(), /*typeArguments*/ + void 0, /*argumentsArray*/ + emptyArray)); changes.insertNodeAtConstructorStart(sourceFile, ctr, superCall); } var fixId27, errorCodes32; var init_fixConstructorForDerivedNeedSuperCall = __esm({ "src/services/codefixes/fixConstructorForDerivedNeedSuperCall.ts"() { "use strict"; + init_ts4(); init_ts_codefix(); fixId27 = "constructorForDerivedNeedSuperCall"; @@ -152012,13 +136648,16 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} registerCodeFix({ errorCodes: errorCodes32, getCodeActions(context) { - const { sourceFile, span } = context; + const { + sourceFile, + span + } = context; const ctr = getNode(sourceFile, span.start); - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange20(t, sourceFile, ctr)); + const changes = ts_textChanges_exports.ChangeTracker.with(context, t => doChange20(t, sourceFile, ctr)); return [createCodeFixAction(fixId27, changes, Diagnostics.Add_missing_super_call, fixId27, Diagnostics.Add_all_missing_super_calls)]; }, fixIds: [fixId27], - getAllCodeActions: (context) => codeFixAll(context, errorCodes32, (changes, diag2) => doChange20(changes, context.sourceFile, getNode(diag2.file, diag2.start))) + getAllCodeActions: context => codeFixAll(context, errorCodes32, (changes, diag2) => doChange20(changes, context.sourceFile, getNode(diag2.file, diag2.start))) }); } }); @@ -152031,6 +136670,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} var init_fixEnableJsxFlag = __esm({ "src/services/codefixes/fixEnableJsxFlag.ts"() { "use strict"; + init_ts4(); init_ts_codefix(); fixID = "fixEnableJsxFlag"; @@ -152038,18 +136678,20 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} registerCodeFix({ errorCodes: errorCodes33, getCodeActions: function getCodeActionsToFixEnableJsxFlag(context) { - const { configFile } = context.program.getCompilerOptions(); + const { + configFile + } = context.program.getCompilerOptions(); if (configFile === void 0) { return void 0; } - const changes = ts_textChanges_exports.ChangeTracker.with(context, (changeTracker) => doChange21(changeTracker, configFile)); - return [ - createCodeFixActionWithoutFixAll(fixID, changes, Diagnostics.Enable_the_jsx_flag_in_your_configuration_file) - ]; + const changes = ts_textChanges_exports.ChangeTracker.with(context, changeTracker => doChange21(changeTracker, configFile)); + return [createCodeFixActionWithoutFixAll(fixID, changes, Diagnostics.Enable_the_jsx_flag_in_your_configuration_file)]; }, fixIds: [fixID], - getAllCodeActions: (context) => codeFixAll(context, errorCodes33, (changes) => { - const { configFile } = context.program.getCompilerOptions(); + getAllCodeActions: context => codeFixAll(context, errorCodes33, changes => { + const { + configFile + } = context.program.getCompilerOptions(); if (configFile === void 0) { return void 0; } @@ -152061,33 +136703,26 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} // src/services/codefixes/fixNaNEquality.ts function getInfo11(program, sourceFile, span) { - const diag2 = find(program.getSemanticDiagnostics(sourceFile), (diag3) => diag3.start === span.start && diag3.length === span.length); - if (diag2 === void 0 || diag2.relatedInformation === void 0) - return; - const related = find(diag2.relatedInformation, (related2) => related2.code === Diagnostics.Did_you_mean_0.code); - if (related === void 0 || related.file === void 0 || related.start === void 0 || related.length === void 0) - return; + const diag2 = find(program.getSemanticDiagnostics(sourceFile), diag3 => diag3.start === span.start && diag3.length === span.length); + if (diag2 === void 0 || diag2.relatedInformation === void 0) return; + const related = find(diag2.relatedInformation, related2 => related2.code === Diagnostics.Did_you_mean_0.code); + if (related === void 0 || related.file === void 0 || related.start === void 0 || related.length === void 0) return; const token = findAncestorMatchingSpan(related.file, createTextSpan(related.start, related.length)); - if (token === void 0) - return; + if (token === void 0) return; if (isExpression(token) && isBinaryExpression(token.parent)) { - return { suggestion: getSuggestion(related.messageText), expression: token.parent, arg: token }; + return { + suggestion: getSuggestion(related.messageText), + expression: token.parent, + arg: token + }; } return void 0; } function doChange22(changes, sourceFile, arg, expression) { - const callExpression = factory.createCallExpression( - factory.createPropertyAccessExpression(factory.createIdentifier("Number"), factory.createIdentifier("isNaN")), - /*typeArguments*/ - void 0, - [arg] - ); + const callExpression = factory.createCallExpression(factory.createPropertyAccessExpression(factory.createIdentifier("Number"), factory.createIdentifier("isNaN")), /*typeArguments*/ + void 0, [arg]); const operator = expression.operatorToken.kind; - changes.replaceNode( - sourceFile, - expression, - operator === 38 /* ExclamationEqualsEqualsToken */ || operator === 36 /* ExclamationEqualsToken */ ? factory.createPrefixUnaryExpression(54 /* ExclamationToken */, callExpression) : callExpression - ); + changes.replaceNode(sourceFile, expression, operator === 38 /* ExclamationEqualsEqualsToken */ || operator === 36 /* ExclamationEqualsToken */ ? factory.createPrefixUnaryExpression(54 /* ExclamationToken */, callExpression) : callExpression); } function getSuggestion(messageText) { const [_, suggestion] = flattenDiagnosticMessageText(messageText, "\n", 0).match(/'(.*)'/) || []; @@ -152097,25 +136732,31 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} var init_fixNaNEquality = __esm({ "src/services/codefixes/fixNaNEquality.ts"() { "use strict"; + init_ts4(); init_ts_codefix(); fixId28 = "fixNaNEquality"; - errorCodes34 = [ - Diagnostics.This_condition_will_always_return_0.code - ]; + errorCodes34 = [Diagnostics.This_condition_will_always_return_0.code]; registerCodeFix({ errorCodes: errorCodes34, getCodeActions(context) { - const { sourceFile, span, program } = context; + const { + sourceFile, + span, + program + } = context; const info = getInfo11(program, sourceFile, span); - if (info === void 0) - return; - const { suggestion, expression, arg } = info; - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange22(t, sourceFile, arg, expression)); + if (info === void 0) return; + const { + suggestion, + expression, + arg + } = info; + const changes = ts_textChanges_exports.ChangeTracker.with(context, t => doChange22(t, sourceFile, arg, expression)); return [createCodeFixAction(fixId28, changes, [Diagnostics.Use_0, suggestion], fixId28, Diagnostics.Use_Number_isNaN_in_all_conditions)]; }, fixIds: [fixId28], - getAllCodeActions: (context) => { + getAllCodeActions: context => { return codeFixAll(context, errorCodes34, (changes, diag2) => { const info = getInfo11(context.program, diag2.file, createTextSpan(diag2.start, diag2.length)); if (info) { @@ -152131,17 +136772,16 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} var init_fixModuleAndTargetOptions = __esm({ "src/services/codefixes/fixModuleAndTargetOptions.ts"() { "use strict"; + init_ts4(); init_ts_codefix(); registerCodeFix({ - errorCodes: [ - Diagnostics.Top_level_await_expressions_are_only_allowed_when_the_module_option_is_set_to_es2022_esnext_system_node16_or_nodenext_and_the_target_option_is_set_to_es2017_or_higher.code, - Diagnostics.Top_level_await_using_statements_are_only_allowed_when_the_module_option_is_set_to_es2022_esnext_system_node16_or_nodenext_and_the_target_option_is_set_to_es2017_or_higher.code, - Diagnostics.Top_level_for_await_loops_are_only_allowed_when_the_module_option_is_set_to_es2022_esnext_system_node16_or_nodenext_and_the_target_option_is_set_to_es2017_or_higher.code - ], + errorCodes: [Diagnostics.Top_level_await_expressions_are_only_allowed_when_the_module_option_is_set_to_es2022_esnext_system_node16_or_nodenext_and_the_target_option_is_set_to_es2017_or_higher.code, Diagnostics.Top_level_await_using_statements_are_only_allowed_when_the_module_option_is_set_to_es2022_esnext_system_node16_or_nodenext_and_the_target_option_is_set_to_es2017_or_higher.code, Diagnostics.Top_level_for_await_loops_are_only_allowed_when_the_module_option_is_set_to_es2022_esnext_system_node16_or_nodenext_and_the_target_option_is_set_to_es2017_or_higher.code], getCodeActions: function getCodeActionsToFixModuleAndTarget(context) { const compilerOptions = context.program.getCompilerOptions(); - const { configFile } = compilerOptions; + const { + configFile + } = compilerOptions; if (configFile === void 0) { return void 0; } @@ -152149,7 +136789,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} const moduleKind = getEmitModuleKind(compilerOptions); const moduleOutOfRange = moduleKind >= 5 /* ES2015 */ && moduleKind < 99 /* ESNext */; if (moduleOutOfRange) { - const changes = ts_textChanges_exports.ChangeTracker.with(context, (changes2) => { + const changes = ts_textChanges_exports.ChangeTracker.with(context, changes2 => { setJsonCompilerOptionValue(changes2, configFile, "module", factory.createStringLiteral("esnext")); }); codeFixes.push(createCodeFixActionWithoutFixAll("fixModuleOption", changes, [Diagnostics.Set_the_module_option_in_your_configuration_file_to_0, "esnext"])); @@ -152157,10 +136797,9 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} const target = getEmitScriptTarget(compilerOptions); const targetOutOfRange = target < 4 /* ES2017 */ || target > 99 /* ESNext */; if (targetOutOfRange) { - const changes = ts_textChanges_exports.ChangeTracker.with(context, (tracker) => { + 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")]); @@ -152186,22 +136825,24 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} var init_fixPropertyAssignment = __esm({ "src/services/codefixes/fixPropertyAssignment.ts"() { "use strict"; + init_ts4(); init_ts_codefix(); fixId29 = "fixPropertyAssignment"; - errorCodes35 = [ - Diagnostics.Did_you_mean_to_use_a_Colon_An_can_only_follow_a_property_name_when_the_containing_object_literal_is_part_of_a_destructuring_pattern.code - ]; + errorCodes35 = [Diagnostics.Did_you_mean_to_use_a_Colon_An_can_only_follow_a_property_name_when_the_containing_object_literal_is_part_of_a_destructuring_pattern.code]; registerCodeFix({ errorCodes: errorCodes35, fixIds: [fixId29], getCodeActions(context) { - const { sourceFile, span } = context; + const { + sourceFile, + span + } = context; const property = getProperty2(sourceFile, span.start); - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange23(t, context.sourceFile, property)); + const changes = ts_textChanges_exports.ChangeTracker.with(context, t => doChange23(t, context.sourceFile, property)); return [createCodeFixAction(fixId29, changes, [Diagnostics.Change_0_to_1, "=", ":"], fixId29, [Diagnostics.Switch_each_misused_0_to_1, "=", ":"])]; }, - getAllCodeActions: (context) => codeFixAll(context, errorCodes35, (changes, diag2) => doChange23(changes, diag2.file, getProperty2(diag2.file, diag2.start))) + getAllCodeActions: context => codeFixAll(context, errorCodes35, (changes, diag2) => doChange23(changes, diag2.file, getProperty2(diag2.file, diag2.start))) }); } }); @@ -152211,26 +136852,36 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} const token = getTokenAtPosition(sourceFile, pos); const heritageClauses = getContainingClass(token).heritageClauses; const extendsToken = heritageClauses[0].getFirstToken(); - return extendsToken.kind === 96 /* ExtendsKeyword */ ? { extendsToken, heritageClauses } : void 0; + return extendsToken.kind === 96 /* ExtendsKeyword */ ? { + extendsToken, + heritageClauses + } : void 0; } function doChanges2(changes, sourceFile, extendsToken, heritageClauses) { changes.replaceNode(sourceFile, extendsToken, factory.createToken(119 /* ImplementsKeyword */)); if (heritageClauses.length === 2 && heritageClauses[0].token === 96 /* ExtendsKeyword */ && heritageClauses[1].token === 119 /* ImplementsKeyword */) { const implementsToken = heritageClauses[1].getFirstToken(); const implementsFullStart = implementsToken.getFullStart(); - changes.replaceRange(sourceFile, { pos: implementsFullStart, end: implementsFullStart }, factory.createToken(28 /* CommaToken */)); + changes.replaceRange(sourceFile, { + pos: implementsFullStart, + end: implementsFullStart + }, factory.createToken(28 /* CommaToken */)); const text = sourceFile.text; let end = implementsToken.end; while (end < text.length && isWhiteSpaceSingleLine(text.charCodeAt(end))) { end++; } - changes.deleteRange(sourceFile, { pos: implementsToken.getStart(), end }); + changes.deleteRange(sourceFile, { + pos: implementsToken.getStart(), + end + }); } } var fixId30, errorCodes36; var init_fixExtendsInterfaceBecomesImplements = __esm({ "src/services/codefixes/fixExtendsInterfaceBecomesImplements.ts"() { "use strict"; + init_ts4(); init_ts_codefix(); fixId30 = "extendsInterfaceBecomesImplements"; @@ -152238,19 +136889,22 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} registerCodeFix({ errorCodes: errorCodes36, getCodeActions(context) { - const { sourceFile } = context; + const { + sourceFile + } = context; const nodes = getNodes2(sourceFile, context.span.start); - if (!nodes) - return void 0; - const { extendsToken, heritageClauses } = nodes; - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChanges2(t, sourceFile, extendsToken, heritageClauses)); + 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)]; }, fixIds: [fixId30], - getAllCodeActions: (context) => codeFixAll(context, errorCodes36, (changes, diag2) => { + getAllCodeActions: context => codeFixAll(context, errorCodes36, (changes, diag2) => { const nodes = getNodes2(diag2.file, diag2.start); - if (nodes) - doChanges2(changes, diag2.file, nodes.extendsToken, nodes.heritageClauses); + if (nodes) doChanges2(changes, diag2.file, nodes.extendsToken, nodes.heritageClauses); }) }); } @@ -152260,10 +136914,16 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} function getInfo12(sourceFile, pos, diagCode) { const node = getTokenAtPosition(sourceFile, pos); if (isIdentifier(node) || isPrivateIdentifier(node)) { - return { node, className: diagCode === didYouMeanStaticMemberCode ? getContainingClass(node).name.text : void 0 }; + return { + node, + className: diagCode === didYouMeanStaticMemberCode ? getContainingClass(node).name.text : void 0 + }; } } - function doChange24(changes, sourceFile, { node, className }) { + function doChange24(changes, sourceFile, { + node, + className + }) { suppressLeadingAndTrailingTrivia(node); changes.replaceNode(sourceFile, node, factory.createPropertyAccessExpression(className ? factory.createIdentifier(className) : factory.createThis(), node)); } @@ -152271,31 +136931,29 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} var init_fixForgottenThisPropertyAccess = __esm({ "src/services/codefixes/fixForgottenThisPropertyAccess.ts"() { "use strict"; + init_ts4(); init_ts_codefix(); fixId31 = "forgottenThisPropertyAccess"; didYouMeanStaticMemberCode = Diagnostics.Cannot_find_name_0_Did_you_mean_the_static_member_1_0.code; - errorCodes37 = [ - Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0.code, - Diagnostics.Private_identifiers_are_only_allowed_in_class_bodies_and_may_only_be_used_as_part_of_a_class_member_declaration_property_access_or_on_the_left_hand_side_of_an_in_expression.code, - didYouMeanStaticMemberCode - ]; + errorCodes37 = [Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0.code, Diagnostics.Private_identifiers_are_only_allowed_in_class_bodies_and_may_only_be_used_as_part_of_a_class_member_declaration_property_access_or_on_the_left_hand_side_of_an_in_expression.code, didYouMeanStaticMemberCode]; registerCodeFix({ errorCodes: errorCodes37, getCodeActions(context) { - const { sourceFile } = context; + const { + sourceFile + } = context; const info = getInfo12(sourceFile, context.span.start, context.errorCode); if (!info) { return void 0; } - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange24(t, sourceFile, info)); + const changes = ts_textChanges_exports.ChangeTracker.with(context, t => doChange24(t, sourceFile, info)); return [createCodeFixAction(fixId31, changes, [Diagnostics.Add_0_to_unresolved_variable, info.className || "this"], fixId31, Diagnostics.Add_qualifier_to_all_unresolved_variables_matching_a_member_name)]; }, fixIds: [fixId31], - getAllCodeActions: (context) => codeFixAll(context, errorCodes37, (changes, diag2) => { + getAllCodeActions: context => codeFixAll(context, errorCodes37, (changes, diag2) => { const info = getInfo12(diag2.file, diag2.start, diag2.code); - if (info) - doChange24(changes, context.sourceFile, info); + if (info) doChange24(changes, context.sourceFile, info); }) }); } @@ -152311,45 +136969,35 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return; } const replacement = useHtmlEntity ? htmlEntity[character] : `{${quote(sourceFile, preferences, character)}}`; - changes.replaceRangeWithText(sourceFile, { pos: start, end: start + 1 }, replacement); + changes.replaceRangeWithText(sourceFile, { + pos: start, + end: start + 1 + }, replacement); } var fixIdExpression, fixIdHtmlEntity, errorCodes38, htmlEntity; var init_fixInvalidJsxCharacters = __esm({ "src/services/codefixes/fixInvalidJsxCharacters.ts"() { "use strict"; + init_ts4(); init_ts_codefix(); fixIdExpression = "fixInvalidJsxCharacters_expression"; fixIdHtmlEntity = "fixInvalidJsxCharacters_htmlEntity"; - errorCodes38 = [ - Diagnostics.Unexpected_token_Did_you_mean_or_gt.code, - Diagnostics.Unexpected_token_Did_you_mean_or_rbrace.code - ]; + errorCodes38 = [Diagnostics.Unexpected_token_Did_you_mean_or_gt.code, Diagnostics.Unexpected_token_Did_you_mean_or_rbrace.code]; registerCodeFix({ errorCodes: errorCodes38, fixIds: [fixIdExpression, fixIdHtmlEntity], getCodeActions(context) { - const { sourceFile, preferences, span } = context; - const changeToExpression = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange25( - t, - preferences, + const { sourceFile, - span.start, - /*useHtmlEntity*/ - false - )); - const changeToHtmlEntity = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange25( - t, preferences, - sourceFile, - span.start, - /*useHtmlEntity*/ - true - )); - return [ - createCodeFixAction(fixIdExpression, changeToExpression, Diagnostics.Wrap_invalid_character_in_an_expression_container, fixIdExpression, Diagnostics.Wrap_all_invalid_characters_in_an_expression_container), - createCodeFixAction(fixIdHtmlEntity, changeToHtmlEntity, Diagnostics.Convert_invalid_character_to_its_html_entity_code, fixIdHtmlEntity, Diagnostics.Convert_all_invalid_characters_to_HTML_entity_code) - ]; + span + } = context; + const changeToExpression = ts_textChanges_exports.ChangeTracker.with(context, t => doChange25(t, preferences, sourceFile, span.start, /*useHtmlEntity*/ + false)); + const changeToHtmlEntity = ts_textChanges_exports.ChangeTracker.with(context, t => doChange25(t, preferences, sourceFile, span.start, /*useHtmlEntity*/ + true)); + return [createCodeFixAction(fixIdExpression, changeToExpression, Diagnostics.Wrap_invalid_character_in_an_expression_container, fixIdExpression, Diagnostics.Wrap_all_invalid_characters_in_an_expression_container), createCodeFixAction(fixIdHtmlEntity, changeToHtmlEntity, Diagnostics.Convert_invalid_character_to_its_html_entity_code, fixIdHtmlEntity, Diagnostics.Convert_all_invalid_characters_to_HTML_entity_code)]; }, getAllCodeActions(context) { return codeFixAll(context, errorCodes38, (changes, diagnostic) => doChange25(changes, context.preferences, diagnostic.file, diagnostic.start, context.fixId === fixIdHtmlEntity)); @@ -152363,40 +137011,33 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} }); // src/services/codefixes/fixUnmatchedParameter.ts - function getDeleteAction(context, { name, jsDocHost, jsDocParameterTag }) { - const changes = ts_textChanges_exports.ChangeTracker.with(context, (changeTracker) => changeTracker.filterJSDocTags(context.sourceFile, jsDocHost, (t) => t !== jsDocParameterTag)); - return createCodeFixAction( - deleteUnmatchedParameter, - changes, - [Diagnostics.Delete_unused_param_tag_0, name.getText(context.sourceFile)], - deleteUnmatchedParameter, - Diagnostics.Delete_all_unused_param_tags - ); + function getDeleteAction(context, { + name, + jsDocHost, + jsDocParameterTag + }) { + const changes = ts_textChanges_exports.ChangeTracker.with(context, changeTracker => changeTracker.filterJSDocTags(context.sourceFile, jsDocHost, t => t !== jsDocParameterTag)); + return createCodeFixAction(deleteUnmatchedParameter, changes, [Diagnostics.Delete_unused_param_tag_0, name.getText(context.sourceFile)], deleteUnmatchedParameter, Diagnostics.Delete_all_unused_param_tags); } - function getRenameAction(context, { name, jsDocHost, signature, jsDocParameterTag }) { - if (!length(signature.parameters)) - return void 0; + function getRenameAction(context, { + name, + jsDocHost, + signature, + jsDocParameterTag + }) { + if (!length(signature.parameters)) return void 0; const sourceFile = context.sourceFile; const tags = getJSDocTags(signature); - const names = /* @__PURE__ */ new Set(); + const names = /* @__PURE__ */new Set(); for (const tag of tags) { if (isJSDocParameterTag(tag) && isIdentifier(tag.name)) { names.add(tag.name.escapedText); } } - const parameterName = firstDefined(signature.parameters, (p) => isIdentifier(p.name) && !names.has(p.name.escapedText) ? p.name.getText(sourceFile) : void 0); - if (parameterName === void 0) - return void 0; - const newJSDocParameterTag = factory.updateJSDocParameterTag( - jsDocParameterTag, - jsDocParameterTag.tagName, - factory.createIdentifier(parameterName), - jsDocParameterTag.isBracketed, - jsDocParameterTag.typeExpression, - jsDocParameterTag.isNameFirst, - jsDocParameterTag.comment - ); - const changes = ts_textChanges_exports.ChangeTracker.with(context, (changeTracker) => changeTracker.replaceJSDocComment(sourceFile, jsDocHost, map(tags, (t) => t === jsDocParameterTag ? newJSDocParameterTag : t))); + const parameterName = firstDefined(signature.parameters, p => isIdentifier(p.name) && !names.has(p.name.escapedText) ? p.name.getText(sourceFile) : void 0); + if (parameterName === void 0) return void 0; + const newJSDocParameterTag = factory.updateJSDocParameterTag(jsDocParameterTag, jsDocParameterTag.tagName, factory.createIdentifier(parameterName), jsDocParameterTag.isBracketed, jsDocParameterTag.typeExpression, jsDocParameterTag.isNameFirst, jsDocParameterTag.comment); + const changes = ts_textChanges_exports.ChangeTracker.with(context, changeTracker => changeTracker.replaceJSDocComment(sourceFile, jsDocHost, map(tags, t => t === jsDocParameterTag ? newJSDocParameterTag : t))); return createCodeFixActionWithoutFixAll(renameUnmatchedParameter, changes, [Diagnostics.Rename_param_tag_name_0_to_1, name.getText(sourceFile), parameterName]); } function getInfo13(sourceFile, pos) { @@ -152406,7 +137047,12 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} const jsDocHost = getJSDocHost(jsDocParameterTag); const signature = getHostSignatureFromJSDoc(jsDocParameterTag); if (jsDocHost && signature) { - return { jsDocHost, signature, name: token.parent.name, jsDocParameterTag }; + return { + jsDocHost, + signature, + name: token.parent.name, + jsDocParameterTag + }; } } return void 0; @@ -152415,18 +137061,20 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} var init_fixUnmatchedParameter = __esm({ "src/services/codefixes/fixUnmatchedParameter.ts"() { "use strict"; + init_ts4(); init_ts_codefix(); deleteUnmatchedParameter = "deleteUnmatchedParameter"; renameUnmatchedParameter = "renameUnmatchedParameter"; - errorCodes39 = [ - Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name.code - ]; + errorCodes39 = [Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name.code]; registerCodeFix({ fixIds: [deleteUnmatchedParameter, renameUnmatchedParameter], errorCodes: errorCodes39, getCodeActions: function getCodeActionsToFixUnmatchedParameter(context) { - const { sourceFile, span } = context; + const { + sourceFile, + span + } = context; const actions2 = []; const info = getInfo13(sourceFile, span.start); if (info) { @@ -152437,9 +137085,12 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return void 0; }, getAllCodeActions: function getAllCodeActionsToFixUnmatchedParameter(context) { - const tagsToSignature = /* @__PURE__ */ new Map(); - return createCombinedCodeActions(ts_textChanges_exports.ChangeTracker.with(context, (changes) => { - eachDiagnostic(context, errorCodes39, ({ file, start }) => { + const tagsToSignature = /* @__PURE__ */new Map(); + return createCombinedCodeActions(ts_textChanges_exports.ChangeTracker.with(context, changes => { + eachDiagnostic(context, errorCodes39, ({ + file, + start + }) => { const info = getInfo13(file, start); if (info) { tagsToSignature.set(info.signature, append(tagsToSignature.get(info.signature), info.jsDocParameterTag)); @@ -152448,7 +137099,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} tagsToSignature.forEach((tags, signature) => { if (context.fixId === deleteUnmatchedParameter) { const tagsSet = new Set(tags); - changes.filterJSDocTags(signature.getSourceFile(), signature, (t) => !tagsSet.has(t)); + changes.filterJSDocTags(signature.getSourceFile(), signature, t => !tagsSet.has(t)); } }); })); @@ -152460,8 +137111,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} // src/services/codefixes/fixUnreferenceableDecoratorMetadata.ts function getImportDeclaration(sourceFile, program, start) { const identifier = tryCast(getTokenAtPosition(sourceFile, start), isIdentifier); - if (!identifier || identifier.parent.kind !== 183 /* TypeReference */) - return; + 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)); @@ -152476,9 +137126,8 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return; } const checker = program.getTypeChecker(); - const importsValue = !!forEachImportClauseDeclaration(importClause, (decl) => { - if (skipAlias(decl.symbol, checker).flags & 111551 /* Value */) - return true; + const importsValue = !!forEachImportClauseDeclaration(importClause, decl => { + if (skipAlias(decl.symbol, checker).flags & 111551 /* Value */) return true; }); if (importsValue) { return; @@ -152492,18 +137141,18 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} var init_fixUnreferenceableDecoratorMetadata = __esm({ "src/services/codefixes/fixUnreferenceableDecoratorMetadata.ts"() { "use strict"; + init_ts4(); init_ts_codefix(); fixId32 = "fixUnreferenceableDecoratorMetadata"; errorCodes40 = [Diagnostics.A_type_referenced_in_a_decorated_signature_must_be_imported_with_import_type_or_a_namespace_import_when_isolatedModules_and_emitDecoratorMetadata_are_enabled.code]; registerCodeFix({ errorCodes: errorCodes40, - getCodeActions: (context) => { + getCodeActions: context => { const importDeclaration = getImportDeclaration(context.sourceFile, context.program, context.span.start); - if (!importDeclaration) - return; - const namespaceChanges = ts_textChanges_exports.ChangeTracker.with(context, (t) => importDeclaration.kind === 276 /* ImportSpecifier */ && doNamespaceImportChange(t, context.sourceFile, importDeclaration, context.program)); - const typeOnlyChanges = ts_textChanges_exports.ChangeTracker.with(context, (t) => doTypeOnlyImportChange(t, context.sourceFile, importDeclaration, context.program)); + if (!importDeclaration) return; + const namespaceChanges = ts_textChanges_exports.ChangeTracker.with(context, t => importDeclaration.kind === 276 /* ImportSpecifier */ && doNamespaceImportChange(t, context.sourceFile, importDeclaration, context.program)); + const typeOnlyChanges = ts_textChanges_exports.ChangeTracker.with(context, t => doTypeOnlyImportChange(t, context.sourceFile, importDeclaration, context.program)); let actions2; if (namespaceChanges.length) { actions2 = append(actions2, createCodeFixActionWithoutFixAll(fixId32, namespaceChanges, Diagnostics.Convert_named_imports_to_namespace_import)); @@ -152522,6 +137171,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} function changeInferToUnknown(changes, sourceFile, token) { changes.replaceNode(sourceFile, token.parent, factory.createKeywordTypeNode(159 /* UnknownKeyword */)); } + function createDeleteFix(changes, diag2) { return createCodeFixAction(fixName3, changes, diag2, fixIdDelete, Diagnostics.Delete_all_unused_declarations); } @@ -152531,6 +137181,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} function isImport(token) { return token.kind === 102 /* ImportKeyword */ || token.kind === 80 /* Identifier */ && (token.parent.kind === 276 /* ImportSpecifier */ || token.parent.kind === 273 /* ImportClause */); } + function tryGetFullImport(token) { return token.kind === 102 /* ImportKeyword */ ? tryCast(token.parent, isImportDeclaration) : void 0; } @@ -152541,9 +137192,11 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} changes.delete(sourceFile, node.parent.kind === 243 /* VariableStatement */ ? node.parent : node); } function deleteDestructuringElements(changes, sourceFile, node) { - forEach(node.elements, (n) => changes.delete(sourceFile, n)); + forEach(node.elements, n => changes.delete(sourceFile, n)); } - function deleteDestructuring(context, changes, sourceFile, { parent: parent2 }) { + function deleteDestructuring(context, changes, sourceFile, { + parent: parent2 + }) { if (isVariableDeclaration(parent2) && parent2.initializer && isCallLikeExpression(parent2.initializer)) { if (isVariableDeclarationList(parent2.parent) && length(parent2.parent.declarations) > 1) { const varStatement = parent2.parent.parent; @@ -152562,15 +137215,14 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } } 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; } if (isIdentifier(token) && canPrefix(token)) { changes.replaceNode(sourceFile, token, factory.createIdentifier(`_${token.text}`)); if (isParameter(token.parent)) { - getJSDocParameterTags(token.parent).forEach((tag) => { + getJSDocParameterTags(token.parent).forEach(tag => { if (isIdentifier(tag.name)) { changes.replaceNode(sourceFile, tag.name, factory.createIdentifier(`_${tag.name.text}`)); } @@ -152583,23 +137235,23 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} case 169 /* Parameter */: case 168 /* TypeParameter */: return true; - case 260 /* VariableDeclaration */: { - const varDecl = token.parent; - switch (varDecl.parent.parent.kind) { - case 250 /* ForOfStatement */: - case 249 /* ForInStatement */: - return true; + case 260 /* VariableDeclaration */: + { + const varDecl = token.parent; + switch (varDecl.parent.parent.kind) { + case 250 /* ForOfStatement */: + case 249 /* ForInStatement */: + return true; + } } - } } return false; } function tryDeleteDeclaration(sourceFile, token, changes, checker, sourceFiles, program, cancellationToken, isFixAll) { tryDeleteDeclarationWorker(token, changes, sourceFile, checker, sourceFiles, program, cancellationToken, isFixAll); if (isIdentifier(token)) { - ts_FindAllReferences_exports.Core.eachSymbolReferenceInFile(token, checker, sourceFile, (ref) => { - if (isPropertyAccessExpression(ref.parent) && ref.parent.name === ref) - ref = ref.parent; + ts_FindAllReferences_exports.Core.eachSymbolReferenceInFile(token, checker, sourceFile, ref => { + if (isPropertyAccessExpression(ref.parent) && ref.parent.name === ref) ref = ref.parent; if (!isFixAll && mayDeleteExpression(ref)) { changes.delete(sourceFile, ref.parent.parent); } @@ -152607,7 +137259,9 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } } function tryDeleteDeclarationWorker(token, changes, sourceFile, checker, sourceFiles, program, cancellationToken, isFixAll) { - const { parent: parent2 } = token; + const { + parent: parent2 + } = token; if (isParameter(parent2)) { tryDeleteParameter(changes, sourceFile, parent2, checker, sourceFiles, program, cancellationToken, isFixAll); } else if (!(isFixAll && isIdentifier(token) && ts_FindAllReferences_exports.Core.isSymbolReferencedInFile(token, checker, sourceFile))) { @@ -152634,7 +137288,9 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return !ts_FindAllReferences_exports.Core.someSignatureUsage(parameter.parent, sourceFiles, checker, (_, call) => !call || call.arguments.length > index); } function mayDeleteParameter(checker, sourceFile, parameter, sourceFiles, program, cancellationToken, isFixAll) { - const { parent: parent2 } = parameter; + const { + parent: parent2 + } = parameter; switch (parent2.kind) { case 174 /* MethodDeclaration */: case 176 /* Constructor */: @@ -152648,19 +137304,19 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} 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; } } } } return true; - case 262 /* FunctionDeclaration */: { - if (parent2.name && isCallbackLike(checker, sourceFile, parent2.name)) { - return isLastParameter(parent2, parameter, isFixAll); + case 262 /* FunctionDeclaration */: + { + if (parent2.name && isCallbackLike(checker, sourceFile, parent2.name)) { + return isLastParameter(parent2, parameter, isFixAll); + } + return true; } - return true; - } case 218 /* FunctionExpression */: case 219 /* ArrowFunction */: return isLastParameter(parent2, parameter, isFixAll); @@ -152673,13 +137329,13 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } } function isCallbackLike(checker, sourceFile, name) { - return !!ts_FindAllReferences_exports.Core.eachSymbolReferenceInFile(name, checker, sourceFile, (reference) => isIdentifier(reference) && isCallExpression(reference.parent) && reference.parent.arguments.includes(reference)); + return !!ts_FindAllReferences_exports.Core.eachSymbolReferenceInFile(name, checker, sourceFile, reference => isIdentifier(reference) && isCallExpression(reference.parent) && reference.parent.arguments.includes(reference)); } function isLastParameter(func, parameter, isFixAll) { const parameters = func.parameters; const index = parameters.indexOf(parameter); Debug.assert(index !== -1, "The parameter should already be in the list"); - return isFixAll ? parameters.slice(index + 1).every((p) => isIdentifier(p.name) && !p.symbol.isReferenced) : index === parameters.length - 1; + return isFixAll ? parameters.slice(index + 1).every(p => isIdentifier(p.name) && !p.symbol.isReferenced) : index === parameters.length - 1; } function mayDeleteExpression(node) { return (isBinaryExpression(node.parent) && node.parent.left === node || (isPostfixUnaryExpression(node.parent) || isPrefixUnaryExpression(node.parent)) && node.parent.operand === node) && isExpressionStatement(node.parent.parent); @@ -152688,6 +137344,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} var init_fixUnusedIdentifier = __esm({ "src/services/codefixes/fixUnusedIdentifier.ts"() { "use strict"; + init_ts4(); init_ts_codefix(); fixName3 = "unusedIdentifier"; @@ -152695,45 +137352,33 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} fixIdDelete = "unusedIdentifier_delete"; fixIdDeleteImports = "unusedIdentifier_deleteImports"; fixIdInfer = "unusedIdentifier_infer"; - errorCodes41 = [ - Diagnostics._0_is_declared_but_its_value_is_never_read.code, - Diagnostics._0_is_declared_but_never_used.code, - Diagnostics.Property_0_is_declared_but_its_value_is_never_read.code, - Diagnostics.All_imports_in_import_declaration_are_unused.code, - Diagnostics.All_destructured_elements_are_unused.code, - Diagnostics.All_variables_are_unused.code, - Diagnostics.All_type_parameters_are_unused.code - ]; + errorCodes41 = [Diagnostics._0_is_declared_but_its_value_is_never_read.code, Diagnostics._0_is_declared_but_never_used.code, Diagnostics.Property_0_is_declared_but_its_value_is_never_read.code, Diagnostics.All_imports_in_import_declaration_are_unused.code, Diagnostics.All_destructured_elements_are_unused.code, Diagnostics.All_variables_are_unused.code, Diagnostics.All_type_parameters_are_unused.code]; registerCodeFix({ errorCodes: errorCodes41, getCodeActions(context) { - const { errorCode, sourceFile, program, cancellationToken } = context; + const { + errorCode, + sourceFile, + program, + cancellationToken + } = context; const checker = program.getTypeChecker(); const sourceFiles = program.getSourceFiles(); const token = getTokenAtPosition(sourceFile, context.span.start); if (isJSDocTemplateTag(token)) { - return [createDeleteFix(ts_textChanges_exports.ChangeTracker.with(context, (t) => t.delete(sourceFile, token)), Diagnostics.Remove_template_tag)]; + return [createDeleteFix(ts_textChanges_exports.ChangeTracker.with(context, t => t.delete(sourceFile, token)), Diagnostics.Remove_template_tag)]; } if (token.kind === 30 /* LessThanToken */) { - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => deleteTypeParameters(t, sourceFile, token)); + const changes = ts_textChanges_exports.ChangeTracker.with(context, t => deleteTypeParameters(t, sourceFile, token)); return [createDeleteFix(changes, Diagnostics.Remove_type_parameters)]; } const importDecl = tryGetFullImport(token); if (importDecl) { - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => t.delete(sourceFile, importDecl)); + const changes = ts_textChanges_exports.ChangeTracker.with(context, t => t.delete(sourceFile, importDecl)); return [createCodeFixAction(fixName3, changes, [Diagnostics.Remove_import_from_0, showModuleSpecifier(importDecl)], fixIdDeleteImports, Diagnostics.Delete_all_unused_imports)]; } else if (isImport(token)) { - const deletion = ts_textChanges_exports.ChangeTracker.with(context, (t) => tryDeleteDeclaration( - sourceFile, - token, - t, - checker, - sourceFiles, - program, - cancellationToken, - /*isFixAll*/ - false - )); + const deletion = ts_textChanges_exports.ChangeTracker.with(context, t => tryDeleteDeclaration(sourceFile, token, t, checker, sourceFiles, program, cancellationToken, /*isFixAll*/ + false)); if (deletion.length) { return [createCodeFixAction(fixName3, deletion, [Diagnostics.Remove_unused_declaration_for_Colon_0, token.getText(sourceFile)], fixIdDeleteImports, Diagnostics.Delete_all_unused_imports)]; } @@ -152741,54 +137386,40 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (isObjectBindingPattern(token.parent) || isArrayBindingPattern(token.parent)) { if (isParameter(token.parent.parent)) { const elements = token.parent.elements; - const diagnostic = [ - elements.length > 1 ? Diagnostics.Remove_unused_declarations_for_Colon_0 : Diagnostics.Remove_unused_declaration_for_Colon_0, - map(elements, (e) => e.getText(sourceFile)).join(", ") - ]; - return [ - createDeleteFix(ts_textChanges_exports.ChangeTracker.with(context, (t) => deleteDestructuringElements(t, sourceFile, token.parent)), diagnostic) - ]; + const diagnostic = [elements.length > 1 ? Diagnostics.Remove_unused_declarations_for_Colon_0 : Diagnostics.Remove_unused_declaration_for_Colon_0, map(elements, e => e.getText(sourceFile)).join(", ")]; + return [createDeleteFix(ts_textChanges_exports.ChangeTracker.with(context, t => deleteDestructuringElements(t, sourceFile, token.parent)), diagnostic)]; } - return [ - createDeleteFix(ts_textChanges_exports.ChangeTracker.with(context, (t) => deleteDestructuring(context, t, sourceFile, token.parent)), Diagnostics.Remove_unused_destructuring_declaration) - ]; + return [createDeleteFix(ts_textChanges_exports.ChangeTracker.with(context, t => deleteDestructuring(context, t, sourceFile, token.parent)), Diagnostics.Remove_unused_destructuring_declaration)]; } if (canDeleteEntireVariableStatement(sourceFile, token)) { - return [ - createDeleteFix(ts_textChanges_exports.ChangeTracker.with(context, (t) => deleteEntireVariableStatement(t, sourceFile, token.parent)), Diagnostics.Remove_variable_statement) - ]; + return [createDeleteFix(ts_textChanges_exports.ChangeTracker.with(context, t => deleteEntireVariableStatement(t, sourceFile, token.parent)), Diagnostics.Remove_variable_statement)]; } const result = []; if (token.kind === 140 /* InferKeyword */) { - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => changeInferToUnknown(t, sourceFile, token)); + const changes = ts_textChanges_exports.ChangeTracker.with(context, t => changeInferToUnknown(t, sourceFile, token)); const name = cast(token.parent, isInferTypeNode).typeParameter.name.text; result.push(createCodeFixAction(fixName3, changes, [Diagnostics.Replace_infer_0_with_unknown, name], fixIdInfer, Diagnostics.Replace_all_unused_infer_with_unknown)); } else { - const deletion = ts_textChanges_exports.ChangeTracker.with(context, (t) => tryDeleteDeclaration( - sourceFile, - token, - t, - checker, - sourceFiles, - program, - cancellationToken, - /*isFixAll*/ - false - )); + const deletion = ts_textChanges_exports.ChangeTracker.with(context, t => tryDeleteDeclaration(sourceFile, token, t, checker, sourceFiles, program, cancellationToken, /*isFixAll*/ + false)); if (deletion.length) { const name = isComputedPropertyName(token.parent) ? token.parent : token; result.push(createDeleteFix(deletion, [Diagnostics.Remove_unused_declaration_for_Colon_0, name.getText(sourceFile)])); } } - const prefix = ts_textChanges_exports.ChangeTracker.with(context, (t) => tryPrefixDeclaration(t, errorCode, sourceFile, token)); + const prefix = ts_textChanges_exports.ChangeTracker.with(context, t => tryPrefixDeclaration(t, errorCode, sourceFile, token)); if (prefix.length) { result.push(createCodeFixAction(fixName3, prefix, [Diagnostics.Prefix_0_with_an_underscore, token.getText(sourceFile)], fixIdPrefix, Diagnostics.Prefix_all_unused_declarations_with_where_possible)); } return result; }, fixIds: [fixIdPrefix, fixIdDelete, fixIdDeleteImports, fixIdInfer], - getAllCodeActions: (context) => { - const { sourceFile, program, cancellationToken } = context; + getAllCodeActions: context => { + const { + sourceFile, + program, + cancellationToken + } = context; const checker = program.getTypeChecker(); const sourceFiles = program.getSourceFiles(); return codeFixAll(context, errorCodes41, (changes, diag2) => { @@ -152797,57 +137428,41 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} case fixIdPrefix: tryPrefixDeclaration(changes, diag2.code, sourceFile, token); break; - case fixIdDeleteImports: { - const importDecl = tryGetFullImport(token); - if (importDecl) { - changes.delete(sourceFile, importDecl); - } else if (isImport(token)) { - tryDeleteDeclaration( - sourceFile, - token, - changes, - checker, - sourceFiles, - program, - cancellationToken, - /*isFixAll*/ - true - ); - } - break; - } - case fixIdDelete: { - if (token.kind === 140 /* InferKeyword */ || isImport(token)) { - break; - } else if (isJSDocTemplateTag(token)) { - changes.delete(sourceFile, token); - } else if (token.kind === 30 /* LessThanToken */) { - deleteTypeParameters(changes, sourceFile, token); - } else if (isObjectBindingPattern(token.parent)) { - if (token.parent.parent.initializer) { - break; - } else if (!isParameter(token.parent.parent) || isNotProvidedArguments(token.parent.parent, checker, sourceFiles)) { - changes.delete(sourceFile, token.parent.parent); + case fixIdDeleteImports: + { + const importDecl = tryGetFullImport(token); + if (importDecl) { + changes.delete(sourceFile, importDecl); + } else if (isImport(token)) { + tryDeleteDeclaration(sourceFile, token, changes, checker, sourceFiles, program, cancellationToken, /*isFixAll*/ + true); + } + break; + } + case fixIdDelete: + { + if (token.kind === 140 /* InferKeyword */ || isImport(token)) { + break; + } else if (isJSDocTemplateTag(token)) { + changes.delete(sourceFile, token); + } else if (token.kind === 30 /* LessThanToken */) { + deleteTypeParameters(changes, sourceFile, token); + } else if (isObjectBindingPattern(token.parent)) { + if (token.parent.parent.initializer) { + break; + } else if (!isParameter(token.parent.parent) || isNotProvidedArguments(token.parent.parent, checker, sourceFiles)) { + changes.delete(sourceFile, token.parent.parent); + } + } else if (isArrayBindingPattern(token.parent.parent) && token.parent.parent.parent.initializer) { + break; + } else if (canDeleteEntireVariableStatement(sourceFile, token)) { + deleteEntireVariableStatement(changes, sourceFile, token.parent); + } else { + tryDeleteDeclaration(sourceFile, token, changes, checker, sourceFiles, program, cancellationToken, /*isFixAll*/ + true); } - } else if (isArrayBindingPattern(token.parent.parent) && token.parent.parent.parent.initializer) { break; - } else if (canDeleteEntireVariableStatement(sourceFile, token)) { - deleteEntireVariableStatement(changes, sourceFile, token.parent); - } else { - tryDeleteDeclaration( - sourceFile, - token, - changes, - checker, - sourceFiles, - program, - cancellationToken, - /*isFixAll*/ - true - ); } - break; - } case fixIdInfer: if (token.kind === 140 /* InferKeyword */) { changeInferToUnknown(changes, sourceFile, token); @@ -152896,7 +137511,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } if (isBlock(statement.parent)) { const end = start + length2; - const lastStatement = Debug.checkDefined(lastWhere(sliceAfter(statement.parent.statements, statement), (s) => s.pos < end), "Some statement should be last"); + const lastStatement = Debug.checkDefined(lastWhere(sliceAfter(statement.parent.statements, statement), s => s.pos < end), "Some statement should be last"); changes.deleteNodeRange(sourceFile, statement, lastStatement); } else { changes.delete(sourceFile, statement); @@ -152905,8 +137520,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} function lastWhere(a, pred) { let last2; for (const value of a) { - if (!pred(value)) - break; + if (!pred(value)) break; last2 = value; } return last2; @@ -152915,6 +137529,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} var init_fixUnreachableCode = __esm({ "src/services/codefixes/fixUnreachableCode.ts"() { "use strict"; + init_ts4(); init_ts_codefix(); fixId33 = "fixUnreachableCode"; @@ -152923,13 +137538,12 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} errorCodes: errorCodes42, getCodeActions(context) { const syntacticDiagnostics = context.program.getSyntacticDiagnostics(context.sourceFile, context.cancellationToken); - if (syntacticDiagnostics.length) - return; - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange26(t, context.sourceFile, context.span.start, context.span.length, context.errorCode)); + if (syntacticDiagnostics.length) return; + const changes = ts_textChanges_exports.ChangeTracker.with(context, t => doChange26(t, context.sourceFile, context.span.start, context.span.length, context.errorCode)); return [createCodeFixAction(fixId33, changes, Diagnostics.Remove_unreachable_code, fixId33, Diagnostics.Remove_all_unreachable_code)]; }, fixIds: [fixId33], - getAllCodeActions: (context) => codeFixAll(context, errorCodes42, (changes, diag2) => doChange26(changes, diag2.file, diag2.start, diag2.length, diag2.code)) + getAllCodeActions: context => codeFixAll(context, errorCodes42, (changes, diag2) => doChange26(changes, diag2.file, diag2.start, diag2.length, diag2.code)) }); } }); @@ -152940,18 +137554,18 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} const labeledStatement = cast(token.parent, isLabeledStatement); const pos = token.getStart(sourceFile); const statementPos = labeledStatement.statement.getStart(sourceFile); - const end = positionsAreOnSameLine(pos, statementPos, sourceFile) ? statementPos : skipTrivia( - sourceFile.text, - findChildOfKind(labeledStatement, 59 /* ColonToken */, sourceFile).end, - /*stopAfterLineBreak*/ - true - ); - changes.deleteRange(sourceFile, { pos, end }); + const end = positionsAreOnSameLine(pos, statementPos, sourceFile) ? statementPos : skipTrivia(sourceFile.text, findChildOfKind(labeledStatement, 59 /* ColonToken */, sourceFile).end, /*stopAfterLineBreak*/ + true); + changes.deleteRange(sourceFile, { + pos, + end + }); } var fixId34, errorCodes43; var init_fixUnusedLabel = __esm({ "src/services/codefixes/fixUnusedLabel.ts"() { "use strict"; + init_ts4(); init_ts_codefix(); fixId34 = "fixUnusedLabel"; @@ -152959,29 +137573,28 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} registerCodeFix({ errorCodes: errorCodes43, getCodeActions(context) { - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange27(t, context.sourceFile, context.span.start)); + const changes = ts_textChanges_exports.ChangeTracker.with(context, t => doChange27(t, context.sourceFile, context.span.start)); return [createCodeFixAction(fixId34, changes, Diagnostics.Remove_unused_label, fixId34, Diagnostics.Remove_all_unused_labels)]; }, fixIds: [fixId34], - getAllCodeActions: (context) => codeFixAll(context, errorCodes43, (changes, diag2) => doChange27(changes, diag2.file, diag2.start)) + getAllCodeActions: context => codeFixAll(context, errorCodes43, (changes, diag2) => doChange27(changes, diag2.file, diag2.start)) }); } }); // src/services/codefixes/fixJSDocTypes.ts function doChange28(changes, sourceFile, oldTypeNode, newType, checker) { - changes.replaceNode(sourceFile, oldTypeNode, checker.typeToTypeNode( - newType, - /*enclosingDeclaration*/ - oldTypeNode, - /*flags*/ - void 0 - )); + changes.replaceNode(sourceFile, oldTypeNode, checker.typeToTypeNode(newType, /*enclosingDeclaration*/ + oldTypeNode, /*flags*/ + void 0)); } function getInfo14(sourceFile, pos, checker) { const decl = findAncestor(getTokenAtPosition(sourceFile, pos), isTypeContainer); const typeNode = decl && decl.type; - return typeNode && { typeNode, type: getType(checker, typeNode) }; + return typeNode && { + typeNode, + type: getType(checker, typeNode) + }; } function isTypeContainer(node) { switch (node.kind) { @@ -153012,9 +137625,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (type === checker.getNeverType() || type === checker.getVoidType()) { return type; } - return checker.getUnionType( - append([type, checker.getUndefinedType()], node.postfix ? void 0 : checker.getNullType()) - ); + return checker.getUnionType(append([type, checker.getUndefinedType()], node.postfix ? void 0 : checker.getNullType())); } return checker.getTypeFromTypeNode(node); } @@ -153022,24 +137633,25 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} var init_fixJSDocTypes = __esm({ "src/services/codefixes/fixJSDocTypes.ts"() { "use strict"; + init_ts4(); init_ts_codefix(); fixIdPlain = "fixJSDocTypes_plain"; fixIdNullable = "fixJSDocTypes_nullable"; - errorCodes44 = [ - Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments.code, - Diagnostics._0_at_the_end_of_a_type_is_not_valid_TypeScript_syntax_Did_you_mean_to_write_1.code, - Diagnostics._0_at_the_start_of_a_type_is_not_valid_TypeScript_syntax_Did_you_mean_to_write_1.code - ]; + errorCodes44 = [Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments.code, Diagnostics._0_at_the_end_of_a_type_is_not_valid_TypeScript_syntax_Did_you_mean_to_write_1.code, Diagnostics._0_at_the_start_of_a_type_is_not_valid_TypeScript_syntax_Did_you_mean_to_write_1.code]; registerCodeFix({ errorCodes: errorCodes44, getCodeActions(context) { - const { sourceFile } = context; + const { + sourceFile + } = context; const checker = context.program.getTypeChecker(); const info = getInfo14(sourceFile, context.span.start, checker); - if (!info) - return void 0; - const { typeNode, type } = info; + 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)]; if (typeNode.kind === 321 /* JSDocNullableType */) { @@ -153047,19 +137659,25 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } return actions2; function fix(type2, fixId52, fixAllDescription) { - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange28(t, sourceFile, typeNode, type2, checker)); + const changes = ts_textChanges_exports.ChangeTracker.with(context, t => doChange28(t, sourceFile, typeNode, type2, checker)); return createCodeFixAction("jdocTypes", changes, [Diagnostics.Change_0_to_1, original, checker.typeToString(type2)], fixId52, fixAllDescription); } }, fixIds: [fixIdPlain, fixIdNullable], getAllCodeActions(context) { - const { fixId: fixId52, program, sourceFile } = context; + const { + fixId: fixId52, + program, + sourceFile + } = context; const checker = program.getTypeChecker(); return codeFixAll(context, errorCodes44, (changes, err) => { const info = getInfo14(err.file, err.start, checker); - if (!info) - return; - const { typeNode, type } = info; + if (!info) return; + const { + typeNode, + type + } = info; const fixedType = typeNode.kind === 321 /* JSDocNullableType */ && fixId52 === fixIdNullable ? checker.getNullableType(type, 32768 /* Undefined */) : type; doChange28(changes, sourceFile, typeNode, fixedType, checker); }); @@ -153090,27 +137708,27 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} var init_fixMissingCallParentheses = __esm({ "src/services/codefixes/fixMissingCallParentheses.ts"() { "use strict"; + init_ts4(); init_ts_codefix(); fixId35 = "fixMissingCallParentheses"; - errorCodes45 = [ - Diagnostics.This_condition_will_always_return_true_since_this_function_is_always_defined_Did_you_mean_to_call_it_instead.code - ]; + errorCodes45 = [Diagnostics.This_condition_will_always_return_true_since_this_function_is_always_defined_Did_you_mean_to_call_it_instead.code]; registerCodeFix({ errorCodes: errorCodes45, fixIds: [fixId35], getCodeActions(context) { - const { sourceFile, span } = context; + const { + sourceFile, + span + } = context; const callName = getCallName(sourceFile, span.start); - if (!callName) - return; - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange29(t, context.sourceFile, callName)); + if (!callName) return; + const changes = ts_textChanges_exports.ChangeTracker.with(context, t => doChange29(t, context.sourceFile, callName)); return [createCodeFixAction(fixId35, changes, Diagnostics.Add_missing_call_parentheses, fixId35, Diagnostics.Add_all_missing_call_parentheses)]; }, - getAllCodeActions: (context) => codeFixAll(context, errorCodes45, (changes, diag2) => { + getAllCodeActions: context => codeFixAll(context, errorCodes45, (changes, diag2) => { const callName = getCallName(diag2.file, diag2.start); - if (callName) - doChange29(changes, diag2.file, callName); + if (callName) doChange29(changes, diag2.file, callName); }) }); } @@ -153152,7 +137770,10 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} returnType: getReturnType(containingFunction) }; } - function doChange30(changes, sourceFile, { insertBefore, returnType }) { + function doChange30(changes, sourceFile, { + insertBefore, + returnType + }) { if (returnType) { const entityName = getEntityNameFromTypeNode(returnType); if (!entityName || entityName.kind !== 80 /* Identifier */ || entityName.text !== "Promise") { @@ -153165,32 +137786,29 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} var init_fixAwaitInSyncFunction = __esm({ "src/services/codefixes/fixAwaitInSyncFunction.ts"() { "use strict"; + init_ts4(); init_ts_codefix(); fixId36 = "fixAwaitInSyncFunction"; - errorCodes46 = [ - Diagnostics.await_expressions_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules.code, - Diagnostics.await_using_statements_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules.code, - Diagnostics.for_await_loops_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules.code, - Diagnostics.Cannot_find_name_0_Did_you_mean_to_write_this_in_an_async_function.code - ]; + errorCodes46 = [Diagnostics.await_expressions_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules.code, Diagnostics.await_using_statements_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules.code, Diagnostics.for_await_loops_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules.code, Diagnostics.Cannot_find_name_0_Did_you_mean_to_write_this_in_an_async_function.code]; registerCodeFix({ errorCodes: errorCodes46, getCodeActions(context) { - const { sourceFile, span } = context; + const { + sourceFile, + span + } = context; const nodes = getNodes3(sourceFile, span.start); - if (!nodes) - return void 0; - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange30(t, sourceFile, nodes)); + if (!nodes) return void 0; + const changes = ts_textChanges_exports.ChangeTracker.with(context, t => doChange30(t, sourceFile, nodes)); return [createCodeFixAction(fixId36, changes, Diagnostics.Add_async_modifier_to_containing_function, fixId36, Diagnostics.Add_all_missing_async_modifiers)]; }, fixIds: [fixId36], getAllCodeActions: function getAllCodeActionsToFixAwaitInSyncFunction(context) { - const seen = /* @__PURE__ */ new Map(); + const seen = /* @__PURE__ */new Map(); return codeFixAll(context, errorCodes46, (changes, diag2) => { const nodes = getNodes3(diag2.file, diag2.start); - if (!nodes || !addToSeen(seen, getNodeId(nodes.insertBefore))) - return; + if (!nodes || !addToSeen(seen, getNodeId(nodes.insertBefore))) return; doChange30(changes, context.sourceFile, nodes); }); } @@ -153212,12 +137830,10 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} 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); @@ -153230,12 +137846,10 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} var init_fixPropertyOverrideAccessor = __esm({ "src/services/codefixes/fixPropertyOverrideAccessor.ts"() { "use strict"; + init_ts4(); init_ts_codefix(); - errorCodes47 = [ - Diagnostics._0_is_defined_as_an_accessor_in_class_1_but_is_overridden_here_in_2_as_an_instance_property.code, - Diagnostics._0_is_defined_as_a_property_in_class_1_but_is_overridden_here_in_2_as_an_accessor.code - ]; + errorCodes47 = [Diagnostics._0_is_defined_as_an_accessor_in_class_1_but_is_overridden_here_in_2_as_an_instance_property.code, Diagnostics._0_is_defined_as_a_property_in_class_1_but_is_overridden_here_in_2_as_an_accessor.code]; fixId37 = "fixPropertyOverrideAccessor"; registerCodeFix({ errorCodes: errorCodes47, @@ -153246,7 +137860,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } }, fixIds: [fixId37], - getAllCodeActions: (context) => codeFixAll(context, errorCodes47, (changes, diag2) => { + getAllCodeActions: context => codeFixAll(context, errorCodes47, (changes, diag2) => { const edits = doChange31(diag2.file, diag2.start, diag2.length, diag2.code, context); if (edits) { for (const edit of edits) { @@ -153298,7 +137912,9 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (!isParameterPropertyModifier(token.kind) && token.kind !== 80 /* Identifier */ && token.kind !== 26 /* DotDotDotToken */ && token.kind !== 110 /* ThisKeyword */) { return void 0; } - const { parent: parent2 } = token; + const { + parent: parent2 + } = token; const importAdder = createImportAdder(sourceFile, program, preferences, host); errorCode = mapSuggestionDiagnostic(errorCode); switch (errorCode) { @@ -153313,28 +137929,25 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} const type = inferTypeForVariableFromUsage(parent2.name, program, cancellationToken); const typeNode = getTypeNodeIfAccessible(type, parent2, program, host); if (typeNode) { - const typeTag = factory.createJSDocTypeTag( - /*tagName*/ - void 0, - factory.createJSDocTypeExpression(typeNode), - /*comment*/ - void 0 - ); + const typeTag = factory.createJSDocTypeTag( /*tagName*/ + void 0, factory.createJSDocTypeExpression(typeNode), /*comment*/ + void 0); changes.addJSDocTags(sourceFile, cast(parent2.parent.parent, isExpressionStatement), [typeTag]); } importAdder.writeFixes(changes); return parent2; } return void 0; - case Diagnostics.Variable_0_implicitly_has_an_1_type.code: { - const symbol = program.getTypeChecker().getSymbolAtLocation(token); - if (symbol && symbol.valueDeclaration && isVariableDeclaration(symbol.valueDeclaration) && markSeen(symbol.valueDeclaration)) { - annotateVariableDeclaration(changes, importAdder, getSourceFileOfNode(symbol.valueDeclaration), symbol.valueDeclaration, program, host, cancellationToken); - importAdder.writeFixes(changes); - return symbol.valueDeclaration; + case Diagnostics.Variable_0_implicitly_has_an_1_type.code: + { + const symbol = program.getTypeChecker().getSymbolAtLocation(token); + if (symbol && symbol.valueDeclaration && isVariableDeclaration(symbol.valueDeclaration) && markSeen(symbol.valueDeclaration)) { + annotateVariableDeclaration(changes, importAdder, getSourceFileOfNode(symbol.valueDeclaration), symbol.valueDeclaration, program, host, cancellationToken); + importAdder.writeFixes(changes); + return symbol.valueDeclaration; + } + return void 0; } - return void 0; - } } const containingFunction = getContainingFunction(token); if (containingFunction === void 0) { @@ -153395,17 +138008,19 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} annotateJSDocParameters(changes, sourceFile, parameterInferences, program, host); } else { const needParens = isArrowFunction(containingFunction) && !findChildOfKind(containingFunction, 21 /* OpenParenToken */, sourceFile); - if (needParens) - changes.insertNodeBefore(sourceFile, first(containingFunction.parameters), factory.createToken(21 /* OpenParenToken */)); - for (const { declaration, type } of parameterInferences) { + 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) { const references = getFunctionReferences(containingFunction, sourceFile, program, cancellationToken); if (!references || !references.length) { @@ -153423,13 +138038,8 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } } function annotateJSDocThis(changes, sourceFile, containingFunction, typeNode) { - changes.addJSDocTags(sourceFile, containingFunction, [ - factory.createJSDocThisTag( - /*tagName*/ - void 0, - factory.createJSDocTypeExpression(typeNode) - ) - ]); + changes.addJSDocTags(sourceFile, containingFunction, [factory.createJSDocThisTag( /*tagName*/ + void 0, factory.createJSDocTypeExpression(typeNode))]); } function annotateSetAccessor(changes, importAdder, sourceFile, setAccessorDeclaration, program, host, cancellationToken) { const param = firstOrUndefined(setAccessorDeclaration.parameters); @@ -153439,7 +138049,10 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} type = inferTypeForVariableFromUsage(param.name, program, cancellationToken); } if (isInJSFile(setAccessorDeclaration)) { - annotateJSDocParameters(changes, sourceFile, [{ declaration: param, type }], program, host); + annotateJSDocParameters(changes, sourceFile, [{ + declaration: param, + type + }], program, host); } else { annotate(changes, importAdder, sourceFile, param, type, program, host); } @@ -153454,19 +138067,11 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return; } const typeExpression = factory.createJSDocTypeExpression(typeNode); - const typeTag = isGetAccessorDeclaration(declaration) ? factory.createJSDocReturnTag( - /*tagName*/ - void 0, - typeExpression, - /*comment*/ - void 0 - ) : factory.createJSDocTypeTag( - /*tagName*/ - void 0, - typeExpression, - /*comment*/ - void 0 - ); + const typeTag = isGetAccessorDeclaration(declaration) ? factory.createJSDocReturnTag( /*tagName*/ + void 0, typeExpression, /*comment*/ + void 0) : factory.createJSDocTypeTag( /*tagName*/ + void 0, typeExpression, /*comment*/ + void 0); changes.addJSDocTags(sourceFile, parent2, [typeTag]); } else if (!tryReplaceImportTypeNodeWithAutoImport(typeNode, declaration, sourceFile, changes, importAdder, getEmitScriptTarget(program.getCompilerOptions()))) { changes.tryInsertTypeAnnotation(sourceFile, declaration, typeNode); @@ -153476,11 +138081,8 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} function tryReplaceImportTypeNodeWithAutoImport(typeNode, declaration, sourceFile, changes, importAdder, scriptTarget) { const importableReference = tryGetAutoImportableReferenceFromTypeNode(typeNode, scriptTarget); if (importableReference && changes.tryInsertTypeAnnotation(sourceFile, declaration, importableReference.typeNode)) { - forEach(importableReference.symbols, (s) => importAdder.addImportFromExportedSymbol( - s, - /*isValidTypeOnlyUseSite*/ - true - )); + forEach(importableReference.symbols, s => importAdder.addImportFromExportedSymbol(s, /*isValidTypeOnlyUseSite*/ + true)); return true; } return false; @@ -153490,7 +138092,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (!signature) { return; } - const inferences = mapDefined(parameterInferences, (inference) => { + const inferences = mapDefined(parameterInferences, inference => { const param = inference.declaration; if (param.initializer || getJSDocType(param) || !isIdentifier(param.name)) { return; @@ -153499,7 +138101,12 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (typeNode) { const name = factory.cloneNode(param.name); setEmitFlags(name, 3072 /* NoComments */ | 4096 /* NoNestedComments */); - return { name: factory.cloneNode(param.name), param, isOptional: !!inference.isOptional, typeNode }; + return { + name: factory.cloneNode(param.name), + param, + isOptional: !!inference.isOptional, + typeNode + }; } }); if (!inferences.length) { @@ -153510,40 +138117,37 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (needParens) { changes.insertNodeBefore(sourceFile, first(signature.parameters), factory.createToken(21 /* OpenParenToken */)); } - forEach(inferences, ({ typeNode, param }) => { - const typeTag = factory.createJSDocTypeTag( - /*tagName*/ - void 0, - factory.createJSDocTypeExpression(typeNode) - ); - const jsDoc = factory.createJSDocComment( - /*comment*/ - void 0, - [typeTag] - ); - changes.insertNodeAt(sourceFile, param.getStart(sourceFile), jsDoc, { suffix: " " }); + + forEach(inferences, ({ + typeNode, + param + }) => { + const typeTag = factory.createJSDocTypeTag( /*tagName*/ + void 0, factory.createJSDocTypeExpression(typeNode)); + const jsDoc = factory.createJSDocComment( /*comment*/ + void 0, [typeTag]); + changes.insertNodeAt(sourceFile, param.getStart(sourceFile), jsDoc, { + suffix: " " + }); }); if (needParens) { changes.insertNodeAfter(sourceFile, last(signature.parameters), factory.createToken(22 /* CloseParenToken */)); } } else { - const paramTags = map(inferences, ({ name, typeNode, isOptional }) => factory.createJSDocParameterTag( - /*tagName*/ - void 0, + const paramTags = map(inferences, ({ name, - /*isBracketed*/ - !!isOptional, - factory.createJSDocTypeExpression(typeNode), - /*isNameFirst*/ - false, - /*comment*/ - void 0 - )); + typeNode, + isOptional + }) => factory.createJSDocParameterTag( /*tagName*/ + void 0, name, /*isBracketed*/ + !!isOptional, factory.createJSDocTypeExpression(typeNode), /*isNameFirst*/ + false, /*comment*/ + void 0)); changes.addJSDocTags(sourceFile, signature, paramTags); } } function getReferences(token, program, cancellationToken) { - return mapDefined(ts_FindAllReferences_exports.getReferenceEntriesForNode(-1, token, program, program.getSourceFiles(), cancellationToken), (entry) => entry.kind !== ts_FindAllReferences_exports.EntryKind.Span ? tryCast(entry.node, isIdentifier) : void 0); + return mapDefined(ts_FindAllReferences_exports.getReferenceEntriesForNode(-1, token, program, program.getSourceFiles(), cancellationToken), entry => entry.kind !== ts_FindAllReferences_exports.EntryKind.Span ? tryCast(entry.node, isIdentifier) : void 0); } function inferTypeForVariableFromUsage(token, program, cancellationToken) { const references = getReferences(token, program, cancellationToken); @@ -153551,7 +138155,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } function inferTypeForParametersFromUsage(func, sourceFile, program, cancellationToken) { const references = getFunctionReferences(func, sourceFile, program, cancellationToken); - return references && inferTypeFromReferences(program, references, cancellationToken).parameters(func) || func.parameters.map((p) => ({ + return references && inferTypeFromReferences(program, references, cancellationToken).parameters(func) || func.parameters.map(p => ({ declaration: p, type: isIdentifier(p.name) ? inferTypeForVariableFromUsage(p.name, program, cancellationToken) : program.getTypeChecker().getAnyType() })); @@ -153583,15 +138187,10 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} const builtinConstructors = { string: () => checker.getStringType(), number: () => checker.getNumberType(), - Array: (t) => checker.createArrayType(t), - Promise: (t) => checker.createPromiseType(t) + Array: t => checker.createArrayType(t), + Promise: t => checker.createPromiseType(t) }; - const builtins = [ - checker.getStringType(), - checker.getNumberType(), - checker.createArrayType(checker.getAnyType()), - checker.createPromiseType(checker.getAnyType()) - ]; + const builtins = [checker.getStringType(), checker.getNumberType(), checker.createArrayType(checker.getAnyType()), checker.createPromiseType(checker.getAnyType())]; return { single: single2, parameters, @@ -153613,7 +138212,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} }; } function combineUsages(usages) { - const combinedProperties = /* @__PURE__ */ new Map(); + const combinedProperties = /* @__PURE__ */new Map(); for (const u of usages) { if (u.properties) { u.properties.forEach((p, name) => { @@ -153624,25 +138223,26 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} }); } } - const properties = /* @__PURE__ */ new Map(); + const properties = /* @__PURE__ */new Map(); combinedProperties.forEach((ps, name) => { properties.set(name, combineUsages(ps)); }); return { - isNumber: usages.some((u) => u.isNumber), - isString: usages.some((u) => u.isString), - isNumberOrString: usages.some((u) => u.isNumberOrString), - candidateTypes: flatMap(usages, (u) => u.candidateTypes), + isNumber: usages.some(u => u.isNumber), + isString: usages.some(u => u.isString), + isNumberOrString: usages.some(u => u.isNumberOrString), + candidateTypes: flatMap(usages, u => u.candidateTypes), properties, - calls: flatMap(usages, (u) => u.calls), - constructs: flatMap(usages, (u) => u.constructs), - numberIndex: forEach(usages, (u) => u.numberIndex), - stringIndex: forEach(usages, (u) => u.stringIndex), - candidateThisTypes: flatMap(usages, (u) => u.candidateThisTypes), + calls: flatMap(usages, u => u.calls), + constructs: flatMap(usages, u => u.constructs), + numberIndex: forEach(usages, u => u.numberIndex), + stringIndex: forEach(usages, u => u.stringIndex), + candidateThisTypes: flatMap(usages, u => u.candidateThisTypes), inferredTypes: void 0 // clear type cache }; } + function single2() { return combineTypes(inferTypesFromReferencesSingle(references)); } @@ -153655,7 +138255,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} cancellationToken.throwIfCancellationRequested(); calculateUsageOfNode(reference, usage); } - const calls = [...usage.constructs || [], ...usage.calls || []]; + const calls = [...(usage.constructs || []), ...(usage.calls || [])]; return declaration.parameters.map((parameter, parameterIndex) => { const types = []; const isRest = isRestParameter(parameter); @@ -153674,7 +138274,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } if (isIdentifier(parameter.name)) { const inferred = inferTypesFromReferencesSingle(getReferences(parameter.name, program, cancellationToken)); - types.push(...isRest ? mapDefined(inferred, checker.getElementTypeOfArrayType) : inferred); + types.push(...(isRest ? mapDefined(inferred, checker.getElementTypeOfArrayType) : inferred)); } const type = combineTypes(types); return { @@ -153742,15 +138342,19 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} case 172 /* PropertyDeclaration */: inferTypeFromPropertyDeclaration(node.parent, usage); break; - case 260 /* VariableDeclaration */: { - const { name, initializer } = node.parent; - if (node === name) { - if (initializer) { - addCandidateType(usage, checker.getTypeAtLocation(initializer)); + case 260 /* VariableDeclaration */: + { + const { + name, + initializer + } = node.parent; + if (node === name) { + if (initializer) { + addCandidateType(usage, checker.getTypeAtLocation(initializer)); + } + break; } - break; } - } default: return inferTypeFromContextualType(node, usage); } @@ -153820,8 +138424,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} usage.isNumber = true; } else if (otherOperandType.flags & 402653316 /* StringLike */) { usage.isString = true; - } else if (otherOperandType.flags & 1 /* Any */) { - } else { + } else if (otherOperandType.flags & 1 /* Any */) {} else { usage.isNumberOrString = true; } break; @@ -153842,11 +138445,8 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} break; case 57 /* BarBarToken */: case 61 /* QuestionQuestionToken */: - if (node === parent2.left && (node.parent.parent.kind === 260 /* VariableDeclaration */ || isAssignmentExpression( - node.parent.parent, - /*excludeCompoundAssignment*/ - true - ))) { + if (node === parent2.left && (node.parent.parent.kind === 260 /* VariableDeclaration */ || isAssignmentExpression(node.parent.parent, /*excludeCompoundAssignment*/ + true))) { addCandidateType(usage, checker.getTypeAtLocation(parent2.right)); } break; @@ -153879,7 +138479,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} function inferTypeFromPropertyAccessExpression(parent2, usage) { const name = escapeLeadingUnderscores(parent2.name.text); if (!usage.properties) { - usage.properties = /* @__PURE__ */ new Map(); + usage.properties = /* @__PURE__ */new Map(); } const propertyUsage = usage.properties.get(name) || createEmptyUsage(); calculateUsageOfNode(parent2, propertyUsage); @@ -153910,44 +138510,44 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} function removeLowPriorityInferences(inferences, priorities) { const toRemove = []; for (const i of inferences) { - for (const { high, low } of priorities) { + for (const { + high, + low + } of priorities) { if (high(i)) { Debug.assert(!low(i), "Priority can't have both low and high"); toRemove.push(low); } } } - return inferences.filter((i) => toRemove.every((f) => !f(i))); + return inferences.filter(i => toRemove.every(f => !f(i))); } function combineFromUsage(usage) { return combineTypes(inferTypes(usage)); } function combineTypes(inferences) { - if (!inferences.length) - return checker.getAnyType(); + if (!inferences.length) return checker.getAnyType(); const stringNumber = checker.getUnionType([checker.getStringType(), checker.getNumberType()]); - const priorities = [ - { - high: (t) => t === checker.getStringType() || t === checker.getNumberType(), - low: (t) => t === stringNumber - }, - { - high: (t) => !(t.flags & (1 /* Any */ | 16384 /* Void */)), - low: (t) => !!(t.flags & (1 /* Any */ | 16384 /* Void */)) - }, - { - high: (t) => !(t.flags & (98304 /* Nullable */ | 1 /* Any */ | 16384 /* Void */)) && !(getObjectFlags(t) & 16 /* Anonymous */), - low: (t) => !!(getObjectFlags(t) & 16 /* Anonymous */) - } - ]; + const priorities = [{ + high: t => t === checker.getStringType() || t === checker.getNumberType(), + low: t => t === stringNumber + }, { + high: t => !(t.flags & (1 /* Any */ | 16384 /* Void */)), + low: t => !!(t.flags & (1 /* Any */ | 16384 /* Void */)) + }, { + high: t => !(t.flags & (98304 /* Nullable */ | 1 /* Any */ | 16384 /* Void */)) && !(getObjectFlags(t) & 16 /* Anonymous */), + low: t => !!(getObjectFlags(t) & 16 /* Anonymous */) + }]; + let good = removeLowPriorityInferences(inferences, priorities); - const anons = good.filter((i) => getObjectFlags(i) & 16 /* Anonymous */); + const anons = good.filter(i => getObjectFlags(i) & 16 /* Anonymous */); if (anons.length) { - good = good.filter((i) => !(getObjectFlags(i) & 16 /* Anonymous */)); + good = good.filter(i => !(getObjectFlags(i) & 16 /* Anonymous */)); good.push(combineAnonymousTypes(anons)); } return checker.getWidenedType(checker.getUnionType(good.map(checker.getBaseTypeOfLiteralType), 2 /* Subtype */)); } + function combineAnonymousTypes(anons) { if (anons.length === 1) { return anons[0]; @@ -153983,17 +138583,9 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return [name, s]; }); const indexInfos = []; - if (stringIndices.length) - indexInfos.push(checker.createIndexInfo(checker.getStringType(), checker.getUnionType(stringIndices), stringIndexReadonly)); - if (numberIndices.length) - indexInfos.push(checker.createIndexInfo(checker.getNumberType(), checker.getUnionType(numberIndices), numberIndexReadonly)); - return checker.createAnonymousType( - anons[0].symbol, - members, - calls, - constructs, - indexInfos - ); + if (stringIndices.length) indexInfos.push(checker.createIndexInfo(checker.getStringType(), checker.getUnionType(stringIndices), stringIndexReadonly)); + if (numberIndices.length) indexInfos.push(checker.createIndexInfo(checker.getNumberType(), checker.getUnionType(numberIndices), numberIndexReadonly)); + return checker.createAnonymousType(anons[0].symbol, members, calls, constructs, indexInfos); } function inferTypes(usage) { var _a, _b, _c; @@ -154013,7 +138605,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (((_a = usage.properties) == null ? void 0 : _a.size) || ((_b = usage.constructs) == null ? void 0 : _b.length) || usage.stringIndex) { types.push(inferStructuralType(usage)); } - const candidateTypes = (usage.candidateTypes || []).map((t) => checker.getBaseTypeOfLiteralType(t)); + const candidateTypes = (usage.candidateTypes || []).map(t => checker.getBaseTypeOfLiteralType(t)); const callsType = ((_c = usage.calls) == null ? void 0 : _c.length) ? inferStructuralType(usage) : void 0; if (callsType && candidateTypes) { types.push(checker.getUnionType([callsType, ...candidateTypes], 2 /* Subtype */)); @@ -154029,7 +138621,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return types; } function inferStructuralType(usage) { - const members = /* @__PURE__ */ new Map(); + const members = /* @__PURE__ */new Map(); if (usage.properties) { usage.properties.forEach((u, name) => { const symbol = checker.createSymbol(4 /* Property */, name); @@ -154039,33 +138631,21 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } const callSignatures = usage.calls ? [getSignatureFromCalls(usage.calls)] : []; const constructSignatures = usage.constructs ? [getSignatureFromCalls(usage.constructs)] : []; - const indexInfos = usage.stringIndex ? [checker.createIndexInfo( - checker.getStringType(), - combineFromUsage(usage.stringIndex), - /*isReadonly*/ - false - )] : []; - return checker.createAnonymousType( - /*symbol*/ - void 0, - members, - callSignatures, - constructSignatures, - indexInfos - ); + const indexInfos = usage.stringIndex ? [checker.createIndexInfo(checker.getStringType(), combineFromUsage(usage.stringIndex), /*isReadonly*/ + false)] : []; + return checker.createAnonymousType( /*symbol*/ + void 0, members, callSignatures, constructSignatures, indexInfos); } function inferNamedTypesFromProperties(usage) { - if (!usage.properties || !usage.properties.size) - return []; - const types = builtins.filter((t) => allPropertiesAreAssignableToUsage(t, usage)); + if (!usage.properties || !usage.properties.size) return []; + const types = builtins.filter(t => allPropertiesAreAssignableToUsage(t, usage)); if (0 < types.length && types.length < 3) { - return types.map((t) => inferInstantiationFromUsage(t, usage)); + return types.map(t => inferInstantiationFromUsage(t, usage)); } 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) { @@ -154085,8 +138665,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } 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); @@ -154099,7 +138678,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (genericType === typeParameter) { return [usageType]; } else if (genericType.flags & 3145728 /* UnionOrIntersection */) { - return flatMap(genericType.types, (t) => inferTypeParameters(t, usageType, typeParameter)); + return flatMap(genericType.types, t => inferTypeParameters(t, usageType, typeParameter)); } else if (getObjectFlags(genericType) & 4 /* Reference */ && getObjectFlags(usageType) & 4 /* Reference */) { const genericArgs = checker.getTypeArguments(genericType); const usageArgs = checker.getTypeArguments(usageType); @@ -154144,42 +138723,29 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return types; } function getFunctionFromCalls(calls) { - return checker.createAnonymousType( - /*symbol*/ - void 0, - createSymbolTable(), - [getSignatureFromCalls(calls)], - emptyArray, - emptyArray - ); + return checker.createAnonymousType( /*symbol*/ + void 0, createSymbolTable(), [getSignatureFromCalls(calls)], emptyArray, emptyArray); } function getSignatureFromCalls(calls) { const parameters2 = []; - const length2 = Math.max(...calls.map((c) => c.argumentTypes.length)); + const length2 = Math.max(...calls.map(c => c.argumentTypes.length)); for (let i = 0; i < length2; i++) { const symbol = checker.createSymbol(1 /* FunctionScopedVariable */, escapeLeadingUnderscores(`arg${i}`)); - symbol.links.type = combineTypes(calls.map((call) => call.argumentTypes[i] || checker.getUndefinedType())); - if (calls.some((call) => call.argumentTypes[i] === void 0)) { + symbol.links.type = combineTypes(calls.map(call => call.argumentTypes[i] || checker.getUndefinedType())); + if (calls.some(call => call.argumentTypes[i] === void 0)) { symbol.flags |= 16777216 /* Optional */; } + parameters2.push(symbol); } - const returnType = combineFromUsage(combineUsages(calls.map((call) => call.return_))); - return checker.createSignature( - /*declaration*/ - void 0, - /*typeParameters*/ - void 0, - /*thisParameter*/ - void 0, - parameters2, - returnType, - /*typePredicate*/ - void 0, - length2, - 0 /* None */ - ); + const returnType = combineFromUsage(combineUsages(calls.map(call => call.return_))); + return checker.createSignature( /*declaration*/ + void 0, /*typeParameters*/ + void 0, /*thisParameter*/ + void 0, parameters2, returnType, /*typePredicate*/ + void 0, length2, 0 /* None */); } + function addCandidateType(usage, type) { if (type && !(type.flags & 1 /* Any */) && !(type.flags & 131072 /* Never */)) { (usage.candidateTypes || (usage.candidateTypes = [])).push(type); @@ -154195,68 +138761,70 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} var init_inferFromUsage = __esm({ "src/services/codefixes/inferFromUsage.ts"() { "use strict"; + init_ts4(); init_ts_codefix(); fixId38 = "inferFromUsage"; errorCodes48 = [ - // Variable declarations - Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined.code, - // Variable uses - Diagnostics.Variable_0_implicitly_has_an_1_type.code, - // Parameter declarations - Diagnostics.Parameter_0_implicitly_has_an_1_type.code, - Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code, - // Get Accessor declarations - Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation.code, - Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type.code, - // Set Accessor declarations - Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation.code, - // Property declarations - Diagnostics.Member_0_implicitly_has_an_1_type.code, - //// Suggestions - // Variable declarations - Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_but_a_better_type_may_be_inferred_from_usage.code, - // Variable uses - Diagnostics.Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code, - // Parameter declarations - Diagnostics.Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code, - Diagnostics.Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage.code, - // Get Accessor declarations - Diagnostics.Property_0_implicitly_has_type_any_but_a_better_type_for_its_get_accessor_may_be_inferred_from_usage.code, - Diagnostics._0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage.code, - // Set Accessor declarations - Diagnostics.Property_0_implicitly_has_type_any_but_a_better_type_for_its_set_accessor_may_be_inferred_from_usage.code, - // Property declarations - Diagnostics.Member_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code, - // Function expressions and declarations - Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation.code - ]; + // Variable declarations + Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined.code, + // Variable uses + Diagnostics.Variable_0_implicitly_has_an_1_type.code, + // Parameter declarations + Diagnostics.Parameter_0_implicitly_has_an_1_type.code, Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code, + // Get Accessor declarations + Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation.code, Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type.code, + // Set Accessor declarations + Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation.code, + // Property declarations + Diagnostics.Member_0_implicitly_has_an_1_type.code, + //// Suggestions + // Variable declarations + Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_but_a_better_type_may_be_inferred_from_usage.code, + // Variable uses + Diagnostics.Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code, + // Parameter declarations + Diagnostics.Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code, Diagnostics.Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage.code, + // Get Accessor declarations + Diagnostics.Property_0_implicitly_has_type_any_but_a_better_type_for_its_get_accessor_may_be_inferred_from_usage.code, Diagnostics._0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage.code, + // Set Accessor declarations + Diagnostics.Property_0_implicitly_has_type_any_but_a_better_type_for_its_set_accessor_may_be_inferred_from_usage.code, + // Property declarations + Diagnostics.Member_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code, + // Function expressions and declarations + Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation.code]; registerCodeFix({ errorCodes: errorCodes48, getCodeActions(context) { - const { sourceFile, program, span: { start }, errorCode, cancellationToken, host, preferences } = context; + const { + sourceFile, + program, + span: { + start + }, + errorCode, + cancellationToken, + host, + preferences + } = context; const token = getTokenAtPosition(sourceFile, start); let declaration; - const changes = ts_textChanges_exports.ChangeTracker.with(context, (changes2) => { - declaration = doChange32( - changes2, - sourceFile, - token, - errorCode, - program, - cancellationToken, - /*markSeen*/ - returnTrue, - host, - preferences - ); + const changes = ts_textChanges_exports.ChangeTracker.with(context, changes2 => { + declaration = doChange32(changes2, sourceFile, token, errorCode, program, cancellationToken, /*markSeen*/ + returnTrue, host, preferences); }); const name = declaration && getNameOfDeclaration(declaration); return !name || changes.length === 0 ? void 0 : [createCodeFixAction(fixId38, changes, [getDiagnostic(errorCode, token), getTextOfNode(name)], fixId38, Diagnostics.Infer_all_types_from_usage)]; }, fixIds: [fixId38], getAllCodeActions(context) { - const { sourceFile, program, cancellationToken, host, preferences } = context; + const { + sourceFile, + program, + cancellationToken, + host, + preferences + } = context; const markSeen = nodeSeenTracker(); return codeFixAll(context, errorCodes48, (changes, err) => { doChange32(changes, sourceFile, getTokenAtPosition(err.file, err.start), err.code, program, cancellationToken, markSeen, host, preferences); @@ -154279,15 +138847,16 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } const returnType = checker.getTypeFromTypeNode(returnTypeNode); const promisedType = checker.getAwaitedType(returnType) || checker.getVoidType(); - const promisedTypeNode = checker.typeToTypeNode( - promisedType, - /*enclosingDeclaration*/ - returnTypeNode, - /*flags*/ - void 0 - ); + const promisedTypeNode = checker.typeToTypeNode(promisedType, /*enclosingDeclaration*/ + returnTypeNode, /*flags*/ + void 0); if (promisedTypeNode) { - return { returnTypeNode, returnType, promisedTypeNode, promisedType }; + return { + returnTypeNode, + returnType, + promisedTypeNode, + promisedType + }; } } function doChange33(changes, sourceFile, returnTypeNode, promisedTypeNode) { @@ -154297,33 +138866,35 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} var init_fixReturnTypeInAsyncFunction = __esm({ "src/services/codefixes/fixReturnTypeInAsyncFunction.ts"() { "use strict"; + init_ts4(); init_ts_codefix(); fixId39 = "fixReturnTypeInAsyncFunction"; - errorCodes49 = [ - Diagnostics.The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_Did_you_mean_to_write_Promise_0.code - ]; + errorCodes49 = [Diagnostics.The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_Did_you_mean_to_write_Promise_0.code]; registerCodeFix({ errorCodes: errorCodes49, fixIds: [fixId39], getCodeActions: function getCodeActionsToFixReturnTypeInAsyncFunction(context) { - const { sourceFile, program, span } = context; + const { + sourceFile, + program, + span + } = context; const checker = program.getTypeChecker(); const info = getInfo15(sourceFile, program.getTypeChecker(), span.start); if (!info) { return void 0; } - const { returnTypeNode, returnType, promisedTypeNode, promisedType } = info; - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange33(t, sourceFile, returnTypeNode, promisedTypeNode)); - return [createCodeFixAction( - fixId39, - changes, - [Diagnostics.Replace_0_with_Promise_1, checker.typeToString(returnType), checker.typeToString(promisedType)], - fixId39, - Diagnostics.Fix_all_incorrect_return_type_of_an_async_functions - )]; + const { + returnTypeNode, + returnType, + promisedTypeNode, + promisedType + } = info; + const changes = ts_textChanges_exports.ChangeTracker.with(context, t => doChange33(t, sourceFile, returnTypeNode, promisedTypeNode)); + return [createCodeFixAction(fixId39, changes, [Diagnostics.Replace_0_with_Promise_1, checker.typeToString(returnType), checker.typeToString(promisedType)], fixId39, Diagnostics.Fix_all_incorrect_return_type_of_an_async_functions)]; }, - getAllCodeActions: (context) => codeFixAll(context, errorCodes49, (changes, diag2) => { + getAllCodeActions: context => codeFixAll(context, errorCodes49, (changes, diag2) => { const info = getInfo15(diag2.file, context.program.getTypeChecker(), diag2.start); if (info) { doChange33(changes, diag2.file, info.returnTypeNode, info.promisedTypeNode); @@ -154335,7 +138906,9 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} // src/services/codefixes/disableJsDiagnostics.ts function makeChange8(changes, sourceFile, position, seenLines) { - const { line: lineNumber } = getLineAndCharacterOfPosition(sourceFile, position); + const { + line: lineNumber + } = getLineAndCharacterOfPosition(sourceFile, position); if (!seenLines || tryAddToSet(seenLines, lineNumber)) { changes.insertCommentBeforeLine(sourceFile, lineNumber, position, " @ts-ignore"); } @@ -154344,43 +138917,40 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} var init_disableJsDiagnostics = __esm({ "src/services/codefixes/disableJsDiagnostics.ts"() { "use strict"; + init_ts4(); init_ts_codefix(); fixName4 = "disableJsDiagnostics"; fixId40 = "disableJsDiagnostics"; - errorCodes50 = mapDefined(Object.keys(Diagnostics), (key) => { + errorCodes50 = mapDefined(Object.keys(Diagnostics), key => { const diag2 = Diagnostics[key]; return diag2.category === 1 /* Error */ ? diag2.code : void 0; }); registerCodeFix({ errorCodes: errorCodes50, getCodeActions: function getCodeActionsToDisableJsDiagnostics(context) { - const { sourceFile, program, span, host, formatContext } = context; + const { + sourceFile, + program, + span, + host, + formatContext + } = context; if (!isInJSFile(sourceFile) || !isCheckJsEnabledForFile(sourceFile, program.getCompilerOptions())) { return void 0; } const newLineCharacter = sourceFile.checkJsDirective ? "" : getNewLineOrDefaultFromHost(host, formatContext.options); const fixes = [ - // fixId unnecessary because adding `// @ts-nocheck` even once will ignore every error in the file. - createCodeFixActionWithoutFixAll( - fixName4, - [createFileTextChanges(sourceFile.fileName, [ - createTextChange( - sourceFile.checkJsDirective ? createTextSpanFromBounds(sourceFile.checkJsDirective.pos, sourceFile.checkJsDirective.end) : createTextSpan(0, 0), - `// @ts-nocheck${newLineCharacter}` - ) - ])], - Diagnostics.Disable_checking_for_this_file - ) - ]; + // fixId unnecessary because adding `// @ts-nocheck` even once will ignore every error in the file. + createCodeFixActionWithoutFixAll(fixName4, [createFileTextChanges(sourceFile.fileName, [createTextChange(sourceFile.checkJsDirective ? createTextSpanFromBounds(sourceFile.checkJsDirective.pos, sourceFile.checkJsDirective.end) : createTextSpan(0, 0), `// @ts-nocheck${newLineCharacter}`)])], Diagnostics.Disable_checking_for_this_file)]; if (ts_textChanges_exports.isValidLocationToAddComment(sourceFile, span.start)) { - fixes.unshift(createCodeFixAction(fixName4, ts_textChanges_exports.ChangeTracker.with(context, (t) => makeChange8(t, sourceFile, span.start)), Diagnostics.Ignore_this_error_message, fixId40, Diagnostics.Add_ts_ignore_to_all_error_messages)); + fixes.unshift(createCodeFixAction(fixName4, ts_textChanges_exports.ChangeTracker.with(context, t => makeChange8(t, sourceFile, span.start)), Diagnostics.Ignore_this_error_message, fixId40, Diagnostics.Add_ts_ignore_to_all_error_messages)); } return fixes; }, fixIds: [fixId40], - getAllCodeActions: (context) => { - const seenLines = /* @__PURE__ */ new Set(); + getAllCodeActions: context => { + const seenLines = /* @__PURE__ */new Set(); return codeFixAll(context, errorCodes50, (changes, diag2) => { if (ts_textChanges_exports.isValidLocationToAddComment(diag2.file, diag2.start)) { makeChange8(changes, diag2.file, diag2.start, seenLines); @@ -154396,17 +138966,8 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} const classMembers = classDeclaration.symbol.members; for (const symbol of possiblyMissingSymbols) { if (!classMembers.has(symbol.escapedName)) { - addNewNodeForMemberSymbol( - symbol, - classDeclaration, - sourceFile, - context, - preferences, - importAdder, - addClassElement, - /*body*/ - void 0 - ); + addNewNodeForMemberSymbol(symbol, classDeclaration, sourceFile, context, preferences, importAdder, addClassElement, /*body*/ + void 0); } } } @@ -154417,11 +138978,12 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} }; } function addNewNodeForMemberSymbol(symbol, enclosingDeclaration, sourceFile, context, preferences, importAdder, addClassElement, body, preserveOptional = 3 /* All */, isAmbient = false) { + var _ref45; const declarations = symbol.getDeclarations(); const declaration = firstOrUndefined(declarations); const checker = context.program.getTypeChecker(); const scriptTarget = getEmitScriptTarget(context.program.getCompilerOptions()); - const kind = (declaration == null ? void 0 : declaration.kind) ?? 171 /* PropertySignature */; + const kind = (_ref45 = declaration == null ? void 0 : declaration.kind) !== null && _ref45 !== void 0 ? _ref45 : 171 /* PropertySignature */; const declarationName = createDeclarationName(symbol, declaration); const effectiveModifierFlags = declaration ? getEffectiveModifierFlags(declaration) : 0 /* None */; let modifierFlags = effectiveModifierFlags & 256 /* Static */; @@ -154429,6 +138991,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (declaration && isAutoAccessorPropertyDeclaration(declaration)) { modifierFlags |= 512 /* Accessor */; } + const modifiers = createModifiers(); const type = checker.getWidenedType(checker.getTypeOfSymbolAtLocation(symbol, enclosingDeclaration)); const optional = !!(symbol.flags & 16777216 /* Optional */); @@ -154446,68 +139009,41 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} importSymbols(importAdder, importableReference.symbols); } } - addClassElement(factory.createPropertyDeclaration( - modifiers, - declaration ? createName(declarationName) : symbol.getName(), - optional && preserveOptional & 2 /* Property */ ? factory.createToken(58 /* QuestionToken */) : void 0, - typeNode, - /*initializer*/ - void 0 - )); + addClassElement(factory.createPropertyDeclaration(modifiers, declaration ? createName(declarationName) : symbol.getName(), optional && preserveOptional & 2 /* Property */ ? factory.createToken(58 /* QuestionToken */) : void 0, typeNode, /*initializer*/ + void 0)); break; case 177 /* GetAccessor */: - case 178 /* SetAccessor */: { - Debug.assertIsDefined(declarations); - let typeNode2 = checker.typeToTypeNode( - type, - enclosingDeclaration, - /*flags*/ - void 0, - getNoopSymbolTrackerWithResolver(context) - ); - const allAccessors = getAllAccessorDeclarations(declarations, declaration); - const orderedAccessors = allAccessors.secondAccessor ? [allAccessors.firstAccessor, allAccessors.secondAccessor] : [allAccessors.firstAccessor]; - if (importAdder) { - const importableReference = tryGetAutoImportableReferenceFromTypeNode(typeNode2, scriptTarget); - if (importableReference) { - typeNode2 = importableReference.typeNode; - importSymbols(importAdder, importableReference.symbols); + case 178 /* SetAccessor */: + { + Debug.assertIsDefined(declarations); + let typeNode2 = checker.typeToTypeNode(type, enclosingDeclaration, /*flags*/ + void 0, getNoopSymbolTrackerWithResolver(context)); + const allAccessors = getAllAccessorDeclarations(declarations, declaration); + const orderedAccessors = allAccessors.secondAccessor ? [allAccessors.firstAccessor, allAccessors.secondAccessor] : [allAccessors.firstAccessor]; + if (importAdder) { + const importableReference = tryGetAutoImportableReferenceFromTypeNode(typeNode2, scriptTarget); + if (importableReference) { + typeNode2 = importableReference.typeNode; + importSymbols(importAdder, importableReference.symbols); + } } - } - for (const accessor of orderedAccessors) { - if (isGetAccessorDeclaration(accessor)) { - addClassElement(factory.createGetAccessorDeclaration( - modifiers, - createName(declarationName), - emptyArray, - createTypeNode(typeNode2), - createBody(body, quotePreference, ambient) - )); - } else { - Debug.assertNode(accessor, isSetAccessorDeclaration, "The counterpart to a getter should be a setter"); - const parameter = getSetAccessorValueParameter(accessor); - const parameterName = parameter && isIdentifier(parameter.name) ? idText(parameter.name) : void 0; - addClassElement(factory.createSetAccessorDeclaration( - modifiers, - createName(declarationName), - createDummyParameters( - 1, - [parameterName], - [createTypeNode(typeNode2)], - 1, - /*inJs*/ - false - ), - createBody(body, quotePreference, ambient) - )); + for (const accessor of orderedAccessors) { + if (isGetAccessorDeclaration(accessor)) { + addClassElement(factory.createGetAccessorDeclaration(modifiers, createName(declarationName), emptyArray, createTypeNode(typeNode2), createBody(body, quotePreference, ambient))); + } else { + Debug.assertNode(accessor, isSetAccessorDeclaration, "The counterpart to a getter should be a setter"); + const parameter = getSetAccessorValueParameter(accessor); + const parameterName = parameter && isIdentifier(parameter.name) ? idText(parameter.name) : void 0; + addClassElement(factory.createSetAccessorDeclaration(modifiers, createName(declarationName), createDummyParameters(1, [parameterName], [createTypeNode(typeNode2)], 1, /*inJs*/ + false), createBody(body, quotePreference, ambient))); + } } + break; } - break; - } case 173 /* MethodSignature */: case 174 /* MethodDeclaration */: Debug.assertIsDefined(declarations); - const signatures = type.isUnion() ? flatMap(type.types, (t) => t.getCallSignatures()) : type.getCallSignatures(); + const signatures = type.isUnion() ? flatMap(type.types, t => t.getCallSignatures()) : type.getCallSignatures(); if (!some(signatures)) { break; } @@ -154533,8 +139069,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } 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; @@ -154544,6 +139079,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (shouldAddOverrideKeyword()) { modifiers2 = append(modifiers2, factory.createToken(164 /* OverrideKeyword */)); } + return modifiers2 && factory.createNodeArray(modifiers2); } function shouldAddOverrideKeyword() { @@ -154553,25 +139089,17 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (isIdentifier(node) && node.escapedText === "constructor") { return factory.createComputedPropertyName(factory.createStringLiteral(idText(node), quotePreference === 0 /* Single */)); } - return getSynthesizedDeepClone( - node, - /*includeTrivia*/ - false - ); + + return getSynthesizedDeepClone(node, /*includeTrivia*/ + false); } function createBody(block, quotePreference2, ambient2) { - return ambient2 ? void 0 : getSynthesizedDeepClone( - block, - /*includeTrivia*/ - false - ) || createStubbedMethodBody(quotePreference2); + return ambient2 ? void 0 : getSynthesizedDeepClone(block, /*includeTrivia*/ + false) || createStubbedMethodBody(quotePreference2); } function createTypeNode(typeNode) { - return getSynthesizedDeepClone( - typeNode, - /*includeTrivia*/ - false - ); + return getSynthesizedDeepClone(typeNode, /*includeTrivia*/ + false); } function createDeclarationName(symbol2, declaration2) { if (getCheckFlags(symbol2) & 262144 /* Mapped */) { @@ -154580,11 +139108,8 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return factory.createIdentifier(unescapeLeadingUnderscores(getPropertyNameFromType(nameType))); } } - return getSynthesizedDeepClone( - getNameOfDeclaration(declaration2), - /*includeTrivia*/ - false - ); + return getSynthesizedDeepClone(getNameOfDeclaration(declaration2), /*includeTrivia*/ + false); } } function createSignatureDeclarationFromSignature(kind, context, quotePreference, signature, body, name, modifiers, optional, enclosingDeclaration, importAdder) { @@ -154602,7 +139127,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} let type = isJs ? void 0 : signatureDeclaration.type; if (importAdder) { if (typeParameters) { - const newTypeParameters = sameMap(typeParameters, (typeParameterDecl) => { + const newTypeParameters = sameMap(typeParameters, typeParameterDecl => { let constraint = typeParameterDecl.constraint; let defaultType = typeParameterDecl.default; if (constraint) { @@ -154619,19 +139144,13 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} importSymbols(importAdder, importableReference.symbols); } } - return factory.updateTypeParameterDeclaration( - typeParameterDecl, - typeParameterDecl.modifiers, - typeParameterDecl.name, - constraint, - defaultType - ); + return factory.updateTypeParameterDeclaration(typeParameterDecl, typeParameterDecl.modifiers, typeParameterDecl.name, constraint, defaultType); }); if (typeParameters !== newTypeParameters) { typeParameters = setTextRange(factory.createNodeArray(newTypeParameters, typeParameters.hasTrailingComma), typeParameters); } } - const newParameters = sameMap(parameters, (parameterDecl) => { + const newParameters = sameMap(parameters, parameterDecl => { let type2 = isJs ? void 0 : parameterDecl.type; if (type2) { const importableReference = tryGetAutoImportableReferenceFromTypeNode(type2, scriptTarget); @@ -154640,15 +139159,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} importSymbols(importAdder, importableReference.symbols); } } - return factory.updateParameterDeclaration( - parameterDecl, - parameterDecl.modifiers, - parameterDecl.dotDotDotToken, - parameterDecl.name, - isJs ? void 0 : parameterDecl.questionToken, - type2, - parameterDecl.initializer - ); + return factory.updateParameterDeclaration(parameterDecl, parameterDecl.modifiers, parameterDecl.dotDotDotToken, parameterDecl.name, isJs ? void 0 : parameterDecl.questionToken, type2, parameterDecl.initializer); }); if (parameters !== newParameters) { parameters = setTextRange(factory.createNodeArray(newParameters, parameters.hasTrailingComma), parameters); @@ -154664,16 +139175,16 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} const questionToken = optional ? factory.createToken(58 /* QuestionToken */) : void 0; const asteriskToken = signatureDeclaration.asteriskToken; if (isFunctionExpression(signatureDeclaration)) { - return factory.updateFunctionExpression(signatureDeclaration, modifiers, signatureDeclaration.asteriskToken, tryCast(name, isIdentifier), typeParameters, parameters, type, body ?? signatureDeclaration.body); + return factory.updateFunctionExpression(signatureDeclaration, modifiers, signatureDeclaration.asteriskToken, tryCast(name, isIdentifier), typeParameters, parameters, type, body !== null && body !== void 0 ? body : signatureDeclaration.body); } if (isArrowFunction(signatureDeclaration)) { - return factory.updateArrowFunction(signatureDeclaration, modifiers, typeParameters, parameters, type, signatureDeclaration.equalsGreaterThanToken, body ?? signatureDeclaration.body); + return factory.updateArrowFunction(signatureDeclaration, modifiers, typeParameters, parameters, type, signatureDeclaration.equalsGreaterThanToken, body !== null && body !== void 0 ? body : signatureDeclaration.body); } if (isMethodDeclaration(signatureDeclaration)) { - return factory.updateMethodDeclaration(signatureDeclaration, modifiers, asteriskToken, name ?? factory.createIdentifier(""), questionToken, typeParameters, parameters, type, body); + return factory.updateMethodDeclaration(signatureDeclaration, modifiers, asteriskToken, name !== null && name !== void 0 ? name : factory.createIdentifier(""), questionToken, typeParameters, parameters, type, body); } if (isFunctionDeclaration(signatureDeclaration)) { - return factory.updateFunctionDeclaration(signatureDeclaration, modifiers, signatureDeclaration.asteriskToken, tryCast(name, isIdentifier), typeParameters, parameters, type, body ?? signatureDeclaration.body); + return factory.updateFunctionDeclaration(signatureDeclaration, modifiers, signatureDeclaration.asteriskToken, tryCast(name, isIdentifier), typeParameters, parameters, type, body !== null && body !== void 0 ? body : signatureDeclaration.body); } return void 0; } @@ -154683,80 +139194,44 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} const tracker = getNoopSymbolTrackerWithResolver(context); const checker = context.program.getTypeChecker(); const isJs = isInJSFile(contextNode); - const { typeArguments, arguments: args, parent: parent2 } = call; + const { + typeArguments, + arguments: args, + parent: parent2 + } = call; const contextualType = isJs ? void 0 : checker.getContextualType(call); - const names = map(args, (arg) => isIdentifier(arg) ? arg.text : isPropertyAccessExpression(arg) && isIdentifier(arg.name) ? arg.name.text : void 0); - const instanceTypes = isJs ? [] : map(args, (arg) => checker.getTypeAtLocation(arg)); - const { argumentTypeNodes, argumentTypeParameters } = getArgumentTypesAndTypeParameters( - checker, - importAdder, - instanceTypes, - contextNode, - scriptTarget, - 1 /* NoTruncation */, - tracker - ); + const names = map(args, arg => isIdentifier(arg) ? arg.text : isPropertyAccessExpression(arg) && isIdentifier(arg.name) ? arg.name.text : void 0); + const instanceTypes = isJs ? [] : map(args, arg => checker.getTypeAtLocation(arg)); + const { + argumentTypeNodes, + argumentTypeParameters + } = getArgumentTypesAndTypeParameters(checker, importAdder, instanceTypes, contextNode, scriptTarget, 1 /* NoTruncation */, tracker); const modifiers = modifierFlags ? factory.createNodeArray(factory.createModifiersFromModifierFlags(modifierFlags)) : void 0; const asteriskToken = isYieldExpression(parent2) ? factory.createToken(42 /* AsteriskToken */) : void 0; const typeParameters = isJs ? void 0 : createTypeParametersForArguments(checker, argumentTypeParameters, typeArguments); - const parameters = createDummyParameters( - args.length, - names, - argumentTypeNodes, - /*minArgumentCount*/ - void 0, - isJs - ); - const type = isJs || contextualType === void 0 ? void 0 : checker.typeToTypeNode( - contextualType, - contextNode, - /*flags*/ - void 0, - tracker - ); + const parameters = createDummyParameters(args.length, names, argumentTypeNodes, /*minArgumentCount*/ + void 0, isJs); + const type = isJs || contextualType === void 0 ? void 0 : checker.typeToTypeNode(contextualType, contextNode, /*flags*/ + void 0, tracker); switch (kind) { case 174 /* MethodDeclaration */: - return factory.createMethodDeclaration( - modifiers, - asteriskToken, - name, - /*questionToken*/ - void 0, - typeParameters, - parameters, - type, - createStubbedMethodBody(quotePreference) - ); + return factory.createMethodDeclaration(modifiers, asteriskToken, name, /*questionToken*/ + void 0, typeParameters, parameters, type, createStubbedMethodBody(quotePreference)); case 173 /* MethodSignature */: - return factory.createMethodSignature( - modifiers, - name, - /*questionToken*/ - void 0, - typeParameters, - parameters, - type === void 0 ? factory.createKeywordTypeNode(159 /* UnknownKeyword */) : type - ); + return factory.createMethodSignature(modifiers, name, /*questionToken*/ + void 0, typeParameters, parameters, type === void 0 ? factory.createKeywordTypeNode(159 /* UnknownKeyword */) : type); case 262 /* FunctionDeclaration */: Debug.assert(typeof name === "string" || isIdentifier(name), "Unexpected name"); - return factory.createFunctionDeclaration( - modifiers, - asteriskToken, - name, - typeParameters, - parameters, - type, - createStubbedBody(Diagnostics.Function_not_implemented.message, quotePreference) - ); + return factory.createFunctionDeclaration(modifiers, asteriskToken, name, typeParameters, parameters, type, createStubbedBody(Diagnostics.Function_not_implemented.message, quotePreference)); default: Debug.fail("Unexpected kind"); } } function createTypeParametersForArguments(checker, argumentTypeParameters, typeArguments) { - const usedNames = new Set(argumentTypeParameters.map((pair) => pair[0])); + const usedNames = new Set(argumentTypeParameters.map(pair => pair[0])); const constraintsByName = new Map(argumentTypeParameters); if (typeArguments) { - const typeArgumentsWithNewTypes = typeArguments.filter((typeArgument) => !argumentTypeParameters.some((pair) => { + const typeArgumentsWithNewTypes = typeArguments.filter(typeArgument => !argumentTypeParameters.some(pair => { var _a; return checker.getTypeAtLocation(typeArgument) === ((_a = pair[1]) == null ? void 0 : _a.argumentType); })); @@ -154765,18 +139240,11 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} usedNames.add(createTypeParameterName(i)); } } - return arrayFrom( - usedNames.values(), - (usedName) => { - var _a; - return factory.createTypeParameterDeclaration( - /*modifiers*/ - void 0, - usedName, - (_a = constraintsByName.get(usedName)) == null ? void 0 : _a.constraint - ); - } - ); + return arrayFrom(usedNames.values(), usedName => { + var _a; + return factory.createTypeParameterDeclaration( /*modifiers*/ + void 0, usedName, (_a = constraintsByName.get(usedName)) == null ? void 0 : _a.constraint); + }); } function createTypeParameterName(index) { return 84 /* T */ + index <= 90 /* Z */ ? String.fromCharCode(84 /* T */ + index) : `T${index}`; @@ -154798,9 +139266,10 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } return type.flags & 262144 /* TypeParameter */; } + function getArgumentTypesAndTypeParameters(checker, importAdder, instanceTypes, contextNode, scriptTarget, flags, tracker) { const argumentTypeNodes = []; - const argumentTypeParameters = /* @__PURE__ */ new Map(); + const argumentTypeParameters = /* @__PURE__ */new Map(); for (let i = 0; i < instanceTypes.length; i += 1) { const instanceType = instanceTypes[i]; if (instanceType.isUnionOrIntersection() && instanceType.types.some(typeContainsTypeParameter)) { @@ -154818,14 +139287,21 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} const argumentTypeParameter = getFirstTypeParameterName(instanceType); const instanceTypeConstraint = instanceType.isTypeParameter() && instanceType.constraint && !isAnonymousObjectConstraintType(instanceType.constraint) ? typeToAutoImportableTypeNode(checker, importAdder, instanceType.constraint, contextNode, scriptTarget, flags, tracker) : void 0; if (argumentTypeParameter) { - argumentTypeParameters.set(argumentTypeParameter, { argumentType: instanceType, constraint: instanceTypeConstraint }); + argumentTypeParameters.set(argumentTypeParameter, { + argumentType: instanceType, + constraint: instanceTypeConstraint + }); } } - return { argumentTypeNodes, argumentTypeParameters: arrayFrom(argumentTypeParameters.entries()) }; + return { + argumentTypeNodes, + argumentTypeParameters: arrayFrom(argumentTypeParameters.entries()) + }; } function isAnonymousObjectConstraintType(type) { return type.flags & 524288 /* Object */ && type.objectFlags === 16 /* Anonymous */; } + function getFirstTypeParameterName(type) { var _a; if (type.flags & (1048576 /* Union */ | 2097152 /* Intersection */)) { @@ -154840,25 +139316,18 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } function createDummyParameters(argCount, names, types, minArgumentCount, inJs) { const parameters = []; - const parameterNameCounts = /* @__PURE__ */ new Map(); + const parameterNameCounts = /* @__PURE__ */new Map(); for (let i = 0; i < argCount; i++) { const parameterName = (names == null ? void 0 : names[i]) || `arg${i}`; const parameterNameCount = parameterNameCounts.get(parameterName); parameterNameCounts.set(parameterName, (parameterNameCount || 0) + 1); - const newParameter = factory.createParameterDeclaration( - /*modifiers*/ - void 0, - /*dotDotDotToken*/ - void 0, - /*name*/ - parameterName + (parameterNameCount || ""), - /*questionToken*/ - minArgumentCount !== void 0 && i >= minArgumentCount ? factory.createToken(58 /* QuestionToken */) : void 0, - /*type*/ - inJs ? void 0 : (types == null ? void 0 : types[i]) || factory.createKeywordTypeNode(159 /* UnknownKeyword */), - /*initializer*/ - void 0 - ); + const newParameter = factory.createParameterDeclaration( /*modifiers*/ + void 0, /*dotDotDotToken*/ + void 0, /*name*/ + parameterName + (parameterNameCount || ""), /*questionToken*/ + minArgumentCount !== void 0 && i >= minArgumentCount ? factory.createToken(58 /* QuestionToken */) : void 0, /*type*/ + inJs ? void 0 : (types == null ? void 0 : types[i]) || factory.createKeywordTypeNode(159 /* UnknownKeyword */), /*initializer*/ + void 0); parameters.push(newParameter); } return parameters; @@ -154877,41 +139346,19 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } } const maxNonRestArgs = maxArgsSignature.parameters.length - (signatureHasRestParameter(maxArgsSignature) ? 1 : 0); - const maxArgsParameterSymbolNames = maxArgsSignature.parameters.map((symbol) => symbol.name); - const parameters = createDummyParameters( - maxNonRestArgs, - maxArgsParameterSymbolNames, - /*types*/ - void 0, - minArgumentCount, - /*inJs*/ - false - ); + const maxArgsParameterSymbolNames = maxArgsSignature.parameters.map(symbol => symbol.name); + const parameters = createDummyParameters(maxNonRestArgs, maxArgsParameterSymbolNames, /*types*/ + void 0, minArgumentCount, /*inJs*/ + false); if (someSigHasRestParameter) { - const restParameter = factory.createParameterDeclaration( - /*modifiers*/ - void 0, - factory.createToken(26 /* DotDotDotToken */), - maxArgsParameterSymbolNames[maxNonRestArgs] || "rest", - /*questionToken*/ - maxNonRestArgs >= minArgumentCount ? factory.createToken(58 /* QuestionToken */) : void 0, - factory.createArrayTypeNode(factory.createKeywordTypeNode(159 /* UnknownKeyword */)), - /*initializer*/ - void 0 - ); + const restParameter = factory.createParameterDeclaration( /*modifiers*/ + void 0, factory.createToken(26 /* DotDotDotToken */), maxArgsParameterSymbolNames[maxNonRestArgs] || "rest", /*questionToken*/ + maxNonRestArgs >= minArgumentCount ? factory.createToken(58 /* QuestionToken */) : void 0, factory.createArrayTypeNode(factory.createKeywordTypeNode(159 /* UnknownKeyword */)), /*initializer*/ + void 0); parameters.push(restParameter); } - return createStubbedMethod( - modifiers, - name, - optional, - /*typeParameters*/ - void 0, - parameters, - getReturnTypeFromSignatures(signatures, checker, context, enclosingDeclaration), - quotePreference, - body - ); + return createStubbedMethod(modifiers, name, optional, /*typeParameters*/ + void 0, parameters, getReturnTypeFromSignatures(signatures, checker, context, enclosingDeclaration), quotePreference, body); } function getReturnTypeFromSignatures(signatures, checker, context, enclosingDeclaration) { if (length(signatures)) { @@ -154920,58 +139367,27 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } } function createStubbedMethod(modifiers, name, optional, typeParameters, parameters, returnType, quotePreference, body) { - return factory.createMethodDeclaration( - modifiers, - /*asteriskToken*/ - void 0, - name, - optional ? factory.createToken(58 /* QuestionToken */) : void 0, - typeParameters, - parameters, - returnType, - body || createStubbedMethodBody(quotePreference) - ); + return factory.createMethodDeclaration(modifiers, /*asteriskToken*/ + void 0, name, optional ? factory.createToken(58 /* QuestionToken */) : void 0, typeParameters, parameters, returnType, body || createStubbedMethodBody(quotePreference)); } function createStubbedMethodBody(quotePreference) { return createStubbedBody(Diagnostics.Method_not_implemented.message, quotePreference); } function createStubbedBody(text, quotePreference) { - return factory.createBlock( - [factory.createThrowStatement( - factory.createNewExpression( - factory.createIdentifier("Error"), - /*typeArguments*/ - void 0, - // TODO Handle auto quote preference. - [factory.createStringLiteral( - text, - /*isSingleQuote*/ - quotePreference === 0 /* Single */ - )] - ) - )], - /*multiLine*/ - true - ); + return factory.createBlock([factory.createThrowStatement(factory.createNewExpression(factory.createIdentifier("Error"), /*typeArguments*/ + void 0, + // TODO Handle auto quote preference. + [factory.createStringLiteral(text, /*isSingleQuote*/ + quotePreference === 0 /* Single */)]))], /*multiLine*/ + true); } function setJsonCompilerOptionValues(changeTracker, configFile, options) { const tsconfigObjectLiteral = getTsConfigObjectLiteralExpression(configFile); - if (!tsconfigObjectLiteral) - return void 0; + if (!tsconfigObjectLiteral) return void 0; const compilerOptionsProperty = findJsonProperty(tsconfigObjectLiteral, "compilerOptions"); if (compilerOptionsProperty === void 0) { - changeTracker.insertNodeAtObjectStart( - configFile, - tsconfigObjectLiteral, - createJsonPropertyAssignment( - "compilerOptions", - factory.createObjectLiteralExpression( - options.map(([optionName, optionValue]) => createJsonPropertyAssignment(optionName, optionValue)), - /*multiLine*/ - true - ) - ) - ); + changeTracker.insertNodeAtObjectStart(configFile, tsconfigObjectLiteral, createJsonPropertyAssignment("compilerOptions", factory.createObjectLiteralExpression(options.map(([optionName, optionValue]) => createJsonPropertyAssignment(optionName, optionValue)), /*multiLine*/ + true))); return; } const compilerOptions = compilerOptionsProperty.initializer; @@ -154994,13 +139410,16 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return factory.createPropertyAssignment(factory.createStringLiteral(name), initializer); } function findJsonProperty(obj, name) { - return find(obj.properties, (p) => isPropertyAssignment(p) && !!p.name && isStringLiteral(p.name) && p.name.text === name); + return find(obj.properties, p => isPropertyAssignment(p) && !!p.name && isStringLiteral(p.name) && p.name.text === name); } function tryGetAutoImportableReferenceFromTypeNode(importTypeNode, scriptTarget) { let symbols; const typeNode = visitNode(importTypeNode, visit, isTypeNode); if (symbols && typeNode) { - return { typeNode, symbols }; + return { + typeNode, + symbols + }; } function visit(node) { if (isLiteralImportTypeNode(node) && node.qualifier) { @@ -155021,11 +139440,8 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return factory.createQualifiedName(replaceFirstIdentifierOfEntityName(name.left, newIdentifier), name.right); } function importSymbols(importAdder, symbols) { - symbols.forEach((s) => importAdder.addImportFromExportedSymbol( - s, - /*isValidTypeOnlyUseSite*/ - true - )); + symbols.forEach(s => importAdder.addImportFromExportedSymbol(s, /*isValidTypeOnlyUseSite*/ + true)); } function findAncestorMatchingSpan(sourceFile, span) { const end = textSpanEnd(span); @@ -155039,8 +139455,9 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} var init_helpers2 = __esm({ "src/services/codefixes/helpers.ts"() { "use strict"; + init_ts4(); - PreserveOptionalFlags = /* @__PURE__ */ ((PreserveOptionalFlags2) => { + PreserveOptionalFlags = /* @__PURE__ */(PreserveOptionalFlags2 => { PreserveOptionalFlags2[PreserveOptionalFlags2["Method"] = 1] = "Method"; PreserveOptionalFlags2[PreserveOptionalFlags2["Property"] = 2] = "Property"; PreserveOptionalFlags2[PreserveOptionalFlags2["All"] = 3] = "All"; @@ -155052,10 +139469,18 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} // 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; + const { + isStatic: isStatic2, + isReadonly, + fieldName, + accessorName, + originalName, + type, + container, + declaration + } = fieldInfo; suppressLeadingAndTrailingTrivia(fieldName); suppressLeadingAndTrailingTrivia(accessorName); suppressLeadingAndTrailingTrivia(declaration); @@ -155111,6 +139536,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (!(modifierFlags & 4 /* Protected */)) { modifierFlags |= 1 /* Public */; } + return modifierFlags; } function prepareModifierFlagsForField(modifierFlags) { @@ -155156,66 +139582,24 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} }; } function generateGetAccessor(fieldName, accessorName, type, modifiers, isStatic2, container) { - return factory.createGetAccessorDeclaration( - modifiers, - accessorName, - [], - type, - factory.createBlock( - [ - factory.createReturnStatement( - createAccessorAccessExpression(fieldName, isStatic2, container) - ) - ], - /*multiLine*/ - true - ) - ); + return factory.createGetAccessorDeclaration(modifiers, accessorName, [], type, factory.createBlock([factory.createReturnStatement(createAccessorAccessExpression(fieldName, isStatic2, container))], /*multiLine*/ + true)); } function generateSetAccessor(fieldName, accessorName, type, modifiers, isStatic2, container) { - return factory.createSetAccessorDeclaration( - modifiers, - accessorName, - [factory.createParameterDeclaration( - /*modifiers*/ - void 0, - /*dotDotDotToken*/ - void 0, - factory.createIdentifier("value"), - /*questionToken*/ - void 0, - type - )], - factory.createBlock( - [ - factory.createExpressionStatement( - factory.createAssignment( - createAccessorAccessExpression(fieldName, isStatic2, container), - factory.createIdentifier("value") - ) - ) - ], - /*multiLine*/ - true - ) - ); + return factory.createSetAccessorDeclaration(modifiers, accessorName, [factory.createParameterDeclaration( /*modifiers*/ + void 0, /*dotDotDotToken*/ + void 0, factory.createIdentifier("value"), /*questionToken*/ + void 0, type)], factory.createBlock([factory.createExpressionStatement(factory.createAssignment(createAccessorAccessExpression(fieldName, isStatic2, container), factory.createIdentifier("value")))], /*multiLine*/ + true)); } function updatePropertyDeclaration(changeTracker, file, declaration, type, fieldName, modifiers) { - const property = factory.updatePropertyDeclaration( - declaration, - modifiers, - fieldName, - declaration.questionToken || declaration.exclamationToken, - type, - declaration.initializer - ); + const property = factory.updatePropertyDeclaration(declaration, modifiers, fieldName, declaration.questionToken || declaration.exclamationToken, type, declaration.initializer); changeTracker.replaceNode(file, declaration, property); } function updatePropertyAssignmentDeclaration(changeTracker, file, declaration, fieldName) { let assignment = factory.updatePropertyAssignment(declaration, fieldName, declaration.initializer); if (assignment.modifiers || assignment.questionToken || assignment.exclamationToken) { - if (assignment === declaration) - assignment = factory.cloneNode(assignment); + if (assignment === declaration) assignment = factory.cloneNode(assignment); assignment.modifiers = void 0; assignment.questionToken = void 0; assignment.exclamationToken = void 0; @@ -155235,8 +139619,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} 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)); @@ -155259,6 +139642,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return factory.createUnionTypeNode([...types, factory.createKeywordTypeNode(157 /* UndefinedKeyword */)]); } } + return typeNode; } function getAllSupers(decl, checker) { @@ -155266,12 +139650,10 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} 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; } @@ -155280,6 +139662,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} var init_generateAccessors = __esm({ "src/services/codefixes/generateAccessors.ts"() { "use strict"; + init_ts4(); } }); @@ -155290,38 +139673,23 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} const namespace = getNamespaceDeclarationNode(node); const opts = context.program.getCompilerOptions(); const variations = []; - variations.push(createAction(context, sourceFile, node, makeImport( - namespace.name, - /*namedImports*/ - void 0, - node.moduleSpecifier, - getQuotePreference(sourceFile, context.preferences) - ))); + variations.push(createAction(context, sourceFile, node, makeImport(namespace.name, /*namedImports*/ + void 0, node.moduleSpecifier, getQuotePreference(sourceFile, context.preferences)))); if (getEmitModuleKind(opts) === 1 /* CommonJS */) { - variations.push(createAction( - context, - sourceFile, - node, - factory.createImportEqualsDeclaration( - /*modifiers*/ - void 0, - /*isTypeOnly*/ - false, - namespace.name, - factory.createExternalModuleReference(node.moduleSpecifier) - ) - )); + variations.push(createAction(context, sourceFile, node, factory.createImportEqualsDeclaration( /*modifiers*/ + void 0, /*isTypeOnly*/ + false, namespace.name, factory.createExternalModuleReference(node.moduleSpecifier)))); } return variations; } function createAction(context, sourceFile, node, replacement) { - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => t.replaceNode(sourceFile, node, replacement)); + const changes = ts_textChanges_exports.ChangeTracker.with(context, t => t.replaceNode(sourceFile, node, replacement)); return createCodeFixActionWithoutFixAll(fixName5, changes, [Diagnostics.Replace_import_with_0, changes[0].textChanges[0].newText]); } function getActionsForUsageOfInvalidImport(context) { const sourceFile = context.sourceFile; const targetKind = Diagnostics.This_expression_is_not_callable.code === context.errorCode ? 213 /* CallExpression */ : 214 /* NewExpression */; - const node = findAncestor(getTokenAtPosition(sourceFile, context.span.start), (a) => a.kind === targetKind); + const node = findAncestor(getTokenAtPosition(sourceFile, context.span.start), a => a.kind === targetKind); if (!node) { return []; } @@ -155330,7 +139698,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } function getActionsForInvalidImportLocation(context) { const sourceFile = context.sourceFile; - const node = findAncestor(getTokenAtPosition(sourceFile, context.span.start), (a) => a.getStart() === context.span.start && a.getEnd() === context.span.start + context.span.length); + const node = findAncestor(getTokenAtPosition(sourceFile, context.span.start), a => a.getStart() === context.span.start && a.getEnd() === context.span.start + context.span.length); if (!node) { return []; } @@ -155348,7 +139716,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } if (isExpression(expr) && !(isNamedDeclaration(expr.parent) && expr.parent.name === expr)) { const sourceFile = context.sourceFile; - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => t.replaceNode(sourceFile, expr, factory.createPropertyAccessExpression(expr, "default"), {})); + const changes = ts_textChanges_exports.ChangeTracker.with(context, t => t.replaceNode(sourceFile, expr, factory.createPropertyAccessExpression(expr, "default"), {})); fixes.push(createCodeFixActionWithoutFixAll(fixName5, changes, Diagnostics.Use_synthetic_default_member)); } return fixes; @@ -155357,31 +139725,18 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} var init_fixInvalidImportSyntax = __esm({ "src/services/codefixes/fixInvalidImportSyntax.ts"() { "use strict"; + init_ts4(); init_ts_codefix(); fixName5 = "invalidImportSyntax"; registerCodeFix({ - errorCodes: [ - Diagnostics.This_expression_is_not_callable.code, - Diagnostics.This_expression_is_not_constructable.code - ], + errorCodes: [Diagnostics.This_expression_is_not_callable.code, Diagnostics.This_expression_is_not_constructable.code], getCodeActions: getActionsForUsageOfInvalidImport }); registerCodeFix({ errorCodes: [ - // The following error codes cover pretty much all assignability errors that could involve an expression - Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1.code, - Diagnostics.Type_0_does_not_satisfy_the_constraint_1.code, - Diagnostics.Type_0_is_not_assignable_to_type_1.code, - Diagnostics.Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated.code, - Diagnostics.Type_predicate_0_is_not_assignable_to_1.code, - Diagnostics.Property_0_of_type_1_is_not_assignable_to_2_index_type_3.code, - Diagnostics._0_index_type_1_is_not_assignable_to_2_index_type_3.code, - Diagnostics.Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2.code, - Diagnostics.Property_0_in_type_1_is_not_assignable_to_type_2.code, - Diagnostics.Property_0_of_JSX_spread_attribute_is_not_assignable_to_target_property.code, - Diagnostics.The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1.code - ], + // The following error codes cover pretty much all assignability errors that could involve an expression + Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1.code, Diagnostics.Type_0_does_not_satisfy_the_constraint_1.code, Diagnostics.Type_0_is_not_assignable_to_type_1.code, Diagnostics.Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated.code, Diagnostics.Type_predicate_0_is_not_assignable_to_1.code, Diagnostics.Property_0_of_type_1_is_not_assignable_to_2_index_type_3.code, Diagnostics._0_index_type_1_is_not_assignable_to_2_index_type_3.code, Diagnostics.Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2.code, Diagnostics.Property_0_in_type_1_is_not_assignable_to_type_2.code, Diagnostics.Property_0_of_JSX_spread_attribute_is_not_assignable_to_target_property.code, Diagnostics.The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1.code], getCodeActions: getActionsForInvalidImportLocation }); } @@ -155393,31 +139748,27 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (isIdentifier(token) && isPropertyDeclaration(token.parent)) { const type = getEffectiveTypeAnnotationNode(token.parent); if (type) { - return { type, prop: token.parent, isJs: isInJSFile(token.parent) }; + return { + type, + prop: token.parent, + isJs: isInJSFile(token.parent) + }; } } return void 0; } function getActionForAddMissingDefiniteAssignmentAssertion(context, info) { - if (info.isJs) - return void 0; - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => addDefiniteAssignmentAssertion(t, context.sourceFile, info.prop)); + if (info.isJs) return void 0; + const changes = ts_textChanges_exports.ChangeTracker.with(context, t => addDefiniteAssignmentAssertion(t, context.sourceFile, info.prop)); return createCodeFixAction(fixName6, changes, [Diagnostics.Add_definite_assignment_assertion_to_property_0, info.prop.getText()], fixIdAddDefiniteAssignmentAssertions, Diagnostics.Add_definite_assignment_assertions_to_all_uninitialized_properties); } function addDefiniteAssignmentAssertion(changeTracker, propertyDeclarationSourceFile, propertyDeclaration) { suppressLeadingAndTrailingTrivia(propertyDeclaration); - const property = factory.updatePropertyDeclaration( - propertyDeclaration, - propertyDeclaration.modifiers, - propertyDeclaration.name, - factory.createToken(54 /* ExclamationToken */), - propertyDeclaration.type, - propertyDeclaration.initializer - ); + const property = factory.updatePropertyDeclaration(propertyDeclaration, propertyDeclaration.modifiers, propertyDeclaration.name, factory.createToken(54 /* ExclamationToken */), propertyDeclaration.type, propertyDeclaration.initializer); changeTracker.replaceNode(propertyDeclarationSourceFile, propertyDeclaration, property); } function getActionForAddMissingUndefinedType(context, info) { - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => addUndefinedType(t, context.sourceFile, info)); + const changes = ts_textChanges_exports.ChangeTracker.with(context, t => addUndefinedType(t, context.sourceFile, info)); return createCodeFixAction(fixName6, changes, [Diagnostics.Add_undefined_type_to_property_0, info.prop.name.getText()], fixIdAddUndefinedType, Diagnostics.Add_undefined_type_to_all_uninitialized_properties); } function addUndefinedType(changeTracker, sourceFile, info) { @@ -155425,35 +139776,23 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} const types = isUnionTypeNode(info.type) ? info.type.types.concat(undefinedTypeNode) : [info.type, undefinedTypeNode]; const unionTypeNode = factory.createUnionTypeNode(types); if (info.isJs) { - changeTracker.addJSDocTags(sourceFile, info.prop, [factory.createJSDocTypeTag( - /*tagName*/ - void 0, - factory.createJSDocTypeExpression(unionTypeNode) - )]); + changeTracker.addJSDocTags(sourceFile, info.prop, [factory.createJSDocTypeTag( /*tagName*/ + void 0, factory.createJSDocTypeExpression(unionTypeNode))]); } else { changeTracker.replaceNode(sourceFile, info.type, unionTypeNode); } } function getActionForAddMissingInitializer(context, info) { - if (info.isJs) - return void 0; + if (info.isJs) return void 0; const checker = context.program.getTypeChecker(); const initializer = getInitializer(checker, info.prop); - if (!initializer) - return void 0; - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => addInitializer(t, context.sourceFile, info.prop, initializer)); + if (!initializer) return void 0; + const changes = ts_textChanges_exports.ChangeTracker.with(context, t => addInitializer(t, context.sourceFile, info.prop, initializer)); return createCodeFixAction(fixName6, changes, [Diagnostics.Add_initializer_to_property_0, info.prop.name.getText()], fixIdAddInitializer, Diagnostics.Add_initializers_to_all_uninitialized_properties); } function addInitializer(changeTracker, propertyDeclarationSourceFile, propertyDeclaration, initializer) { suppressLeadingAndTrailingTrivia(propertyDeclaration); - const property = factory.updatePropertyDeclaration( - propertyDeclaration, - propertyDeclaration.modifiers, - propertyDeclaration.name, - propertyDeclaration.questionToken, - propertyDeclaration.type, - initializer - ); + const property = factory.updatePropertyDeclaration(propertyDeclaration, propertyDeclaration.modifiers, propertyDeclaration.name, propertyDeclaration.questionToken, propertyDeclaration.type, initializer); changeTracker.replaceNode(propertyDeclarationSourceFile, propertyDeclaration, property); } function getInitializer(checker, propertyDeclaration) { @@ -155461,10 +139800,8 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } function getDefaultValueFromType(checker, type) { if (type.flags & 512 /* BooleanLiteral */) { - return type === checker.getFalseType() || type === checker.getFalseType( - /*fresh*/ - true - ) ? factory.createFalse() : factory.createTrue(); + return type === checker.getFalseType() || type === checker.getFalseType( /*fresh*/ + true) ? factory.createFalse() : factory.createTrue(); } else if (type.isStringLiteral()) { return factory.createStringLiteral(type.value); } else if (type.isNumberLiteral()) { @@ -155472,21 +139809,15 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } else if (type.flags & 2048 /* BigIntLiteral */) { return factory.createBigIntLiteral(type.value); } else if (type.isUnion()) { - return firstDefined(type.types, (t) => getDefaultValueFromType(checker, t)); + 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; - return factory.createNewExpression( - factory.createIdentifier(type.symbol.name), - /*typeArguments*/ - void 0, - /*argumentsArray*/ - void 0 - ); + if (constructorDeclaration && constructorDeclaration.parameters.length) return void 0; + return factory.createNewExpression(factory.createIdentifier(type.symbol.name), /*typeArguments*/ + void 0, /*argumentsArray*/ + void 0); } else if (checker.isArrayLikeType(type)) { return factory.createArrayLiteralExpression(); } @@ -155496,6 +139827,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} var init_fixStrictClassInitialization = __esm({ "src/services/codefixes/fixStrictClassInitialization.ts"() { "use strict"; + init_ts4(); init_ts_codefix(); fixName6 = "strictClassInitialization"; @@ -155507,8 +139839,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} errorCodes: errorCodes51, getCodeActions: function getCodeActionsForStrictClassInitializationErrors(context) { const info = getInfo16(context.sourceFile, context.span.start); - if (!info) - return; + if (!info) return; const result = []; append(result, getActionForAddMissingUndefinedType(context, info)); append(result, getActionForAddMissingDefiniteAssignmentAssertion(context, info)); @@ -155516,11 +139847,10 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return result; }, fixIds: [fixIdAddDefiniteAssignmentAssertions, fixIdAddUndefinedType, fixIdAddInitializer], - getAllCodeActions: (context) => { + getAllCodeActions: context => { return codeFixAll(context, errorCodes51, (changes, diag2) => { const info = getInfo16(diag2.file, diag2.start); - if (!info) - return; + if (!info) return; switch (context.fixId) { case fixIdAddDefiniteAssignmentAssertions: addDefiniteAssignmentAssertion(changes, diag2.file, info.prop); @@ -155531,8 +139861,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} 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: @@ -155546,39 +139875,26 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} // src/services/codefixes/requireInTs.ts function doChange34(changes, sourceFile, info) { - const { allowSyntheticDefaults, defaultImportName, namedImports, statement, required } = info; - changes.replaceNode( - sourceFile, + const { + allowSyntheticDefaults, + defaultImportName, + namedImports, statement, - defaultImportName && !allowSyntheticDefaults ? factory.createImportEqualsDeclaration( - /*modifiers*/ - void 0, - /*isTypeOnly*/ - false, - defaultImportName, - factory.createExternalModuleReference(required) - ) : factory.createImportDeclaration( - /*modifiers*/ - void 0, - factory.createImportClause( - /*isTypeOnly*/ - false, - defaultImportName, - namedImports - ), - required, - /*attributes*/ - void 0 - ) - ); + required + } = info; + changes.replaceNode(sourceFile, statement, defaultImportName && !allowSyntheticDefaults ? factory.createImportEqualsDeclaration( /*modifiers*/ + void 0, /*isTypeOnly*/ + false, defaultImportName, factory.createExternalModuleReference(required)) : factory.createImportDeclaration( /*modifiers*/ + void 0, factory.createImportClause( /*isTypeOnly*/ + false, defaultImportName, namedImports), required, /*attributes*/ + void 0)); } function getInfo17(sourceFile, program, pos) { - const { parent: parent2 } = getTokenAtPosition(sourceFile, pos); - if (!isRequireCall( - parent2, - /*requireStringLiteralLikeArgument*/ - true - )) { + const { + parent: parent2 + } = getTokenAtPosition(sourceFile, pos); + if (!isRequireCall(parent2, /*requireStringLiteralLikeArgument*/ + true)) { Debug.failBadSyntaxKind(parent2); } const decl = cast(parent2.parent, isVariableDeclaration); @@ -155600,12 +139916,8 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (!isIdentifier(element.name) || element.initializer) { return void 0; } - importSpecifiers.push(factory.createImportSpecifier( - /*isTypeOnly*/ - false, - tryCast(element.propertyName, isIdentifier), - element.name - )); + importSpecifiers.push(factory.createImportSpecifier( /*isTypeOnly*/ + false, tryCast(element.propertyName, isIdentifier), element.name)); } if (importSpecifiers.length) { return factory.createNamedImports(importSpecifiers); @@ -155615,6 +139927,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} var init_requireInTs = __esm({ "src/services/codefixes/requireInTs.ts"() { "use strict"; + init_ts4(); init_ts_codefix(); fixId41 = "requireInTs"; @@ -155626,11 +139939,11 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (!info) { return void 0; } - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange34(t, context.sourceFile, info)); + const changes = ts_textChanges_exports.ChangeTracker.with(context, t => doChange34(t, context.sourceFile, info)); return [createCodeFixAction(fixId41, changes, Diagnostics.Convert_require_to_import, fixId41, Diagnostics.Convert_all_require_to_import)]; }, fixIds: [fixId41], - getAllCodeActions: (context) => codeFixAll(context, errorCodes52, (changes, diag2) => { + getAllCodeActions: context => codeFixAll(context, errorCodes52, (changes, diag2) => { const info = getInfo17(diag2.file, context.program, diag2.start); if (info) { doChange34(changes, context.sourceFile, info); @@ -155643,29 +139956,34 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} // src/services/codefixes/useDefaultImport.ts function getInfo18(sourceFile, pos) { const name = getTokenAtPosition(sourceFile, pos); - if (!isIdentifier(name)) - return void 0; - const { parent: parent2 } = name; + if (!isIdentifier(name)) return void 0; + const { + parent: parent2 + } = name; if (isImportEqualsDeclaration(parent2) && isExternalModuleReference(parent2.moduleReference)) { - return { importNode: parent2, name, moduleSpecifier: parent2.moduleReference.expression }; + return { + importNode: parent2, + name, + moduleSpecifier: parent2.moduleReference.expression + }; } else if (isNamespaceImport(parent2)) { const importNode = parent2.parent.parent; - return { importNode, name, moduleSpecifier: importNode.moduleSpecifier }; + return { + importNode, + name, + moduleSpecifier: importNode.moduleSpecifier + }; } } function doChange35(changes, sourceFile, info, preferences) { - changes.replaceNode(sourceFile, info.importNode, makeImport( - info.name, - /*namedImports*/ - void 0, - info.moduleSpecifier, - getQuotePreference(sourceFile, preferences) - )); + changes.replaceNode(sourceFile, info.importNode, makeImport(info.name, /*namedImports*/ + void 0, info.moduleSpecifier, getQuotePreference(sourceFile, preferences))); } var fixId42, errorCodes53; var init_useDefaultImport = __esm({ "src/services/codefixes/useDefaultImport.ts"() { "use strict"; + init_ts4(); init_ts_codefix(); fixId42 = "useDefaultImport"; @@ -155673,18 +139991,21 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} registerCodeFix({ errorCodes: errorCodes53, getCodeActions(context) { - const { sourceFile, span: { start } } = context; + const { + sourceFile, + span: { + start + } + } = context; const info = getInfo18(sourceFile, start); - if (!info) - return void 0; - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange35(t, sourceFile, info, context.preferences)); + if (!info) return void 0; + const changes = ts_textChanges_exports.ChangeTracker.with(context, t => doChange35(t, sourceFile, info, context.preferences)); return [createCodeFixAction(fixId42, changes, Diagnostics.Convert_to_default_import, fixId42, Diagnostics.Convert_all_to_default_imports)]; }, fixIds: [fixId42], - getAllCodeActions: (context) => codeFixAll(context, errorCodes53, (changes, diag2) => { + getAllCodeActions: context => codeFixAll(context, errorCodes53, (changes, diag2) => { const info = getInfo18(diag2.file, diag2.start); - if (info) - doChange35(changes, diag2.file, info, context.preferences); + if (info) doChange35(changes, diag2.file, info, context.preferences); }) }); } @@ -155703,22 +140024,21 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} var init_useBigintLiteral = __esm({ "src/services/codefixes/useBigintLiteral.ts"() { "use strict"; + init_ts4(); init_ts_codefix(); fixId43 = "useBigintLiteral"; - errorCodes54 = [ - Diagnostics.Numeric_literals_with_absolute_values_equal_to_2_53_or_greater_are_too_large_to_be_represented_accurately_as_integers.code - ]; + errorCodes54 = [Diagnostics.Numeric_literals_with_absolute_values_equal_to_2_53_or_greater_are_too_large_to_be_represented_accurately_as_integers.code]; registerCodeFix({ errorCodes: errorCodes54, getCodeActions: function getCodeActionsToUseBigintLiteral(context) { - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => makeChange9(t, context.sourceFile, context.span)); + const changes = ts_textChanges_exports.ChangeTracker.with(context, t => makeChange9(t, context.sourceFile, context.span)); if (changes.length > 0) { return [createCodeFixAction(fixId43, changes, Diagnostics.Convert_to_a_bigint_numeric_literal, fixId43, Diagnostics.Convert_all_to_bigint_numeric_literals)]; } }, fixIds: [fixId43], - getAllCodeActions: (context) => { + getAllCodeActions: context => { return codeFixAll(context, errorCodes54, (changes, diag2) => makeChange9(changes, diag2.file, diag2)); } }); @@ -155733,21 +140053,15 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return token.parent; } function doChange36(changes, sourceFile, importType) { - const newTypeNode = factory.updateImportTypeNode( - importType, - importType.argument, - importType.attributes, - importType.qualifier, - importType.typeArguments, - /*isTypeOf*/ - true - ); + const newTypeNode = factory.updateImportTypeNode(importType, importType.argument, importType.attributes, importType.qualifier, importType.typeArguments, /*isTypeOf*/ + true); changes.replaceNode(sourceFile, importType, newTypeNode); } var fixIdAddMissingTypeof, fixId44, errorCodes55; var init_fixAddModuleReferTypeMissingTypeof = __esm({ "src/services/codefixes/fixAddModuleReferTypeMissingTypeof.ts"() { "use strict"; + init_ts4(); init_ts_codefix(); fixIdAddMissingTypeof = "fixAddModuleReferTypeMissingTypeof"; @@ -155756,13 +140070,16 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} registerCodeFix({ errorCodes: errorCodes55, getCodeActions: function getCodeActionsToAddMissingTypeof(context) { - const { sourceFile, span } = context; + const { + sourceFile, + span + } = context; const importType = getImportTypeNode(sourceFile, span.start); - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange36(t, sourceFile, importType)); + const changes = ts_textChanges_exports.ChangeTracker.with(context, t => doChange36(t, sourceFile, importType)); return [createCodeFixAction(fixId44, changes, Diagnostics.Add_missing_typeof, fixId44, Diagnostics.Add_missing_typeof)]; }, fixIds: [fixId44], - getAllCodeActions: (context) => codeFixAll(context, errorCodes55, (changes, diag2) => doChange36(changes, context.sourceFile, getImportTypeNode(diag2.file, diag2.start))) + getAllCodeActions: context => codeFixAll(context, errorCodes55, (changes, diag2) => doChange36(changes, context.sourceFile, getImportTypeNode(diag2.file, diag2.start))) }); } }); @@ -155774,17 +140091,14 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} 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 doChange37(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 = []; @@ -155798,16 +140112,15 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } 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; } } var fixID2, errorCodes56; var init_wrapJsxInFragment = __esm({ "src/services/codefixes/wrapJsxInFragment.ts"() { "use strict"; + init_ts4(); init_ts_codefix(); fixID2 = "wrapJsxInFragment"; @@ -155815,18 +140128,19 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} registerCodeFix({ errorCodes: errorCodes56, getCodeActions: function getCodeActionsToWrapJsxInFragment(context) { - const { sourceFile, span } = context; + const { + sourceFile, + span + } = context; const node = findNodeToFix(sourceFile, span.start); - if (!node) - return void 0; - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange37(t, sourceFile, node)); + if (!node) return void 0; + const changes = ts_textChanges_exports.ChangeTracker.with(context, t => doChange37(t, sourceFile, node)); return [createCodeFixAction(fixID2, changes, Diagnostics.Wrap_in_JSX_fragment, fixID2, Diagnostics.Wrap_all_unparented_JSX_in_JSX_fragment)]; }, fixIds: [fixID2], - getAllCodeActions: (context) => codeFixAll(context, errorCodes56, (changes, diag2) => { + getAllCodeActions: context => codeFixAll(context, errorCodes56, (changes, diag2) => { const node = findNodeToFix(context.sourceFile, diag2.start); - if (!node) - return void 0; + if (!node) return void 0; doChange37(changes, context.sourceFile, node); }) }); @@ -155837,47 +140151,37 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} function getInfo19(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; - return { indexSignature, container }; + if (!container) return void 0; + return { + indexSignature, + container + }; } function createTypeAliasFromInterface(declaration, type) { return factory.createTypeAliasDeclaration(declaration.modifiers, declaration.name, declaration.typeParameters, type); } - function doChange38(changes, sourceFile, { indexSignature, container }) { + function doChange38(changes, sourceFile, { + indexSignature, + container + }) { const members = isInterfaceDeclaration(container) ? container.members : container.type.members; - const otherMembers = members.filter((member) => !isIndexSignatureDeclaration(member)); + const otherMembers = members.filter(member => !isIndexSignatureDeclaration(member)); const parameter = first(indexSignature.parameters); - const mappedTypeParameter = factory.createTypeParameterDeclaration( - /*modifiers*/ - void 0, - cast(parameter.name, isIdentifier), - parameter.type - ); - const mappedIntersectionType = factory.createMappedTypeNode( - hasEffectiveReadonlyModifier(indexSignature) ? factory.createModifier(148 /* ReadonlyKeyword */) : void 0, - mappedTypeParameter, - /*nameType*/ - void 0, - indexSignature.questionToken, - indexSignature.type, - /*members*/ - void 0 - ); - const intersectionType = factory.createIntersectionTypeNode([ - ...getAllSuperTypeNodes(container), - mappedIntersectionType, - ...otherMembers.length ? [factory.createTypeLiteralNode(otherMembers)] : emptyArray - ]); + const mappedTypeParameter = factory.createTypeParameterDeclaration( /*modifiers*/ + void 0, cast(parameter.name, isIdentifier), parameter.type); + const mappedIntersectionType = factory.createMappedTypeNode(hasEffectiveReadonlyModifier(indexSignature) ? factory.createModifier(148 /* ReadonlyKeyword */) : void 0, mappedTypeParameter, /*nameType*/ + void 0, indexSignature.questionToken, indexSignature.type, /*members*/ + void 0); + const intersectionType = factory.createIntersectionTypeNode([...getAllSuperTypeNodes(container), mappedIntersectionType, ...(otherMembers.length ? [factory.createTypeLiteralNode(otherMembers)] : emptyArray)]); changes.replaceNode(sourceFile, container, createTypeAliasFromInterface(container, intersectionType)); } var fixId45, errorCodes57; var init_convertToMappedObjectType = __esm({ "src/services/codefixes/convertToMappedObjectType.ts"() { "use strict"; + init_ts4(); init_ts_codefix(); fixId45 = "fixConvertToMappedObjectType"; @@ -155885,19 +140189,20 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} registerCodeFix({ errorCodes: errorCodes57, getCodeActions: function getCodeActionsToConvertToMappedTypeObject(context) { - const { sourceFile, span } = context; + const { + sourceFile, + span + } = context; const info = getInfo19(sourceFile, span.start); - if (!info) - return void 0; - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange38(t, sourceFile, info)); + if (!info) return void 0; + const changes = ts_textChanges_exports.ChangeTracker.with(context, t => doChange38(t, sourceFile, info)); const name = idText(info.container.name); return [createCodeFixAction(fixId45, changes, [Diagnostics.Convert_0_to_mapped_object_type, name], fixId45, [Diagnostics.Convert_0_to_mapped_object_type, name])]; }, fixIds: [fixId45], - getAllCodeActions: (context) => codeFixAll(context, errorCodes57, (changes, diag2) => { + getAllCodeActions: context => codeFixAll(context, errorCodes57, (changes, diag2) => { const info = getInfo19(diag2.file, diag2.start); - if (info) - doChange38(changes, diag2.file, info); + if (info) doChange38(changes, diag2.file, info); }) }); } @@ -155908,12 +140213,11 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} var init_removeAccidentalCallParentheses = __esm({ "src/services/codefixes/removeAccidentalCallParentheses.ts"() { "use strict"; + init_ts4(); init_ts_codefix(); fixId46 = "removeAccidentalCallParentheses"; - errorCodes58 = [ - Diagnostics.This_expression_is_not_callable_because_it_is_a_get_accessor_Did_you_mean_to_use_it_without.code - ]; + errorCodes58 = [Diagnostics.This_expression_is_not_callable_because_it_is_a_get_accessor_Did_you_mean_to_use_it_without.code]; registerCodeFix({ errorCodes: errorCodes58, getCodeActions(context) { @@ -155921,8 +140225,11 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (!callExpression) { return void 0; } - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => { - t.deleteRange(context.sourceFile, { pos: callExpression.expression.end, end: callExpression.end }); + const changes = ts_textChanges_exports.ChangeTracker.with(context, t => { + t.deleteRange(context.sourceFile, { + pos: callExpression.expression.end, + end: callExpression.end + }); }); return [createCodeFixActionWithoutFixAll(fixId46, changes, Diagnostics.Remove_parentheses)]; }, @@ -155933,7 +140240,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} // src/services/codefixes/removeUnnecessaryAwait.ts function makeChange10(changeTracker, sourceFile, span) { - const awaitKeyword = tryCast(getTokenAtPosition(sourceFile, span.start), (node) => node.kind === 135 /* AwaitKeyword */); + const awaitKeyword = tryCast(getTokenAtPosition(sourceFile, span.start), node => node.kind === 135 /* AwaitKeyword */); const awaitExpression = awaitKeyword && tryCast(awaitKeyword.parent, isAwaitExpression); if (!awaitExpression) { return; @@ -155941,11 +140248,8 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} let expressionToReplace = awaitExpression; const hasSurroundingParens = isParenthesizedExpression(awaitExpression.parent); if (hasSurroundingParens) { - const leftMostExpression = getLeftmostExpression( - awaitExpression.expression, - /*stopAtCallExpressions*/ - false - ); + const leftMostExpression = getLeftmostExpression(awaitExpression.expression, /*stopAtCallExpressions*/ + false); if (isIdentifier(leftMostExpression)) { const precedingToken = findPrecedingToken(awaitExpression.parent.pos, sourceFile); if (precedingToken && precedingToken.kind !== 105 /* NewKeyword */) { @@ -155959,22 +140263,21 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} var init_removeUnnecessaryAwait = __esm({ "src/services/codefixes/removeUnnecessaryAwait.ts"() { "use strict"; + init_ts4(); init_ts_codefix(); fixId47 = "removeUnnecessaryAwait"; - errorCodes59 = [ - Diagnostics.await_has_no_effect_on_the_type_of_this_expression.code - ]; + errorCodes59 = [Diagnostics.await_has_no_effect_on_the_type_of_this_expression.code]; registerCodeFix({ errorCodes: errorCodes59, getCodeActions: function getCodeActionsToRemoveUnnecessaryAwait(context) { - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => makeChange10(t, context.sourceFile, context.span)); + const changes = ts_textChanges_exports.ChangeTracker.with(context, t => makeChange10(t, context.sourceFile, context.span)); if (changes.length > 0) { return [createCodeFixAction(fixId47, changes, Diagnostics.Remove_unnecessary_await, fixId47, Diagnostics.Remove_all_unnecessary_uses_of_await)]; } }, fixIds: [fixId47], - getAllCodeActions: (context) => { + getAllCodeActions: context => { return codeFixAll(context, errorCodes59, (changes, diag2) => makeChange10(changes, diag2.file, diag2)); } }); @@ -155990,45 +140293,17 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return; } const importClause = Debug.checkDefined(importDeclaration.importClause); - changes.replaceNode( - context.sourceFile, - importDeclaration, - factory.updateImportDeclaration( - importDeclaration, - importDeclaration.modifiers, - factory.updateImportClause( - importClause, - importClause.isTypeOnly, - importClause.name, - /*namedBindings*/ - void 0 - ), - importDeclaration.moduleSpecifier, - importDeclaration.attributes - ) - ); - changes.insertNodeAfter( - context.sourceFile, - importDeclaration, - factory.createImportDeclaration( - /*modifiers*/ - void 0, - factory.updateImportClause( - importClause, - importClause.isTypeOnly, - /*name*/ - void 0, - importClause.namedBindings - ), - importDeclaration.moduleSpecifier, - importDeclaration.attributes - ) - ); + changes.replaceNode(context.sourceFile, importDeclaration, factory.updateImportDeclaration(importDeclaration, importDeclaration.modifiers, factory.updateImportClause(importClause, importClause.isTypeOnly, importClause.name, /*namedBindings*/ + void 0), importDeclaration.moduleSpecifier, importDeclaration.attributes)); + changes.insertNodeAfter(context.sourceFile, importDeclaration, factory.createImportDeclaration( /*modifiers*/ + void 0, factory.updateImportClause(importClause, importClause.isTypeOnly, /*name*/ + void 0, importClause.namedBindings), importDeclaration.moduleSpecifier, importDeclaration.attributes)); } var errorCodes60, fixId48; var init_splitTypeOnlyImport = __esm({ "src/services/codefixes/splitTypeOnlyImport.ts"() { "use strict"; + init_ts4(); init_ts_codefix(); errorCodes60 = [Diagnostics.A_type_only_import_can_specify_a_default_import_or_named_bindings_but_not_both.code]; @@ -156037,14 +140312,14 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} errorCodes: errorCodes60, fixIds: [fixId48], getCodeActions: function getCodeActionsToSplitTypeOnlyImport(context) { - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => { + const changes = ts_textChanges_exports.ChangeTracker.with(context, t => { return splitTypeOnlyImport(t, getImportDeclaration2(context.sourceFile, context.span), context); }); if (changes.length) { return [createCodeFixAction(fixId48, changes, Diagnostics.Split_into_two_separate_import_declarations, fixId48, Diagnostics.Split_all_invalid_type_only_imports)]; } }, - getAllCodeActions: (context) => codeFixAll(context, errorCodes60, (changes, error2) => { + getAllCodeActions: context => codeFixAll(context, errorCodes60, (changes, error2) => { splitTypeOnlyImport(changes, getImportDeclaration2(context.sourceFile, error2), context); }) }); @@ -156056,23 +140331,25 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} 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; - return { symbol, token: constToken }; + if (constToken === void 0) return; + return { + symbol, + token: constToken + }; } function doChange39(changes, sourceFile, token) { changes.replaceNode(sourceFile, token, factory.createToken(121 /* LetKeyword */)); } + var fixId49, errorCodes61; var init_convertConstToLet = __esm({ "src/services/codefixes/convertConstToLet.ts"() { "use strict"; + init_ts4(); init_ts_codefix(); fixId49 = "fixConvertConstToLet"; @@ -156080,18 +140357,23 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} registerCodeFix({ errorCodes: errorCodes61, getCodeActions: function getCodeActionsToConvertConstToLet(context) { - const { sourceFile, span, program } = context; + const { + sourceFile, + span, + program + } = context; const info = getInfo20(sourceFile, span.start, program); - if (info === void 0) - return; - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange39(t, sourceFile, info.token)); + if (info === void 0) return; + const changes = ts_textChanges_exports.ChangeTracker.with(context, t => doChange39(t, sourceFile, info.token)); return [createCodeFixActionMaybeFixAll(fixId49, changes, Diagnostics.Convert_const_to_let, fixId49, Diagnostics.Convert_all_const_to_let)]; }, - getAllCodeActions: (context) => { - const { program } = context; - const seen = /* @__PURE__ */ new Map(); - return createCombinedCodeActions(ts_textChanges_exports.ChangeTracker.with(context, (changes) => { - eachDiagnostic(context, errorCodes61, (diag2) => { + getAllCodeActions: context => { + const { + program + } = context; + const seen = /* @__PURE__ */new Map(); + return createCombinedCodeActions(ts_textChanges_exports.ChangeTracker.with(context, changes => { + eachDiagnostic(context, errorCodes61, diag2 => { const info = getInfo20(diag2.file, diag2.start, program); if (info) { if (addToSeen(seen, getSymbolId(info.symbol))) { @@ -156110,9 +140392,13 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} // src/services/codefixes/fixExpectedComma.ts function getInfo21(sourceFile, pos, _) { const node = getTokenAtPosition(sourceFile, pos); - return node.kind === 27 /* SemicolonToken */ && node.parent && (isObjectLiteralExpression(node.parent) || isArrayLiteralExpression(node.parent)) ? { node } : void 0; + return node.kind === 27 /* SemicolonToken */ && node.parent && (isObjectLiteralExpression(node.parent) || isArrayLiteralExpression(node.parent)) ? { + node + } : void 0; } - function doChange40(changes, sourceFile, { node }) { + function doChange40(changes, sourceFile, { + node + }) { const newNode = factory.createToken(28 /* CommaToken */); changes.replaceNode(sourceFile, node, newNode); } @@ -156120,6 +140406,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} var init_fixExpectedComma = __esm({ "src/services/codefixes/fixExpectedComma.ts"() { "use strict"; + init_ts4(); init_ts_codefix(); fixId50 = "fixExpectedComma"; @@ -156128,24 +140415,18 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} registerCodeFix({ errorCodes: errorCodes62, getCodeActions(context) { - const { sourceFile } = context; + const { + sourceFile + } = context; const info = getInfo21(sourceFile, context.span.start, context.errorCode); - if (!info) - return void 0; - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange40(t, sourceFile, info)); - return [createCodeFixAction( - fixId50, - changes, - [Diagnostics.Change_0_to_1, ";", ","], - fixId50, - [Diagnostics.Change_0_to_1, ";", ","] - )]; + if (!info) return void 0; + const changes = ts_textChanges_exports.ChangeTracker.with(context, t => doChange40(t, sourceFile, info)); + return [createCodeFixAction(fixId50, changes, [Diagnostics.Change_0_to_1, ";", ","], fixId50, [Diagnostics.Change_0_to_1, ";", ","])]; }, fixIds: [fixId50], - getAllCodeActions: (context) => codeFixAll(context, errorCodes62, (changes, diag2) => { + getAllCodeActions: context => codeFixAll(context, errorCodes62, (changes, diag2) => { const info = getInfo21(diag2.file, diag2.start, diag2.code); - if (info) - doChange40(changes, context.sourceFile, info); + if (info) doChange40(changes, context.sourceFile, info); }) }); } @@ -156154,15 +140435,12 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} // src/services/codefixes/fixAddVoidToPromise.ts function makeChange11(changes, sourceFile, span, program, seen) { const node = getTokenAtPosition(sourceFile, span.start); - if (!isIdentifier(node) || !isCallExpression(node.parent) || node.parent.expression !== node || node.parent.arguments.length !== 0) - return; + 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)) { @@ -156205,25 +140483,23 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} var init_fixAddVoidToPromise = __esm({ "src/services/codefixes/fixAddVoidToPromise.ts"() { "use strict"; + init_ts4(); init_ts_codefix(); fixName7 = "addVoidToPromise"; fixId51 = "addVoidToPromise"; - errorCodes63 = [ - Diagnostics.Expected_1_argument_but_got_0_new_Promise_needs_a_JSDoc_hint_to_produce_a_resolve_that_can_be_called_without_arguments.code, - Diagnostics.Expected_0_arguments_but_got_1_Did_you_forget_to_include_void_in_your_type_argument_to_Promise.code - ]; + errorCodes63 = [Diagnostics.Expected_1_argument_but_got_0_new_Promise_needs_a_JSDoc_hint_to_produce_a_resolve_that_can_be_called_without_arguments.code, Diagnostics.Expected_0_arguments_but_got_1_Did_you_forget_to_include_void_in_your_type_argument_to_Promise.code]; registerCodeFix({ errorCodes: errorCodes63, fixIds: [fixId51], getCodeActions(context) { - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => makeChange11(t, context.sourceFile, context.span, context.program)); + const changes = ts_textChanges_exports.ChangeTracker.with(context, t => makeChange11(t, context.sourceFile, context.span, context.program)); if (changes.length > 0) { return [createCodeFixAction(fixName7, changes, Diagnostics.Add_void_to_Promise_resolved_without_a_value, fixId51, Diagnostics.Add_void_to_all_Promises_resolved_without_a_value)]; } }, getAllCodeActions(context) { - return codeFixAll(context, errorCodes63, (changes, diag2) => makeChange11(changes, diag2.file, diag2, context.program, /* @__PURE__ */ new Set())); + return codeFixAll(context, errorCodes63, (changes, diag2) => makeChange11(changes, diag2.file, diag2, context.program, /* @__PURE__ */new Set())); } }); } @@ -156276,6 +140552,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} var init_ts_codefix = __esm({ "src/services/_namespaces/ts.codefix.ts"() { "use strict"; + init_codeFixProvider(); init_addConvertToUnknownForNonOverlappingTypes(); init_addEmptyExportDeclaration(); @@ -156353,15 +140630,19 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} function originIsThisType(origin) { return !!(origin.kind & 1 /* ThisType */); } + function originIsSymbolMember(origin) { return !!(origin.kind & 2 /* SymbolMember */); } + function originIsExport(origin) { return !!(origin && origin.kind & 4 /* Export */); } + function originIsResolvedExport(origin) { return !!(origin && origin.kind === 32 /* ResolvedExport */); } + function originIncludesSymbolName(origin) { return originIsExport(origin) || originIsResolvedExport(origin) || originIsComputedPropertyName(origin); } @@ -156371,21 +140652,27 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} function originIsPromise(origin) { return !!(origin.kind & 8 /* Promise */); } + function originIsNullableMember(origin) { return !!(origin.kind & 16 /* Nullable */); } + function originIsTypeOnlyAlias(origin) { return !!(origin && origin.kind & 64 /* TypeOnlyAlias */); } + function originIsObjectLiteralMethod(origin) { return !!(origin && origin.kind & 128 /* ObjectLiteralMethod */); } + function originIsIgnore(origin) { return !!(origin && origin.kind & 256 /* Ignore */); } + function originIsComputedPropertyName(origin) { return !!(origin && origin.kind & 512 /* ComputedPropertyName */); } + function resolvingModuleSpecifiers(logPrefix, host, resolver, program, position, preferences, isForImportStatementCompletion, isValidTypeOnlyUseSite, cb) { var _a, _b, _c; const start = timestamp(); @@ -156430,13 +140717,21 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } function getCompletionsAtPosition(host, program, log, sourceFile, position, preferences, triggerCharacter, completionKind, cancellationToken, formatContext, includeSymbol = false) { var _a; - const { previousToken } = getRelevantTokens(position, sourceFile); + const { + previousToken + } = getRelevantTokens(position, sourceFile); if (triggerCharacter && !isInString(sourceFile, position, previousToken) && !isValidTrigger(sourceFile, triggerCharacter, previousToken, position)) { return void 0; } if (triggerCharacter === " ") { if (preferences.includeCompletionsForImportStatements && preferences.includeCompletionsWithInsertText) { - return { isGlobalCompletion: true, isMemberCompletion: false, isNewIdentifierLocation: true, isIncomplete: true, entries: [] }; + return { + isGlobalCompletion: true, + isMemberCompletion: false, + isNewIdentifierLocation: true, + isIncomplete: true, + entries: [] + }; } return void 0; } @@ -156458,19 +140753,8 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (previousToken && isBreakOrContinueStatement(previousToken.parent) && (previousToken.kind === 83 /* BreakKeyword */ || previousToken.kind === 88 /* ContinueKeyword */ || previousToken.kind === 80 /* Identifier */)) { return getLabelCompletionAtPosition(previousToken.parent); } - const completionData = getCompletionData( - program, - log, - sourceFile, - compilerOptions, - position, - preferences, - /*detailsEntryId*/ - void 0, - host, - formatContext, - cancellationToken - ); + const completionData = getCompletionData(program, log, sourceFile, compilerOptions, position, preferences, /*detailsEntryId*/ + void 0, host, formatContext, cancellationToken); if (!completionData) { return void 0; } @@ -156482,31 +140766,11 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } return response; case 1 /* JsDocTagName */: - return jsdocCompletionInfo([ - ...ts_JsDoc_exports.getJSDocTagNameCompletions(), - ...getJSDocParameterCompletions( - sourceFile, - position, - checker, - compilerOptions, - preferences, - /*tagNameOnly*/ - true - ) - ]); + return jsdocCompletionInfo([...ts_JsDoc_exports.getJSDocTagNameCompletions(), ...getJSDocParameterCompletions(sourceFile, position, checker, compilerOptions, preferences, /*tagNameOnly*/ + true)]); case 2 /* JsDocTag */: - return jsdocCompletionInfo([ - ...ts_JsDoc_exports.getJSDocTagCompletions(), - ...getJSDocParameterCompletions( - sourceFile, - position, - checker, - compilerOptions, - preferences, - /*tagNameOnly*/ - false - ) - ]); + return jsdocCompletionInfo([...ts_JsDoc_exports.getJSDocTagCompletions(), ...getJSDocParameterCompletions(sourceFile, position, checker, compilerOptions, preferences, /*tagNameOnly*/ + false)]); case 3 /* JsDocParameterName */: return jsdocCompletionInfo(ts_JsDoc_exports.getJSDocParameterNameCompletions(completionData.tag)); case 4 /* Keywords */: @@ -156522,14 +140786,12 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} result = compareStringsCaseSensitiveUI(entryInArray.name, entryToInsert.name); } if (result === 0 /* EqualTo */ && ((_a = entryInArray.data) == null ? void 0 : _a.moduleSpecifier) && ((_b = entryToInsert.data) == null ? void 0 : _b.moduleSpecifier)) { - result = compareNumberOfDirectorySeparators( - entryInArray.data.moduleSpecifier, - entryToInsert.data.moduleSpecifier - ); + result = compareNumberOfDirectorySeparators(entryInArray.data.moduleSpecifier, entryToInsert.data.moduleSpecifier); } if (result === 0 /* EqualTo */) { return -1 /* LessThan */; } + return result; } function completionEntryDataIsResolved(data) { @@ -156537,62 +140799,57 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } 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); - const newEntries = resolvingModuleSpecifiers( - "continuePreviousIncompleteResponse", - host, - ts_codefix_exports.createImportSpecifierResolver(file, program, host, preferences), - program, - location.getStart(), - preferences, - /*isForImportStatementCompletion*/ - false, - isValidTypeOnlyAliasUseSite(location), - (context) => { - const entries = mapDefined(previousResponse.entries, (entry) => { - var _a; - if (!entry.hasAction || !entry.source || !entry.data || completionEntryDataIsResolved(entry.data)) { - return entry; - } - if (!charactersFuzzyMatchInString(entry.name, lowerCaseTokenText)) { - return void 0; - } - const { origin } = Debug.checkDefined(getAutoImportSymbolFromCompletionEntryData(entry.name, entry.data, program, host)); - const info = exportMap.get(file.path, entry.data.exportMapKey); - const result = info && context.tryResolve(info, !isExternalModuleNameRelative(stripQuotes(origin.moduleSymbol.name))); - if (result === "skipped") - return entry; - if (!result || result === "failed") { - (_a = host.log) == null ? void 0 : _a.call(host, `Unexpected failure resolving auto import for '${entry.name}' from '${entry.source}'`); - return void 0; - } - const newOrigin = { - ...origin, - kind: 32 /* ResolvedExport */, - moduleSpecifier: result.moduleSpecifier - }; - entry.data = originToCompletionEntryData(newOrigin); - entry.source = getSourceFromOrigin(newOrigin); - entry.sourceDisplay = [textPart(newOrigin.moduleSpecifier)]; + const newEntries = resolvingModuleSpecifiers("continuePreviousIncompleteResponse", host, ts_codefix_exports.createImportSpecifierResolver(file, program, host, preferences), program, location.getStart(), preferences, /*isForImportStatementCompletion*/ + false, isValidTypeOnlyAliasUseSite(location), context => { + const entries = mapDefined(previousResponse.entries, entry => { + var _a; + if (!entry.hasAction || !entry.source || !entry.data || completionEntryDataIsResolved(entry.data)) { return entry; - }); - if (!context.skippedAny()) { - previousResponse.isIncomplete = void 0; } - return entries; + if (!charactersFuzzyMatchInString(entry.name, lowerCaseTokenText)) { + return void 0; + } + 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 || 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; + } + const newOrigin = { + ...origin, + kind: 32 /* ResolvedExport */, + moduleSpecifier: result.moduleSpecifier + }; + entry.data = originToCompletionEntryData(newOrigin); + entry.source = getSourceFromOrigin(newOrigin); + entry.sourceDisplay = [textPart(newOrigin.moduleSpecifier)]; + return entry; + }); + if (!context.skippedAny()) { + previousResponse.isIncomplete = void 0; } - ); + return entries; + }); previousResponse.entries = newEntries; previousResponse.flags = (previousResponse.flags || 0) | 4 /* IsContinuation */; previousResponse.optionalReplacementSpan = getOptionalReplacementSpan(touchNode); return previousResponse; } function jsdocCompletionInfo(entries) { - return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries }; + return { + isGlobalCompletion: false, + isMemberCompletion: false, + isNewIdentifierLocation: false, + entries + }; } function getJSDocParameterCompletions(sourceFile, position, checker, options, preferences, tagNameOnly) { const currentToken = getTokenAtPosition(sourceFile, position); @@ -156609,45 +140866,25 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } const isJs = isSourceFileJS(sourceFile); const isSnippet = preferences.includeCompletionsWithSnippetText || void 0; - const paramTagCount = countWhere(jsDoc.tags, (tag) => isJSDocParameterTag(tag) && tag.getEnd() <= position); - return mapDefined(func.parameters, (param) => { + const paramTagCount = countWhere(jsDoc.tags, tag => isJSDocParameterTag(tag) && tag.getEnd() <= position); + return mapDefined(func.parameters, param => { if (getJSDocParameterTags(param).length) { return void 0; } if (isIdentifier(param.name)) { - const tabstopCounter = { tabstop: 1 }; + const tabstopCounter = { + tabstop: 1 + }; const paramName = param.name.text; - let displayText = getJSDocParamAnnotation( - paramName, - param.initializer, - param.dotDotDotToken, - isJs, - /*isObject*/ - false, - /*isSnippet*/ - false, - checker, - options, - preferences - ); - let snippetText = isSnippet ? getJSDocParamAnnotation( - paramName, - param.initializer, - param.dotDotDotToken, - isJs, - /*isObject*/ - false, - /*isSnippet*/ - true, - checker, - options, - preferences, - tabstopCounter - ) : void 0; + let displayText = getJSDocParamAnnotation(paramName, param.initializer, param.dotDotDotToken, isJs, /*isObject*/ + false, /*isSnippet*/ + false, checker, options, preferences); + let snippetText = isSnippet ? getJSDocParamAnnotation(paramName, param.initializer, param.dotDotDotToken, isJs, /*isObject*/ + false, /*isSnippet*/ + true, checker, options, preferences, tabstopCounter) : void 0; if (tagNameOnly) { displayText = displayText.slice(1); - if (snippetText) - snippetText = snippetText.slice(1); + if (snippetText) snippetText = snippetText.slice(1); } return { name: displayText, @@ -156658,36 +140895,15 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} }; } else if (param.parent.parameters.indexOf(param) === paramTagCount) { const paramPath = `param${paramTagCount}`; - const displayTextResult = generateJSDocParamTagsForDestructuring( - paramPath, - param.name, - param.initializer, - param.dotDotDotToken, - isJs, - /*isSnippet*/ - false, - checker, - options, - preferences - ); - const snippetTextResult = isSnippet ? generateJSDocParamTagsForDestructuring( - paramPath, - param.name, - param.initializer, - param.dotDotDotToken, - isJs, - /*isSnippet*/ - true, - checker, - options, - preferences - ) : void 0; + const displayTextResult = generateJSDocParamTagsForDestructuring(paramPath, param.name, param.initializer, param.dotDotDotToken, isJs, /*isSnippet*/ + false, checker, options, preferences); + const snippetTextResult = isSnippet ? generateJSDocParamTagsForDestructuring(paramPath, param.name, param.initializer, param.dotDotDotToken, isJs, /*isSnippet*/ + true, checker, options, preferences) : void 0; let displayText = displayTextResult.join(getNewLineCharacter(options) + "* "); let snippetText = snippetTextResult == null ? void 0 : snippetTextResult.join(getNewLineCharacter(options) + "* "); if (tagNameOnly) { displayText = displayText.slice(1); - if (snippetText) - snippetText = snippetText.slice(1); + if (snippetText) snippetText = snippetText.slice(1); } return { name: displayText, @@ -156701,40 +140917,22 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } function generateJSDocParamTagsForDestructuring(path, pattern, initializer, dotDotDotToken, isJs, isSnippet, checker, options, preferences) { if (!isJs) { - return [ - getJSDocParamAnnotation( - path, - initializer, - dotDotDotToken, - isJs, - /*isObject*/ - false, - isSnippet, - checker, - options, - preferences, - { tabstop: 1 } - ) - ]; + return [getJSDocParamAnnotation(path, initializer, dotDotDotToken, isJs, /*isObject*/ + false, isSnippet, checker, options, preferences, { + tabstop: 1 + })]; } - return patternWorker(path, pattern, initializer, dotDotDotToken, { tabstop: 1 }); + return patternWorker(path, pattern, initializer, dotDotDotToken, { + tabstop: 1 + }); function patternWorker(path2, pattern2, initializer2, dotDotDotToken2, counter) { if (isObjectBindingPattern(pattern2) && !dotDotDotToken2) { const oldTabstop = counter.tabstop; - const childCounter = { tabstop: oldTabstop }; - const rootParam = getJSDocParamAnnotation( - path2, - initializer2, - dotDotDotToken2, - isJs, - /*isObject*/ - true, - isSnippet, - checker, - options, - preferences, - childCounter - ); + const childCounter = { + tabstop: oldTabstop + }; + const rootParam = getJSDocParamAnnotation(path2, initializer2, dotDotDotToken2, isJs, /*isObject*/ + true, isSnippet, checker, options, preferences, childCounter); let childTags = []; for (const element of pattern2.elements) { const elementTags = elementWorker(path2, element, childCounter); @@ -156750,21 +140948,8 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return [rootParam, ...childTags]; } } - return [ - getJSDocParamAnnotation( - path2, - initializer2, - dotDotDotToken2, - isJs, - /*isObject*/ - false, - isSnippet, - checker, - options, - preferences, - counter - ) - ]; + return [getJSDocParamAnnotation(path2, initializer2, dotDotDotToken2, isJs, /*isObject*/ + false, isSnippet, checker, options, preferences, counter)]; } function elementWorker(path2, element, counter) { if (!element.propertyName && isIdentifier(element.name) || isIdentifier(element.name)) { @@ -156773,21 +140958,8 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return void 0; } const paramName = `${path2}.${propertyName}`; - return [ - getJSDocParamAnnotation( - paramName, - element.initializer, - element.dotDotDotToken, - isJs, - /*isObject*/ - false, - isSnippet, - checker, - options, - preferences, - counter - ) - ]; + return [getJSDocParamAnnotation(paramName, element.initializer, element.dotDotDotToken, isJs, /*isObject*/ + false, isSnippet, checker, options, preferences, counter)]; } else if (element.propertyName) { const propertyName = tryGetTextOfPropertyName(element.propertyName); return propertyName && patternWorker(`${path2}.${propertyName}`, element.name, element.initializer, element.dotDotDotToken, counter); @@ -156919,86 +141091,47 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} const caseClause = findAncestor(contextToken, isCaseClause); if (caseClause && (isCaseKeyword(contextToken) || isNodeDescendantOf(contextToken, caseClause.expression))) { const tracker = newCaseClauseTracker(checker, caseClause.parent.clauses); - literals = literals.filter((literal) => !tracker.hasValue(literal)); + literals = literals.filter(literal => !tracker.hasValue(literal)); symbols.forEach((symbol, i) => { if (symbol.valueDeclaration && isEnumMember(symbol.valueDeclaration)) { const value = checker.getConstantValue(symbol.valueDeclaration); if (value !== void 0 && tracker.hasValue(value)) { - symbolToOriginInfoMap[i] = { kind: 256 /* Ignore */ }; + symbolToOriginInfoMap[i] = { + kind: 256 /* Ignore */ + }; } } }); } + const entries = createSortedArray(); const isChecked = isCheckedFile(sourceFile, compilerOptions); if (isChecked && !isNewIdentifierLocation && (!symbols || symbols.length === 0) && keywordFilters === 0 /* None */) { return void 0; } - const uniqueNames = getCompletionEntriesFromSymbols( - symbols, - entries, - /*replacementToken*/ - void 0, - contextToken, - location, - position, - sourceFile, - host, - program, - getEmitScriptTarget(compilerOptions), - log, - completionKind, - preferences, - compilerOptions, - formatContext, - isTypeOnlyLocation, - propertyAccessToConvert, - isJsxIdentifierExpected, - isJsxInitializer, - importStatementCompletion, - recommendedCompletion, - symbolToOriginInfoMap, - symbolToSortTextMap, - isJsxIdentifierExpected, - isRightOfOpenTag, - includeSymbol - ); + const uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, /*replacementToken*/ + void 0, contextToken, location, position, sourceFile, host, program, getEmitScriptTarget(compilerOptions), log, completionKind, preferences, compilerOptions, formatContext, isTypeOnlyLocation, propertyAccessToConvert, isJsxIdentifierExpected, isJsxInitializer, importStatementCompletion, recommendedCompletion, symbolToOriginInfoMap, symbolToSortTextMap, isJsxIdentifierExpected, isRightOfOpenTag, includeSymbol); if (keywordFilters !== 0 /* None */) { for (const keywordEntry of getKeywordCompletions(keywordFilters, !insideJsDocTagTypeExpression && isSourceFileJS(sourceFile))) { if (isTypeOnlyLocation && isTypeKeyword(stringToToken(keywordEntry.name)) || !isTypeOnlyLocation && isContextualKeywordInAutoImportableExpressionSpace(keywordEntry.name) || !uniqueNames.has(keywordEntry.name)) { uniqueNames.add(keywordEntry.name); - insertSorted( - entries, - keywordEntry, - compareCompletionEntries, - /*allowDuplicates*/ - true - ); + insertSorted(entries, keywordEntry, compareCompletionEntries, /*allowDuplicates*/ + true); } } } for (const keywordEntry of getContextualKeywords(contextToken, position)) { if (!uniqueNames.has(keywordEntry.name)) { uniqueNames.add(keywordEntry.name); - insertSorted( - entries, - keywordEntry, - compareCompletionEntries, - /*allowDuplicates*/ - true - ); + insertSorted(entries, keywordEntry, compareCompletionEntries, /*allowDuplicates*/ + true); } } for (const literal of literals) { const literalEntry = createCompletionEntryForLiteral(sourceFile, preferences, literal); uniqueNames.add(literalEntry.name); - insertSorted( - entries, - literalEntry, - compareCompletionEntries, - /*allowDuplicates*/ - true - ); + insertSorted(entries, literalEntry, compareCompletionEntries, /*allowDuplicates*/ + true); } if (!isChecked) { getJSCompletionEntries(sourceFile, location.pos, uniqueNames, getEmitScriptTarget(compilerOptions), entries); @@ -157027,7 +141160,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} const clauses = caseBlock.clauses; const checker = program.getTypeChecker(); const switchType = checker.getTypeAtLocation(caseBlock.parent.expression); - if (switchType && switchType.isUnion() && every(switchType.types, (type) => type.isLiteral())) { + if (switchType && switchType.isUnion() && every(switchType.types, type => type.isLiteral())) { const tracker = newCaseClauseTracker(checker, clauses); const target = getEmitScriptTarget(options); const quotePreference = getQuotePreference(sourceFile, preferences); @@ -157056,7 +141189,10 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } else if (!tracker.hasValue(type.value)) { switch (typeof type.value) { case "object": - elements.push(type.value.negative ? factory.createPrefixUnaryExpression(41 /* MinusToken */, factory.createBigIntLiteral({ negative: false, base10Value: type.value.base10Value })) : factory.createBigIntLiteral(type.value)); + elements.push(type.value.negative ? factory.createPrefixUnaryExpression(41 /* MinusToken */, factory.createBigIntLiteral({ + negative: false, + base10Value: type.value.base10Value + })) : factory.createBigIntLiteral(type.value)); break; case "number": elements.push(type.value < 0 ? factory.createPrefixUnaryExpression(41 /* MinusToken */, factory.createNumericLiteral(-type.value)) : factory.createNumericLiteral(type.value)); @@ -157070,7 +141206,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (elements.length === 0) { return void 0; } - const newClauses = map(elements, (element) => factory.createCaseClause(element, [])); + const newClauses = map(elements, element => factory.createCaseClause(element, [])); const newLineChar = getNewLineOrDefaultFromHost(host, formatContext == null ? void 0 : formatContext.options); const printer = createSnippetPrinter({ removeComments: true, @@ -157078,7 +141214,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} target: options.target, newLine: getNewLineKind(newLineChar) }); - const printNode = formatContext ? (node) => printer.printAndFormatNode(4 /* Unspecified */, node, sourceFile, formatContext) : (node) => printer.printNode(4 /* Unspecified */, node, sourceFile); + const printNode = formatContext ? node => printer.printAndFormatNode(4 /* Unspecified */, node, sourceFile, formatContext) : node => printer.printNode(4 /* Unspecified */, node, sourceFile); const insertText = map(newClauses, (clause, i) => { if (preferences.includeCompletionsWithSnippetText) { return `${printNode(clause)}$${i + 1}`; @@ -157135,17 +141271,12 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } const unescapedName = unescapeLeadingUnderscores(entityName.right.escapedText); if (canUsePropertyAccess(unescapedName, languageVersion)) { - return factory.createPropertyAccessExpression( - entityNameToExpression(entityName.left, languageVersion, quotePreference), - unescapedName - ); + return factory.createPropertyAccessExpression(entityNameToExpression(entityName.left, languageVersion, quotePreference), unescapedName); } else { - return factory.createElementAccessExpression( - entityNameToExpression(entityName.left, languageVersion, quotePreference), - factory.createStringLiteral(unescapedName, quotePreference === 0 /* Single */) - ); + return factory.createElementAccessExpression(entityNameToExpression(entityName.left, languageVersion, quotePreference), factory.createStringLiteral(unescapedName, quotePreference === 0 /* Single */)); } } + function isMemberCompletionKind(kind) { switch (kind) { case 0 /* ObjectPropertyDeclaration */: @@ -157157,7 +141288,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } } function getJsxClosingTagCompletion(location, sourceFile) { - const jsxClosingElement = findAncestor(location, (node) => { + const jsxClosingElement = findAncestor(location, node => { switch (node.kind) { case 287 /* JsxClosingElement */: return true; @@ -157182,7 +141313,13 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} kindModifiers: void 0, sortText: SortText.LocationPriority }; - return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: false, optionalReplacementSpan: replacementSpan, entries: [entry] }; + return { + isGlobalCompletion: false, + isMemberCompletion: true, + isNewIdentifierLocation: false, + optionalReplacementSpan: replacementSpan, + entries: [entry] + }; } return; } @@ -157208,7 +141345,12 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return typeof literal === "object" ? pseudoBigIntToString(literal) + "n" : isString(literal) ? quote(sourceFile, preferences, literal) : JSON.stringify(literal); } function createCompletionEntryForLiteral(sourceFile, preferences, literal) { - return { name: completionNameForLiteral(sourceFile, preferences, literal), kind: "string" /* string */, kindModifiers: "" /* none */, sortText: SortText.LocationPriority }; + return { + name: completionNameForLiteral(sourceFile, preferences, literal), + kind: "string" /* string */, + kindModifiers: "" /* none */, + sortText: SortText.LocationPriority + }; } function createCompletionEntry(symbol, sortText, replacementToken, contextToken, location, position, sourceFile, host, program, name, needsConvertPropertyAccess, origin, recommendedCompletion, propertyAccessToConvert, isJsxInitializer, importStatementCompletion, useSemicolons, options, preferences, completionKind, formatContext, isJsxIdentifierExpected, isRightOfOpenTag, includeSymbol) { var _a, _b; @@ -157239,16 +141381,14 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} 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)) { @@ -157263,7 +141403,10 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (originIsResolvedExport(origin)) { sourceDisplay = [textPart(origin.moduleSpecifier)]; if (importStatementCompletion) { - ({ insertText, replacementSpan } = getInsertTextAndReplacementSpanForImportCompletion(name, importStatementCompletion, origin, useSemicolons, sourceFile, options, preferences)); + ({ + insertText, + replacementSpan + } = getInsertTextAndReplacementSpanForImportCompletion(name, importStatementCompletion, origin, useSemicolons, sourceFile, options, preferences)); isSnippet = preferences.includeCompletionsWithSnippetText ? true : void 0; } } @@ -157280,7 +141423,12 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} let importAdder; const memberCompletionEntry = getEntryForMemberCompletion(host, program, options, preferences, name, symbol, location, position, contextToken, formatContext); if (memberCompletionEntry) { - ({ insertText, filterText, isSnippet, importAdder } = memberCompletionEntry); + ({ + insertText, + filterText, + isSnippet, + importAdder + } = memberCompletionEntry); if (importAdder == null ? void 0 : importAdder.hasFixes()) { hasAction = true; source = "ClassMemberSnippet/" /* ClassMemberSnippet */; @@ -157290,7 +141438,11 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } } if (origin && originIsObjectLiteralMethod(origin)) { - ({ insertText, isSnippet, labelDetails } = origin); + ({ + insertText, + isSnippet, + labelDetails + } = origin); if (!preferences.useLabelDetailsInCompletionEntries) { name = name + labelDetails.detail; labelDetails = void 0; @@ -157301,8 +141453,8 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (isJsxIdentifierExpected && !isRightOfOpenTag && preferences.includeCompletionsWithSnippetText && preferences.jsxAttributeCompletionStyle && preferences.jsxAttributeCompletionStyle !== "none" && !(isJsxAttribute(location.parent) && location.parent.initializer)) { let useBraces2 = preferences.jsxAttributeCompletionStyle === "braces"; const type = typeChecker.getTypeOfSymbolAtLocation(symbol, location); - if (preferences.jsxAttributeCompletionStyle === "auto" && !(type.flags & 528 /* BooleanLike */) && !(type.flags & 1048576 /* Union */ && find(type.types, (type2) => !!(type2.flags & 528 /* BooleanLike */)))) { - if (type.flags & 402653316 /* StringLike */ || type.flags & 1048576 /* Union */ && every(type.types, (type2) => !!(type2.flags & (402653316 /* StringLike */ | 32768 /* Undefined */) || isStringAndEmptyAnonymousObjectIntersection(type2)))) { + if (preferences.jsxAttributeCompletionStyle === "auto" && !(type.flags & 528 /* BooleanLike */) && !(type.flags & 1048576 /* Union */ && find(type.types, type2 => !!(type2.flags & 528 /* BooleanLike */)))) { + if (type.flags & 402653316 /* StringLike */ || type.flags & 1048576 /* Union */ && every(type.types, type2 => !!(type2.flags & (402653316 /* StringLike */ | 32768 /* Undefined */) || isStringAndEmptyAnonymousObjectIntersection(type2)))) { insertText = `${escapeSnippetText(name)}=${quote(sourceFile, preferences, "$1")}`; isSnippet = true; } else { @@ -157345,7 +141497,9 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} isPackageJsonImport: originIsPackageJsonImport(origin) || void 0, isImportStatementCompletion: !!importStatementCompletion || void 0, data, - ...includeSymbol ? { symbol } : void 0 + ...(includeSymbol ? { + symbol + } : void 0) }; } function isClassLikeMemberCompletion(symbol, location, sourceFile) { @@ -157377,55 +141531,51 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (preferences.includeCompletionsWithSnippetText) { isSnippet = true; const emptyStmt = factory.createEmptyStatement(); - body = factory.createBlock( - [emptyStmt], - /*multiLine*/ - true - ); - setSnippetElement(emptyStmt, { kind: 0 /* TabStop */, order: 0 }); + body = factory.createBlock([emptyStmt], /*multiLine*/ + true); + setSnippetElement(emptyStmt, { + kind: 0 /* TabStop */, + order: 0 + }); } else { - body = factory.createBlock( - [], - /*multiLine*/ - true - ); + body = factory.createBlock([], /*multiLine*/ + true); } let modifiers = 0 /* None */; - const { modifiers: presentModifiers, range: eraseRange, decorators: presentDecorators } = getPresentModifiers(contextToken, sourceFile, position); + const { + modifiers: presentModifiers, + range: eraseRange, + decorators: presentDecorators + } = getPresentModifiers(contextToken, sourceFile, position); const isAbstract = presentModifiers & 64 /* Abstract */ && classLikeDeclaration.modifierFlagsCache & 64 /* Abstract */; let completionNodes = []; - ts_codefix_exports.addNewNodeForMemberSymbol( - symbol, - classLikeDeclaration, - sourceFile, - { program, host }, - preferences, - importAdder, - // `addNewNodeForMemberSymbol` calls this callback function for each new member node - // it adds for the given member symbol. - // We store these member nodes in the `completionNodes` array. - // Note: there might be: - // - No nodes if `addNewNodeForMemberSymbol` cannot figure out a node for the member; - // - One node; - // - More than one node if the member is overloaded (e.g. a method with overload signatures). - (node) => { - let requiredModifiers = 0 /* None */; - if (isAbstract) { - requiredModifiers |= 64 /* Abstract */; - } - if (isClassElement(node) && checker.getMemberOverrideModifierStatus(classLikeDeclaration, node, symbol) === 1 /* NeedsOverride */) { - requiredModifiers |= 16 /* Override */; - } - if (!completionNodes.length) { - modifiers = node.modifierFlagsCache | requiredModifiers; - } - node = factory.replaceModifiers(node, modifiers); - completionNodes.push(node); - }, - body, - ts_codefix_exports.PreserveOptionalFlags.Property, - !!isAbstract - ); + ts_codefix_exports.addNewNodeForMemberSymbol(symbol, classLikeDeclaration, sourceFile, { + program, + host + }, preferences, importAdder, + // `addNewNodeForMemberSymbol` calls this callback function for each new member node + // it adds for the given member symbol. + // We store these member nodes in the `completionNodes` array. + // Note: there might be: + // - No nodes if `addNewNodeForMemberSymbol` cannot figure out a node for the member; + // - One node; + // - More than one node if the member is overloaded (e.g. a method with overload signatures). + node => { + let requiredModifiers = 0 /* None */; + if (isAbstract) { + requiredModifiers |= 64 /* Abstract */; + } + + if (isClassElement(node) && checker.getMemberOverrideModifierStatus(classLikeDeclaration, node, symbol) === 1 /* NeedsOverride */) { + requiredModifiers |= 16 /* Override */; + } + + if (!completionNodes.length) { + modifiers = node.modifierFlagsCache | requiredModifiers; + } + node = factory.replaceModifiers(node, modifiers); + completionNodes.push(node); + }, body, ts_codefix_exports.PreserveOptionalFlags.Property, !!isAbstract); if (completionNodes.length) { const isMethod = symbol.flags & 8192 /* Method */; let allowedModifiers = modifiers | 16 /* Override */ | 1 /* Public */; @@ -157434,6 +141584,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } else { allowedModifiers |= 1024 /* Async */; } + const allowedAndPresent = presentModifiers & allowedModifiers; if (presentModifiers & ~allowedModifiers) { return void 0; @@ -157441,11 +141592,13 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (modifiers & 4 /* Protected */ && allowedAndPresent & 1 /* Public */) { modifiers &= ~4 /* Protected */; } + if (allowedAndPresent !== 0 /* None */ && !(allowedAndPresent & 1 /* Public */)) { modifiers &= ~1 /* Public */; } + modifiers |= allowedAndPresent; - completionNodes = completionNodes.map((node) => factory.replaceModifiers(node, modifiers)); + completionNodes = completionNodes.map(node => factory.replaceModifiers(node, modifiers)); if (presentDecorators == null ? void 0 : presentDecorators.length) { const lastNode = completionNodes[completionNodes.length - 1]; if (canHaveDecorators(lastNode)) { @@ -157454,30 +141607,33 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } const format = 1 /* MultiLine */ | 131072 /* NoTrailingNewLine */; if (formatContext) { - insertText = printer.printAndFormatSnippetList( - format, - factory.createNodeArray(completionNodes), - sourceFile, - formatContext - ); + insertText = printer.printAndFormatSnippetList(format, factory.createNodeArray(completionNodes), sourceFile, formatContext); } else { - insertText = printer.printSnippetList( - format, - factory.createNodeArray(completionNodes), - sourceFile - ); + insertText = printer.printSnippetList(format, factory.createNodeArray(completionNodes), sourceFile); } } - return { insertText, filterText, isSnippet, importAdder, eraseRange }; + return { + insertText, + filterText, + isSnippet, + importAdder, + eraseRange + }; } function getPresentModifiers(contextToken, sourceFile, position) { if (!contextToken || getLineAndCharacterOfPosition(sourceFile, position).line > getLineAndCharacterOfPosition(sourceFile, contextToken.getEnd()).line) { - return { modifiers: 0 /* None */ }; + return { + modifiers: 0 /* None */ + }; } + let modifiers = 0 /* None */; let decorators; let contextMod; - const range = { pos: position, end: position }; + const range = { + pos: position, + end: position + }; if (isPropertyDeclaration(contextToken.parent) && contextToken.parent.modifiers) { modifiers |= modifiersToFlags(contextToken.parent.modifiers) & 98303 /* Modifier */; decorators = contextToken.parent.modifiers.filter(isDecorator) || []; @@ -157490,7 +141646,11 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} range.pos = Math.min(range.pos, contextToken.pos); } } - return { modifiers, decorators, range: range.pos !== position ? range : void 0 }; + return { + modifiers, + decorators, + range: range.pos !== position ? range : void 0 + }; } function isModifierLike2(node) { if (isModifier(node)) { @@ -157520,17 +141680,11 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} newLine: getNewLineKind(getNewLineOrDefaultFromHost(host, formatContext == null ? void 0 : formatContext.options)) }); if (formatContext) { - insertText = printer.printAndFormatSnippetList(16 /* CommaDelimited */ | 64 /* AllowTrailingComma */, factory.createNodeArray( - [method], - /*hasTrailingComma*/ - true - ), sourceFile, formatContext); + insertText = printer.printAndFormatSnippetList(16 /* CommaDelimited */ | 64 /* AllowTrailingComma */, factory.createNodeArray([method], /*hasTrailingComma*/ + true), sourceFile, formatContext); } else { - insertText = printer.printSnippetList(16 /* CommaDelimited */ | 64 /* AllowTrailingComma */, factory.createNodeArray( - [method], - /*hasTrailingComma*/ - true - ), sourceFile); + insertText = printer.printSnippetList(16 /* CommaDelimited */ | 64 /* AllowTrailingComma */, factory.createNodeArray([method], /*hasTrailingComma*/ + true), sourceFile); } const signaturePrinter = createPrinter({ removeComments: true, @@ -157538,18 +141692,17 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} target: options.target, omitTrailingSemicolon: true }); - const methodSignature = factory.createMethodSignature( - /*modifiers*/ - void 0, - /*name*/ - "", - method.questionToken, - method.typeParameters, - method.parameters, - method.type - ); - const labelDetails = { detail: signaturePrinter.printNode(4 /* Unspecified */, methodSignature, sourceFile) }; - return { isSnippet, insertText, labelDetails }; + const methodSignature = factory.createMethodSignature( /*modifiers*/ + void 0, /*name*/ + "", method.questionToken, method.typeParameters, method.parameters, method.type); + const labelDetails = { + detail: signaturePrinter.printNode(4 /* Unspecified */, methodSignature, sourceFile) + }; + return { + isSnippet, + insertText, + labelDetails + }; } function createObjectLiteralMethod(symbol, enclosingDeclaration, sourceFile, program, host, preferences) { const declarations = symbol.getDeclarations(); @@ -157558,11 +141711,8 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } const checker = program.getTypeChecker(); const declaration = declarations[0]; - const name = getSynthesizedDeepClone( - getNameOfDeclaration(declaration), - /*includeTrivia*/ - false - ); + const name = getSynthesizedDeepClone(getNameOfDeclaration(declaration), /*includeTrivia*/ + false); const type = checker.getWidenedType(checker.getTypeOfSymbolAtLocation(symbol, enclosingDeclaration)); const quotePreference = getQuotePreference(sourceFile, preferences); const builderFlags = 33554432 /* OmitThisParameter */ | (quotePreference === 0 /* Single */ ? 268435456 /* UseSingleQuotesForStringLiteralType */ : 0 /* None */); @@ -157570,69 +141720,52 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} case 171 /* PropertySignature */: case 172 /* PropertyDeclaration */: case 173 /* MethodSignature */: - case 174 /* MethodDeclaration */: { - let effectiveType = type.flags & 1048576 /* Union */ && type.types.length < 10 ? checker.getUnionType(type.types, 2 /* Subtype */) : type; - if (effectiveType.flags & 1048576 /* Union */) { - const functionTypes = filter(effectiveType.types, (type2) => checker.getSignaturesOfType(type2, 0 /* Call */).length > 0); - if (functionTypes.length === 1) { - effectiveType = functionTypes[0]; - } else { + case 174 /* MethodDeclaration */: + { + let effectiveType = type.flags & 1048576 /* Union */ && type.types.length < 10 ? checker.getUnionType(type.types, 2 /* Subtype */) : type; + if (effectiveType.flags & 1048576 /* Union */) { + const functionTypes = filter(effectiveType.types, type2 => checker.getSignaturesOfType(type2, 0 /* Call */).length > 0); + if (functionTypes.length === 1) { + effectiveType = functionTypes[0]; + } else { + return void 0; + } + } + const signatures = checker.getSignaturesOfType(effectiveType, 0 /* Call */); + if (signatures.length !== 1) { return void 0; } + const typeNode = checker.typeToTypeNode(effectiveType, enclosingDeclaration, builderFlags, ts_codefix_exports.getNoopSymbolTrackerWithResolver({ + program, + host + })); + if (!typeNode || !isFunctionTypeNode(typeNode)) { + return void 0; + } + let body; + if (preferences.includeCompletionsWithSnippetText) { + const emptyStmt = factory.createEmptyStatement(); + body = factory.createBlock([emptyStmt], /*multiLine*/ + true); + setSnippetElement(emptyStmt, { + kind: 0 /* TabStop */, + order: 0 + }); + } else { + body = factory.createBlock([], /*multiLine*/ + true); + } + const parameters = typeNode.parameters.map(typedParam => factory.createParameterDeclaration( /*modifiers*/ + void 0, typedParam.dotDotDotToken, typedParam.name, /*questionToken*/ + void 0, /*type*/ + void 0, typedParam.initializer)); + return factory.createMethodDeclaration( /*modifiers*/ + void 0, /*asteriskToken*/ + void 0, name, /*questionToken*/ + void 0, /*typeParameters*/ + void 0, parameters, /*type*/ + void 0, body); } - const signatures = checker.getSignaturesOfType(effectiveType, 0 /* Call */); - if (signatures.length !== 1) { - return void 0; - } - const typeNode = checker.typeToTypeNode(effectiveType, enclosingDeclaration, builderFlags, ts_codefix_exports.getNoopSymbolTrackerWithResolver({ program, host })); - if (!typeNode || !isFunctionTypeNode(typeNode)) { - return void 0; - } - let body; - if (preferences.includeCompletionsWithSnippetText) { - const emptyStmt = factory.createEmptyStatement(); - body = factory.createBlock( - [emptyStmt], - /*multiLine*/ - true - ); - setSnippetElement(emptyStmt, { kind: 0 /* TabStop */, order: 0 }); - } else { - body = factory.createBlock( - [], - /*multiLine*/ - true - ); - } - const parameters = typeNode.parameters.map( - (typedParam) => factory.createParameterDeclaration( - /*modifiers*/ - void 0, - typedParam.dotDotDotToken, - typedParam.name, - /*questionToken*/ - void 0, - /*type*/ - void 0, - typedParam.initializer - ) - ); - return factory.createMethodDeclaration( - /*modifiers*/ - void 0, - /*asteriskToken*/ - void 0, - name, - /*questionToken*/ - void 0, - /*typeParameters*/ - void 0, - parameters, - /*type*/ - void 0, - body - ); - } default: return void 0; } @@ -157643,14 +141776,14 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} const printer = createPrinter(printerOptions, baseWriter); const writer = { ...baseWriter, - write: (s) => escapingWrite(s, () => baseWriter.write(s)), + write: s => escapingWrite(s, () => baseWriter.write(s)), nonEscapingWrite: baseWriter.write, - writeLiteral: (s) => escapingWrite(s, () => baseWriter.writeLiteral(s)), - writeStringLiteral: (s) => escapingWrite(s, () => baseWriter.writeStringLiteral(s)), + writeLiteral: s => escapingWrite(s, () => baseWriter.writeLiteral(s)), + writeStringLiteral: s => escapingWrite(s, () => baseWriter.writeStringLiteral(s)), writeSymbol: (s, symbol) => escapingWrite(s, () => baseWriter.writeSymbol(s, symbol)), - writeParameter: (s) => escapingWrite(s, () => baseWriter.writeParameter(s)), - writeComment: (s) => escapingWrite(s, () => baseWriter.writeComment(s)), - writeProperty: (s) => escapingWrite(s, () => baseWriter.writeProperty(s)) + writeParameter: s => escapingWrite(s, () => baseWriter.writeParameter(s)), + writeComment: s => escapingWrite(s, () => baseWriter.writeComment(s)), + writeProperty: s => escapingWrite(s, () => baseWriter.writeProperty(s)) }; return { printSnippetList, @@ -157664,7 +141797,13 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} const start = baseWriter.getTextPos(); write(); const end = baseWriter.getTextPos(); - escapes = append(escapes || (escapes = []), { newText: escaped, span: { start, length: end - start } }); + escapes = append(escapes || (escapes = []), { + newText: escaped, + span: { + start, + length: end - start + } + }); } else { write(); } @@ -157681,28 +141820,20 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } function printAndFormatSnippetList(format, list, sourceFile, formatContext) { const syntheticFile = { - text: printUnescapedSnippetList( - format, - list, - sourceFile - ), + text: printUnescapedSnippetList(format, list, sourceFile), getLineAndCharacterOfPosition(pos) { return getLineAndCharacterOfPosition(this, pos); } }; const formatOptions = getFormatCodeSettingsForWriting(formatContext, sourceFile); - const changes = flatMap(list, (node) => { + const changes = flatMap(list, node => { const nodeWithPos = ts_textChanges_exports.assignPositionsToNode(node); - return ts_formatting_exports.formatNodeGivenIndentation( - nodeWithPos, - syntheticFile, - sourceFile.languageVariant, - /* indentation */ - 0, - /* delta */ - 0, - { ...formatContext, options: formatOptions } - ); + return ts_formatting_exports.formatNodeGivenIndentation(nodeWithPos, syntheticFile, sourceFile.languageVariant, /* indentation */ + 0, /* delta */ + 0, { + ...formatContext, + options: formatOptions + }); }); const allChanges = escapes ? stableSort(concatenate(changes, escapes), (a, b) => compareTextSpans(a.span, b.span)) : changes; return ts_textChanges_exports.applyChanges(syntheticFile.text, allChanges); @@ -157719,27 +141850,19 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } function printAndFormatNode(hint, node, sourceFile, formatContext) { const syntheticFile = { - text: printUnescapedNode( - hint, - node, - sourceFile - ), + text: printUnescapedNode(hint, node, sourceFile), getLineAndCharacterOfPosition(pos) { return getLineAndCharacterOfPosition(this, pos); } }; const formatOptions = getFormatCodeSettingsForWriting(formatContext, sourceFile); const nodeWithPos = ts_textChanges_exports.assignPositionsToNode(node); - const changes = ts_formatting_exports.formatNodeGivenIndentation( - nodeWithPos, - syntheticFile, - sourceFile.languageVariant, - /* indentation */ - 0, - /* delta */ - 0, - { ...formatContext, options: formatOptions } - ); + const changes = ts_formatting_exports.formatNodeGivenIndentation(nodeWithPos, syntheticFile, sourceFile.languageVariant, /* indentation */ + 0, /* delta */ + 0, { + ...formatContext, + options: formatOptions + }); const allChanges = escapes ? stableSort(concatenate(changes, escapes), (a, b) => compareTextSpans(a.span, b.span)) : changes; return ts_textChanges_exports.applyChanges(syntheticFile.text, allChanges); } @@ -157801,26 +141924,33 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} const quotedModuleSpecifier = escapeSnippetText(quote(sourceFile, preferences, origin.moduleSpecifier)); const exportKind = origin.isDefaultExport ? 1 /* Default */ : origin.exportName === "export=" /* ExportEquals */ ? 2 /* ExportEquals */ : 0 /* Named */; const tabStop = preferences.includeCompletionsWithSnippetText ? "$1" : ""; - const importKind = ts_codefix_exports.getImportKind( - sourceFile, - exportKind, - options, - /*forceImportKeyword*/ - true - ); + const importKind = ts_codefix_exports.getImportKind(sourceFile, exportKind, options, /*forceImportKeyword*/ + true); const isImportSpecifierTypeOnly = importStatementCompletion.couldBeTypeOnlyImportSpecifier; const topLevelTypeOnlyText = importStatementCompletion.isTopLevelTypeOnly ? ` ${tokenToString(156 /* TypeKeyword */)} ` : " "; const importSpecifierTypeOnlyText = isImportSpecifierTypeOnly ? `${tokenToString(156 /* TypeKeyword */)} ` : ""; const suffix = useSemicolons ? ";" : ""; switch (importKind) { case 3 /* CommonJS */: - return { replacementSpan, insertText: `import${topLevelTypeOnlyText}${escapeSnippetText(name)}${tabStop} = require(${quotedModuleSpecifier})${suffix}` }; + return { + replacementSpan, + insertText: `import${topLevelTypeOnlyText}${escapeSnippetText(name)}${tabStop} = require(${quotedModuleSpecifier})${suffix}` + }; case 1 /* Default */: - return { replacementSpan, insertText: `import${topLevelTypeOnlyText}${escapeSnippetText(name)}${tabStop} from ${quotedModuleSpecifier}${suffix}` }; + return { + replacementSpan, + insertText: `import${topLevelTypeOnlyText}${escapeSnippetText(name)}${tabStop} from ${quotedModuleSpecifier}${suffix}` + }; case 2 /* Namespace */: - return { replacementSpan, insertText: `import${topLevelTypeOnlyText}* as ${escapeSnippetText(name)} from ${quotedModuleSpecifier}${suffix}` }; + return { + replacementSpan, + insertText: `import${topLevelTypeOnlyText}* as ${escapeSnippetText(name)} from ${quotedModuleSpecifier}${suffix}` + }; case 0 /* Named */: - return { replacementSpan, insertText: `import${topLevelTypeOnlyText}{ ${importSpecifierTypeOnlyText}${escapeSnippetText(name)}${tabStop} } from ${quotedModuleSpecifier}${suffix}` }; + return { + replacementSpan, + insertText: `import${topLevelTypeOnlyText}{ ${importSpecifierTypeOnlyText}${escapeSnippetText(name)}${tabStop} } from ${quotedModuleSpecifier}${suffix}` + }; } } function quotePropertyName(sourceFile, preferences, name) { @@ -157842,81 +141972,58 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if ((origin == null ? void 0 : origin.kind) === 1 /* ThisType */) { return "ThisProperty/" /* ThisProperty */; } + if ((origin == null ? void 0 : origin.kind) === 64 /* TypeOnlyAlias */) { return "TypeOnlyAlias/" /* TypeOnlyAlias */; } } + function getCompletionEntriesFromSymbols(symbols, entries, replacementToken, contextToken, location, position, sourceFile, host, program, target, log, kind, preferences, compilerOptions, formatContext, isTypeOnlyLocation, propertyAccessToConvert, jsxIdentifierExpected, isJsxInitializer, importStatementCompletion, recommendedCompletion, symbolToOriginInfoMap, symbolToSortTextMap, isJsxIdentifierExpected, isRightOfOpenTag, includeSymbol = false) { const start = timestamp(); const variableOrParameterDeclaration = getVariableOrParameterDeclaration(contextToken, location); const useSemicolons = probablyUsesSemicolons(sourceFile); const typeChecker = program.getTypeChecker(); - const uniques = /* @__PURE__ */ new Map(); + const uniques = /* @__PURE__ */new Map(); for (let i = 0; i < symbols.length; i++) { + var _ref46; const symbol = symbols[i]; const origin = symbolToOriginInfoMap == null ? void 0 : symbolToOriginInfoMap[i]; const info = getCompletionEntryDisplayNameForSymbol(symbol, target, origin, kind, !!jsxIdentifierExpected); if (!info || uniques.get(info.name) && (!origin || !originIsObjectLiteralMethod(origin)) || kind === 1 /* Global */ && symbolToSortTextMap && !shouldIncludeSymbol(symbol, symbolToSortTextMap)) { continue; } - const { name, needsConvertPropertyAccess } = info; - const originalSortText = (symbolToSortTextMap == null ? void 0 : symbolToSortTextMap[getSymbolId(symbol)]) ?? SortText.LocationPriority; - const sortText = isDeprecated(symbol, typeChecker) ? SortText.Deprecated(originalSortText) : originalSortText; - const entry = createCompletionEntry( - symbol, - sortText, - replacementToken, - contextToken, - location, - position, - sourceFile, - host, - program, + const { name, - needsConvertPropertyAccess, - origin, - recommendedCompletion, - propertyAccessToConvert, - isJsxInitializer, - importStatementCompletion, - useSemicolons, - compilerOptions, - preferences, - kind, - formatContext, - isJsxIdentifierExpected, - isRightOfOpenTag, - includeSymbol - ); + needsConvertPropertyAccess + } = info; + const originalSortText = (_ref46 = symbolToSortTextMap == null ? void 0 : symbolToSortTextMap[getSymbolId(symbol)]) !== null && _ref46 !== void 0 ? _ref46 : SortText.LocationPriority; + const sortText = isDeprecated(symbol, typeChecker) ? SortText.Deprecated(originalSortText) : originalSortText; + const entry = createCompletionEntry(symbol, sortText, replacementToken, contextToken, location, position, sourceFile, host, program, name, needsConvertPropertyAccess, origin, recommendedCompletion, propertyAccessToConvert, isJsxInitializer, importStatementCompletion, useSemicolons, compilerOptions, preferences, kind, formatContext, isJsxIdentifierExpected, isRightOfOpenTag, includeSymbol); if (!entry) { continue; } - const shouldShadowLaterSymbols = (!origin || originIsTypeOnlyAlias(origin)) && !(symbol.parent === void 0 && !some(symbol.declarations, (d) => d.getSourceFile() === location.getSourceFile())); + const shouldShadowLaterSymbols = (!origin || originIsTypeOnlyAlias(origin)) && !(symbol.parent === void 0 && !some(symbol.declarations, d => d.getSourceFile() === location.getSourceFile())); uniques.set(name, shouldShadowLaterSymbols); - insertSorted( - entries, - entry, - compareCompletionEntries, - /*allowDuplicates*/ - true - ); + insertSorted(entries, entry, compareCompletionEntries, /*allowDuplicates*/ + true); } log("getCompletionsAtPosition: getCompletionEntriesFromSymbols: " + (timestamp() - start)); return { - has: (name) => uniques.has(name), - add: (name) => uniques.set(name, true) + has: name => uniques.has(name), + add: name => uniques.set(name, true) }; function shouldIncludeSymbol(symbol, symbolToSortTextMap2) { var _a; let allFlags = symbol.flags; if (!isSourceFile(location)) { + var _symbol$valueDeclarat; if (isExportAssignment(location.parent)) { return true; } if (tryCast(variableOrParameterDeclaration, isVariableDeclaration) && symbol.valueDeclaration === variableOrParameterDeclaration) { return false; } - const symbolDeclaration = symbol.valueDeclaration ?? ((_a = symbol.declarations) == null ? void 0 : _a[0]); + const symbolDeclaration = (_symbol$valueDeclarat = symbol.valueDeclaration) !== null && _symbol$valueDeclarat !== void 0 ? _symbol$valueDeclarat : (_a = symbol.declarations) == null ? void 0 : _a[0]; if (variableOrParameterDeclaration && symbolDeclaration && (isTypeParameterDeclaration(variableOrParameterDeclaration) && isTypeParameterDeclaration(symbolDeclaration) || isParameter(variableOrParameterDeclaration) && isParameter(symbolDeclaration))) { const symbolDeclarationPos = symbolDeclaration.pos; const parameters = isParameter(variableOrParameterDeclaration) ? variableOrParameterDeclaration.parent.parameters : isInferTypeNode(variableOrParameterDeclaration.parent) ? void 0 : variableOrParameterDeclaration.parent.typeParameters; @@ -157932,6 +142039,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (isInRightSideOfInternalImportEqualsDeclaration(location)) { return !!(allFlags & 1920 /* Namespace */); } + if (isTypeOnlyLocation) { return symbolCanBeReferencedAtTypeLocation(symbol, typeChecker); } @@ -157939,15 +142047,21 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return !!(allFlags & 111551 /* Value */); } } + function getLabelCompletionAtPosition(node) { const entries = getLabelStatementCompletions(node); if (entries.length) { - return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries }; + return { + isGlobalCompletion: false, + isMemberCompletion: false, + isNewIdentifierLocation: false, + entries + }; } } function getLabelStatementCompletions(node) { const entries = []; - const uniques = /* @__PURE__ */ new Map(); + const uniques = /* @__PURE__ */new Map(); let current = node; while (current) { if (isFunctionLike(current)) { @@ -157971,12 +142085,17 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } function getSymbolCompletionFromEntryId(program, log, sourceFile, position, entryId, host, preferences) { if (entryId.source === "SwitchCases/" /* SwitchCases */) { - return { type: "cases" }; + return { + type: "cases" + }; } if (entryId.data) { const autoImport = getAutoImportSymbolFromCompletionEntryData(entryId.name, entryId.data, program, host); if (autoImport) { - const { contextToken: contextToken2, previousToken: previousToken2 } = getRelevantTokens(position, sourceFile); + const { + contextToken: contextToken2, + previousToken: previousToken2 + } = getRelevantTokens(position, sourceFile); return { type: "symbol", symbol: autoImport.symbol, @@ -157990,108 +142109,150 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } } const compilerOptions = program.getCompilerOptions(); - const completionData = getCompletionData( - program, - log, - sourceFile, - compilerOptions, - position, - { includeCompletionsForModuleExports: true, includeCompletionsWithInsertText: true }, - entryId, - host, - /*formatContext*/ - void 0 - ); + const completionData = getCompletionData(program, log, sourceFile, compilerOptions, position, { + includeCompletionsForModuleExports: true, + includeCompletionsWithInsertText: true + }, entryId, host, /*formatContext*/ + void 0); if (!completionData) { - return { type: "none" }; + return { + type: "none" + }; } if (completionData.kind !== 0 /* Data */) { - return { type: "request", request: completionData }; + return { + type: "request", + request: completionData + }; } - 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 }; + 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 + }; return firstDefined(symbols, (symbol, index) => { const origin = symbolToOriginInfoMap[index]; const info = getCompletionEntryDisplayNameForSymbol(symbol, getEmitScriptTarget(compilerOptions), origin, completionKind, completionData.isJsxIdentifierExpected); - return info && info.name === entryId.name && (entryId.source === "ClassMemberSnippet/" /* ClassMemberSnippet */ && symbol.flags & 106500 /* ClassMember */ || entryId.source === "ObjectLiteralMethodSnippet/" /* ObjectLiteralMethodSnippet */ && symbol.flags & (4 /* Property */ | 8192 /* Method */) || getSourceFromOrigin(origin) === entryId.source || entryId.source === "ObjectLiteralMemberWithComma/" /* ObjectLiteralMemberWithComma */) ? { type: "symbol", symbol, location, origin, contextToken, previousToken, isJsxInitializer, isTypeOnlyLocation } : void 0; - }) || { type: "none" }; + return info && info.name === entryId.name && (entryId.source === "ClassMemberSnippet/" /* ClassMemberSnippet */ && symbol.flags & 106500 /* ClassMember */ || entryId.source === "ObjectLiteralMethodSnippet/" /* ObjectLiteralMethodSnippet */ && symbol.flags & (4 /* Property */ | 8192 /* Method */) || getSourceFromOrigin(origin) === entryId.source || entryId.source === "ObjectLiteralMemberWithComma/" /* ObjectLiteralMemberWithComma */) ? { + type: "symbol", + symbol, + location, + origin, + contextToken, + previousToken, + isJsxInitializer, + isTypeOnlyLocation + } : void 0; + }) || { + type: "none" + }; } function getCompletionEntryDetails(program, log, sourceFile, position, entryId, host, formatContext, preferences, cancellationToken) { const typeChecker = program.getTypeChecker(); const compilerOptions = program.getCompilerOptions(); - const { name, source, data } = entryId; - const { previousToken, contextToken } = getRelevantTokens(position, sourceFile); + const { + name, + source, + data + } = entryId; + const { + previousToken, + contextToken + } = getRelevantTokens(position, sourceFile); if (isInString(sourceFile, position, previousToken)) { return ts_Completions_StringCompletions_exports.getStringLiteralCompletionDetails(name, sourceFile, position, previousToken, typeChecker, compilerOptions, host, cancellationToken, preferences); } const symbolCompletion = getSymbolCompletionFromEntryId(program, log, sourceFile, position, entryId, host, preferences); switch (symbolCompletion.type) { - case "request": { - const { request } = symbolCompletion; - switch (request.kind) { - case 1 /* JsDocTagName */: - return ts_JsDoc_exports.getJSDocTagNameCompletionDetails(name); - case 2 /* JsDocTag */: - return ts_JsDoc_exports.getJSDocTagCompletionDetails(name); - case 3 /* JsDocParameterName */: - return ts_JsDoc_exports.getJSDocParameterNameCompletionDetails(name); - case 4 /* Keywords */: - return some(request.keywordCompletions, (c) => c.name === name) ? createSimpleDetails(name, "keyword" /* keyword */, 5 /* keyword */) : void 0; - default: - return Debug.assertNever(request); + case "request": + { + const { + request + } = symbolCompletion; + switch (request.kind) { + case 1 /* JsDocTagName */: + return ts_JsDoc_exports.getJSDocTagNameCompletionDetails(name); + case 2 /* JsDocTag */: + return ts_JsDoc_exports.getJSDocTagCompletionDetails(name); + case 3 /* JsDocParameterName */: + return ts_JsDoc_exports.getJSDocParameterNameCompletionDetails(name); + case 4 /* Keywords */: + return some(request.keywordCompletions, c => c.name === name) ? createSimpleDetails(name, "keyword" /* keyword */, 5 /* keyword */) : void 0; + default: + return Debug.assertNever(request); + } } - } - case "symbol": { - const { symbol, location, contextToken: contextToken2, origin, previousToken: previousToken2 } = symbolCompletion; - const { codeActions, sourceDisplay } = getCompletionEntryCodeActionsAndSourceDisplay(name, location, contextToken2, origin, symbol, program, host, compilerOptions, sourceFile, position, previousToken2, formatContext, preferences, data, source, cancellationToken); - const symbolName2 = originIsComputedPropertyName(origin) ? origin.symbolName : symbol.name; - return createCompletionDetailsForSymbol(symbol, symbolName2, typeChecker, sourceFile, location, cancellationToken, codeActions, sourceDisplay); - } - case "literal": { - const { literal } = symbolCompletion; - return createSimpleDetails(completionNameForLiteral(sourceFile, preferences, literal), "string" /* string */, typeof literal === "string" ? 8 /* stringLiteral */ : 7 /* numericLiteral */); - } - case "cases": { - const snippets = getExhaustiveCaseSnippets( - contextToken.parent, - sourceFile, - preferences, - program.getCompilerOptions(), - host, - program, - /*formatContext*/ - void 0 - ); - if (snippets == null ? void 0 : snippets.importAdder.hasFixes()) { - const { entry, importAdder } = snippets; - const changes = ts_textChanges_exports.ChangeTracker.with( - { host, formatContext, preferences }, - importAdder.writeFixes - ); + case "symbol": + { + const { + symbol, + location, + contextToken: contextToken2, + origin, + previousToken: previousToken2 + } = symbolCompletion; + const { + codeActions, + sourceDisplay + } = getCompletionEntryCodeActionsAndSourceDisplay(name, location, contextToken2, origin, symbol, program, host, compilerOptions, sourceFile, position, previousToken2, formatContext, preferences, data, source, cancellationToken); + const symbolName2 = originIsComputedPropertyName(origin) ? origin.symbolName : symbol.name; + return createCompletionDetailsForSymbol(symbol, symbolName2, typeChecker, sourceFile, location, cancellationToken, codeActions, sourceDisplay); + } + case "literal": + { + const { + literal + } = symbolCompletion; + return createSimpleDetails(completionNameForLiteral(sourceFile, preferences, literal), "string" /* string */, typeof literal === "string" ? 8 /* stringLiteral */ : 7 /* numericLiteral */); + } + + case "cases": + { + const snippets = getExhaustiveCaseSnippets(contextToken.parent, sourceFile, preferences, program.getCompilerOptions(), host, program, /*formatContext*/ + void 0); + if (snippets == null ? void 0 : snippets.importAdder.hasFixes()) { + const { + entry, + importAdder + } = snippets; + const changes = ts_textChanges_exports.ChangeTracker.with({ + host, + formatContext, + preferences + }, importAdder.writeFixes); + return { + name: entry.name, + kind: "" /* unknown */, + kindModifiers: "", + displayParts: [], + sourceDisplay: void 0, + codeActions: [{ + changes, + description: diagnosticToString([Diagnostics.Includes_imports_of_types_referenced_by_0, name]) + }] + }; + } return { - name: entry.name, + name, kind: "" /* unknown */, kindModifiers: "", displayParts: [], - sourceDisplay: void 0, - codeActions: [{ - changes, - description: diagnosticToString([Diagnostics.Includes_imports_of_types_referenced_by_0, name]) - }] + sourceDisplay: void 0 }; } - return { - name, - kind: "" /* unknown */, - kindModifiers: "", - displayParts: [], - sourceDisplay: void 0 - }; - } case "none": - return allKeywordsCompletions().some((c) => c.name === name) ? createSimpleDetails(name, "keyword" /* keyword */, 5 /* keyword */) : void 0; + return allKeywordsCompletions().some(c => c.name === name) ? createSimpleDetails(name, "keyword" /* keyword */, 5 /* keyword */) : void 0; default: Debug.assertNever(symbolCompletion); } @@ -158100,43 +142261,54 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return createCompletionDetails(name, "" /* none */, kind, [displayPart(name, kind2)]); } function createCompletionDetailsForSymbol(symbol, name, checker, sourceFile, location, cancellationToken, codeActions, sourceDisplay) { - const { displayParts, documentation, symbolKind, tags } = checker.runWithCancellationToken(cancellationToken, (checker2) => ts_SymbolDisplay_exports.getSymbolDisplayPartsDocumentationAndSymbolKind(checker2, symbol, sourceFile, location, location, 7 /* All */)); + const { + displayParts, + documentation, + symbolKind, + tags + } = checker.runWithCancellationToken(cancellationToken, checker2 => ts_SymbolDisplay_exports.getSymbolDisplayPartsDocumentationAndSymbolKind(checker2, symbol, sourceFile, location, location, 7 /* All */)); return createCompletionDetails(name, ts_SymbolDisplay_exports.getSymbolModifiers(checker, symbol), symbolKind, displayParts, documentation, tags, codeActions, sourceDisplay); } function createCompletionDetails(name, kindModifiers, kind, displayParts, documentation, tags, codeActions, source) { - return { name, kindModifiers, kind, displayParts, documentation, tags, codeActions, source, sourceDisplay: source }; + return { + name, + kindModifiers, + kind, + displayParts, + documentation, + tags, + codeActions, + source, + sourceDisplay: source + }; } function getCompletionEntryCodeActionsAndSourceDisplay(name, location, contextToken, origin, symbol, program, host, compilerOptions, sourceFile, position, previousToken, formatContext, preferences, data, source, cancellationToken) { if (data == null ? void 0 : data.moduleSpecifier) { if (previousToken && getImportStatementCompletionInfo(contextToken || previousToken, sourceFile).replacementSpan) { - return { codeActions: void 0, sourceDisplay: [textPart(data.moduleSpecifier)] }; + return { + codeActions: void 0, + sourceDisplay: [textPart(data.moduleSpecifier)] + }; } } if (source === "ClassMemberSnippet/" /* ClassMemberSnippet */) { - const { importAdder, eraseRange } = getEntryForMemberCompletion( - host, - program, - compilerOptions, - preferences, - name, - symbol, - location, - position, - contextToken, - formatContext - ); + const { + importAdder, + eraseRange + } = getEntryForMemberCompletion(host, program, compilerOptions, preferences, name, symbol, location, position, contextToken, formatContext); if (importAdder || eraseRange) { - const changes = ts_textChanges_exports.ChangeTracker.with( - { host, formatContext, preferences }, - (tracker) => { - if (importAdder) { - importAdder.writeFixes(tracker); - } - if (eraseRange) { - tracker.deleteRange(sourceFile, eraseRange); - } + const changes = ts_textChanges_exports.ChangeTracker.with({ + host, + formatContext, + preferences + }, tracker => { + if (importAdder) { + importAdder.writeFixes(tracker); } - ); + if (eraseRange) { + tracker.deleteRange(sourceFile, eraseRange); + } + }); return { sourceDisplay: void 0, codeActions: [{ @@ -158147,22 +142319,19 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } } if (originIsTypeOnlyAlias(origin)) { - const codeAction2 = ts_codefix_exports.getPromoteTypeOnlyCompletionAction( - sourceFile, - origin.declaration.name, - program, + const codeAction2 = ts_codefix_exports.getPromoteTypeOnlyCompletionAction(sourceFile, origin.declaration.name, program, host, formatContext, preferences); + Debug.assertIsDefined(codeAction2, "Expected to have a code action for promoting type-only alias"); + return { + codeActions: [codeAction2], + sourceDisplay: void 0 + }; + } + if (source === "ObjectLiteralMemberWithComma/" /* ObjectLiteralMemberWithComma */ && contextToken) { + const changes = ts_textChanges_exports.ChangeTracker.with({ host, formatContext, preferences - ); - Debug.assertIsDefined(codeAction2, "Expected to have a code action for promoting type-only alias"); - return { codeActions: [codeAction2], sourceDisplay: void 0 }; - } - if (source === "ObjectLiteralMemberWithComma/" /* ObjectLiteralMemberWithComma */ && contextToken) { - const changes = ts_textChanges_exports.ChangeTracker.with( - { host, formatContext, preferences }, - (tracker) => tracker.insertText(sourceFile, contextToken.end, ",") - ); + }, tracker => tracker.insertText(sourceFile, contextToken.end, ",")); if (changes) { return { sourceDisplay: void 0, @@ -158174,41 +142343,41 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } } if (!origin || !(originIsExport(origin) || originIsResolvedExport(origin))) { - return { codeActions: void 0, sourceDisplay: void 0 }; + return { + codeActions: void 0, + sourceDisplay: void 0 + }; } const checker = origin.isFromPackageJson ? host.getPackageJsonAutoImportProvider().getTypeChecker() : program.getTypeChecker(); - const { moduleSymbol } = origin; + const { + moduleSymbol + } = origin; const targetSymbol = checker.getMergedSymbol(skipAlias(symbol.exportSymbol || symbol, checker)); const isJsxOpeningTagName = (contextToken == null ? void 0 : contextToken.kind) === 30 /* LessThanToken */ && isJsxOpeningLikeElement(contextToken.parent); - const { moduleSpecifier, codeAction } = ts_codefix_exports.getImportCompletionAction( - targetSymbol, - moduleSymbol, - data == null ? void 0 : data.exportMapKey, - sourceFile, - name, - isJsxOpeningTagName, - host, - program, - formatContext, - previousToken && isIdentifier(previousToken) ? previousToken.getStart(sourceFile) : position, - preferences, - cancellationToken - ); + const { + moduleSpecifier, + codeAction + } = ts_codefix_exports.getImportCompletionAction(targetSymbol, moduleSymbol, data == null ? void 0 : data.exportMapKey, sourceFile, name, isJsxOpeningTagName, host, program, formatContext, previousToken && isIdentifier(previousToken) ? previousToken.getStart(sourceFile) : position, preferences, cancellationToken); Debug.assert(!(data == null ? void 0 : data.moduleSpecifier) || moduleSpecifier === data.moduleSpecifier); - return { sourceDisplay: [textPart(moduleSpecifier)], codeActions: [codeAction] }; + return { + sourceDisplay: [textPart(moduleSpecifier)], + codeActions: [codeAction] + }; } function getCompletionEntrySymbol(program, log, sourceFile, position, entryId, host, preferences) { const completion = getSymbolCompletionFromEntryId(program, log, sourceFile, position, entryId, host, preferences); return completion.type === "symbol" ? completion.symbol : void 0; } function getRecommendedCompletion(previousToken, contextualType, checker) { - return firstDefined(contextualType && (contextualType.isUnion() ? contextualType.types : [contextualType]), (type) => { + return firstDefined(contextualType && (contextualType.isUnion() ? contextualType.types : [contextualType]), type => { const symbol = type && type.symbol; - return symbol && (symbol.flags & (8 /* EnumMember */ | 384 /* Enum */ | 32 /* Class */) && !isAbstractConstructorSymbol(symbol)) ? getFirstSymbolInChain(symbol, previousToken, checker) : void 0; + return symbol && symbol.flags & (8 /* EnumMember */ | 384 /* Enum */ | 32 /* Class */) && !isAbstractConstructorSymbol(symbol) ? getFirstSymbolInChain(symbol, previousToken, checker) : void 0; }); } function getContextualType(previousToken, position, sourceFile, checker) { - const { parent: parent2 } = previousToken; + const { + parent: parent2 + } = previousToken; switch (previousToken.kind) { case 80 /* Identifier */: return getContextualTypeFromParent(previousToken, checker); @@ -158232,32 +142401,25 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return isJsxExpression(parent2) && !isJsxElement(parent2.parent) && !isJsxFragment(parent2.parent) ? checker.getContextualTypeForJsxAttribute(parent2.parent) : void 0; default: const argInfo = ts_SignatureHelp_exports.getArgumentInfoForCompletions(previousToken, position, sourceFile); - return argInfo ? ( - // At `,`, treat this as the next argument after the comma. - checker.getContextualTypeForArgumentAtIndex(argInfo.invocation, argInfo.argumentIndex + (previousToken.kind === 28 /* CommaToken */ ? 1 : 0)) - ) : isEqualityOperatorKind(previousToken.kind) && isBinaryExpression(parent2) && isEqualityOperatorKind(parent2.operatorToken.kind) ? ( - // completion at `x ===/**/` should be for the right side - checker.getTypeAtLocation(parent2.left) - ) : checker.getContextualType(previousToken, 4 /* Completions */) || checker.getContextualType(previousToken); + return argInfo ? + // At `,`, treat this as the next argument after the comma. + checker.getContextualTypeForArgumentAtIndex(argInfo.invocation, argInfo.argumentIndex + (previousToken.kind === 28 /* CommaToken */ ? 1 : 0)) : isEqualityOperatorKind(previousToken.kind) && isBinaryExpression(parent2) && isEqualityOperatorKind(parent2.operatorToken.kind) ? + // completion at `x ===/**/` should be for the right side + checker.getTypeAtLocation(parent2.left) : checker.getContextualType(previousToken, 4 /* Completions */) || checker.getContextualType(previousToken); } } function getFirstSymbolInChain(symbol, enclosingDeclaration, checker) { - const chain = checker.getAccessibleSymbolChain( - symbol, - enclosingDeclaration, - /*meaning*/ - 67108863 /* All */, - /*useOnlyExternalAliasing*/ - false - ); - if (chain) - return first(chain); + const chain = checker.getAccessibleSymbolChain(symbol, enclosingDeclaration, /*meaning*/ + 67108863 /* All */, /*useOnlyExternalAliasing*/ + false); + if (chain) return first(chain); return symbol.parent && (isModuleSymbol(symbol.parent) ? symbol : getFirstSymbolInChain(symbol.parent, enclosingDeclaration, checker)); } function isModuleSymbol(symbol) { var _a; - return !!((_a = symbol.declarations) == null ? void 0 : _a.some((d) => d.kind === 312 /* SourceFile */)); + return !!((_a = symbol.declarations) == null ? void 0 : _a.some(d => d.kind === 312 /* SourceFile */)); } + function getCompletionData(program, log, sourceFile, compilerOptions, position, preferences, detailsEntryId, host, formatContext, cancellationToken) { const typeChecker = program.getTypeChecker(); const inCheckedFile = isCheckedFile(sourceFile, compilerOptions); @@ -158272,19 +142434,27 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (insideComment) { if (hasDocComment(sourceFile, position)) { if (sourceFile.text.charCodeAt(position - 1) === 64 /* at */) { - return { kind: 1 /* JsDocTagName */ }; + return { + kind: 1 /* JsDocTagName */ + }; } else { const lineStart = getLineStartPositionForPosition(position, sourceFile); if (!/[^*|\s(/)]/.test(sourceFile.text.substring(lineStart, position))) { - return { kind: 2 /* JsDocTag */ }; + return { + kind: 2 /* JsDocTag */ + }; } } } + const tag = getJsDocTagAtPosition(currentToken, position); if (tag) { if (tag.tagName.pos <= position && position <= tag.tagName.end) { - return { kind: 1 /* JsDocTagName */ }; + return { + kind: 1 /* JsDocTagName */ + }; } + const typeExpression = tryGetTypeExpressionFromTag(tag); if (typeExpression) { currentToken = getTokenAtPosition(sourceFile, position); @@ -158293,7 +142463,10 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } } if (!insideJsDocTagTypeExpression && isJSDocParameterTag(tag) && (nodeIsMissing(tag.name) || tag.name.pos <= position && position <= tag.name.end)) { - return { kind: 3 /* JsDocParameterName */, tag }; + return { + kind: 3 /* JsDocParameterName */, + tag + }; } } if (!insideJsDocTagTypeExpression) { @@ -158442,9 +142615,9 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} let importSpecifierResolver; const symbolToOriginInfoMap = []; const symbolToSortTextMap = []; - const seenPropertySymbols = /* @__PURE__ */ new Map(); + const seenPropertySymbols = /* @__PURE__ */new Map(); const isTypeOnlyLocation = isTypeOnlyCompletion(); - const getModuleSpecifierResolutionHost = memoizeOne((isFromPackageJson) => { + const getModuleSpecifierResolutionHost = memoizeOne(isFromPackageJson => { return createModuleSpecifierResolutionHost(isFromPackageJson ? host.getPackageJsonAutoImportProvider() : program, host); }); if (isRightOfDot || isRightOfQuestionDot) { @@ -158471,10 +142644,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} log("getCompletionData: Semantic work: " + (timestamp() - semanticStart)); const contextualType = previousToken && getContextualType(previousToken, position, sourceFile, typeChecker); const isLiteralExpected = !tryCast(previousToken, isStringLiteralLike) && !isJsxIdentifierExpected; - const literals = !isLiteralExpected ? [] : mapDefined( - contextualType && (contextualType.isUnion() ? contextualType.types : [contextualType]), - (t) => t.isLiteral() && !(t.flags & 1024 /* EnumLiteral */) ? t.value : void 0 - ); + const literals = !isLiteralExpected ? [] : mapDefined(contextualType && (contextualType.isUnion() ? contextualType.types : [contextualType]), t => t.isLiteral() && !(t.flags & 1024 /* EnumLiteral */) ? t.value : void 0); const recommendedCompletion = previousToken && contextualType && getRecommendedCompletion(previousToken, contextualType, typeChecker); return { kind: 0 /* Data */, @@ -158534,29 +142704,27 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} 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); if (symbol.flags & (1536 /* Module */ | 384 /* Enum */)) { const exportedSymbols = typeChecker.getExportsOfModule(symbol); Debug.assertEachIsDefined(exportedSymbols, "getExportsOfModule() should all be defined"); - const isValidValueAccess = (symbol2) => typeChecker.isValidPropertyAccess(isImportType ? node : node.parent, symbol2.name); - const isValidTypeAccess = (symbol2) => symbolCanBeReferencedAtTypeLocation(symbol2, typeChecker); - const isValidAccess = isNamespaceName ? (symbol2) => { + const isValidValueAccess = symbol2 => typeChecker.isValidPropertyAccess(isImportType ? node : node.parent, symbol2.name); + const isValidTypeAccess = symbol2 => symbolCanBeReferencedAtTypeLocation(symbol2, typeChecker); + const isValidAccess = isNamespaceName ? symbol2 => { var _a; - return !!(symbol2.flags & 1920 /* Namespace */) && !((_a = symbol2.declarations) == null ? void 0 : _a.every((d) => d.parent === node.parent)); - } : isRhsOfImportDeclaration ? ( - // Any kind is allowed when dotting off namespace in internal import equals declaration - (symbol2) => isValidTypeAccess(symbol2) || isValidValueAccess(symbol2) - ) : isTypeLocation || insideJsDocTagTypeExpression ? isValidTypeAccess : isValidValueAccess; + return !!(symbol2.flags & 1920 /* Namespace */) && !((_a = symbol2.declarations) == null ? void 0 : _a.every(d => d.parent === node.parent)); + } : isRhsOfImportDeclaration ? + // Any kind is allowed when dotting off namespace in internal import equals declaration + symbol2 => isValidTypeAccess(symbol2) || isValidValueAccess(symbol2) : isTypeLocation || insideJsDocTagTypeExpression ? isValidTypeAccess : isValidValueAccess; for (const exportedSymbol of exportedSymbols) { if (isValidAccess(exportedSymbol)) { symbols.push(exportedSymbol); } } - if (!isTypeLocation && !insideJsDocTagTypeExpression && symbol.declarations && symbol.declarations.some((d) => d.kind !== 312 /* SourceFile */ && d.kind !== 267 /* ModuleDeclaration */ && d.kind !== 266 /* EnumDeclaration */)) { + if (!isTypeLocation && !insideJsDocTagTypeExpression && symbol.declarations && symbol.declarations.some(d => d.kind !== 312 /* SourceFile */ && d.kind !== 267 /* ModuleDeclaration */ && d.kind !== 266 /* EnumDeclaration */)) { let type = typeChecker.getTypeOfSymbolAtLocation(symbol, node).getNonOptionalType(); let insertQuestionDot = false; if (type.isNullableType()) { @@ -158575,11 +142743,8 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } } if (!isTypeLocation || isInTypeQuery(node)) { - typeChecker.tryGetThisTypeAt( - node, - /*includeGlobalThis*/ - false - ); + typeChecker.tryGetThisTypeAt(node, /*includeGlobalThis*/ + false); let type = typeChecker.getTypeAtLocation(node).getNonOptionalType(); if (!isTypeLocation) { let insertQuestionDot = false; @@ -158594,13 +142759,9 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } addTypeProperties(type, !!(node.flags & 65536 /* AwaitContext */), insertQuestionDot); } else { - addTypeProperties( - type.getNonNullableType(), - /*insertAwait*/ - false, - /*insertQuestionDot*/ - false - ); + addTypeProperties(type.getNonNullableType(), /*insertAwait*/ + false, /*insertQuestionDot*/ + false); } } } @@ -158613,28 +142774,20 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (inCheckedFile) { for (const symbol of type.getApparentProperties()) { if (typeChecker.isValidPropertyAccessForCompletions(propertyAccess, type, symbol)) { - addPropertySymbol( - symbol, - /*insertAwait*/ - false, - insertQuestionDot - ); + addPropertySymbol(symbol, /*insertAwait*/ + false, insertQuestionDot); } } } else { - symbols.push(...filter(getPropertiesForCompletion(type, typeChecker), (s) => typeChecker.isValidPropertyAccessForCompletions(propertyAccess, type, s))); + symbols.push(...filter(getPropertiesForCompletion(type, typeChecker), s => typeChecker.isValidPropertyAccessForCompletions(propertyAccess, type, s))); } if (insertAwait && preferences.includeCompletionsWithInsertText) { const promiseType = typeChecker.getPromisedTypeOfPromise(type); if (promiseType) { for (const symbol of promiseType.getApparentProperties()) { if (typeChecker.isValidPropertyAccessForCompletions(propertyAccess, promiseType, symbol)) { - addPropertySymbol( - symbol, - /*insertAwait*/ - true, - insertQuestionDot - ); + addPropertySymbol(symbol, /*insertAwait*/ + true, insertQuestionDot); } } } @@ -158642,7 +142795,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } function addPropertySymbol(symbol, insertAwait, insertQuestionDot) { var _a; - const computedPropertyName = firstDefined(symbol.declarations, (decl) => tryCast(getNameOfDeclaration(decl), isComputedPropertyName)); + const computedPropertyName = firstDefined(symbol.declarations, decl => tryCast(getNameOfDeclaration(decl), isComputedPropertyName)); if (computedPropertyName) { const leftMostName = getLeftMostName(computedPropertyName.expression); const nameSymbol = leftMostName && typeChecker.getSymbolAtLocation(leftMostName); @@ -158653,21 +142806,21 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} symbols.push(firstAccessibleSymbol); const moduleSymbol = firstAccessibleSymbol.parent; if (!moduleSymbol || !isExternalModuleSymbol(moduleSymbol) || typeChecker.tryGetMemberInModuleExportsAndProperties(firstAccessibleSymbol.name, moduleSymbol) !== firstAccessibleSymbol) { - symbolToOriginInfoMap[index] = { kind: getNullableSymbolOriginInfoKind(2 /* SymbolMemberNoExport */) }; + symbolToOriginInfoMap[index] = { + kind: getNullableSymbolOriginInfoKind(2 /* SymbolMemberNoExport */) + }; } else { const fileName = isExternalModuleNameRelative(stripQuotes(moduleSymbol.name)) ? (_a = getSourceFileOfModule(moduleSymbol)) == null ? void 0 : _a.fileName : void 0; - const { moduleSpecifier } = (importSpecifierResolver || (importSpecifierResolver = ts_codefix_exports.createImportSpecifierResolver(sourceFile, program, host, preferences))).getModuleSpecifierForBestExportInfo( - [{ - exportKind: 0 /* Named */, - moduleFileName: fileName, - isFromPackageJson: false, - moduleSymbol, - symbol: firstAccessibleSymbol, - targetFlags: skipAlias(firstAccessibleSymbol, typeChecker).flags - }], - position, - isValidTypeOnlyAliasUseSite(location) - ) || {}; + const { + moduleSpecifier + } = (importSpecifierResolver || (importSpecifierResolver = ts_codefix_exports.createImportSpecifierResolver(sourceFile, program, host, preferences))).getModuleSpecifierForBestExportInfo([{ + exportKind: 0 /* Named */, + moduleFileName: fileName, + isFromPackageJson: false, + moduleSymbol, + symbol: firstAccessibleSymbol, + targetFlags: skipAlias(firstAccessibleSymbol, typeChecker).flags + }], position, isValidTypeOnlyAliasUseSite(location)) || {}; if (moduleSpecifier) { const origin = { kind: getNullableSymbolOriginInfoKind(6 /* SymbolMemberExport */), @@ -158702,12 +142855,17 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} function addSymbolOriginInfo(symbol2) { if (preferences.includeCompletionsWithInsertText) { if (insertAwait && addToSeen(seenPropertySymbols, getSymbolId(symbol2))) { - symbolToOriginInfoMap[symbols.length] = { kind: getNullableSymbolOriginInfoKind(8 /* Promise */) }; + symbolToOriginInfoMap[symbols.length] = { + kind: getNullableSymbolOriginInfoKind(8 /* Promise */) + }; } else if (insertQuestionDot) { - symbolToOriginInfoMap[symbols.length] = { kind: 16 /* Nullable */ }; + symbolToOriginInfoMap[symbols.length] = { + kind: 16 /* Nullable */ + }; } } } + function getNullableSymbolOriginInfoKind(kind) { return insertQuestionDot ? kind | 16 /* Nullable */ : kind; } @@ -158719,19 +142877,19 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} const result = tryGetObjectTypeLiteralInTypeArgumentCompletionSymbols() || tryGetObjectLikeCompletionSymbols() || tryGetImportCompletionSymbols() || tryGetImportOrExportClauseCompletionSymbols() || tryGetLocalNamedExportCompletionSymbols() || tryGetConstructorCompletion() || tryGetClassLikeCompletionSymbols() || tryGetJsxCompletionSymbols() || (getGlobalCompletions(), 1 /* Success */); return result === 1 /* Success */; } + function tryGetConstructorCompletion() { - if (!tryGetConstructorLikeCompletionContainer(contextToken)) - return 0 /* Continue */; + if (!tryGetConstructorLikeCompletionContainer(contextToken)) return 0 /* Continue */; completionKind = 5 /* None */; isNewIdentifierLocation = true; keywordFilters = 4 /* ConstructorParameterKeywords */; return 1 /* Success */; } + function tryGetJsxCompletionSymbols() { const jsxContainer = tryGetContainingJsxElement(contextToken); const attrsType = jsxContainer && typeChecker.getContextualType(jsxContainer.attributes); - if (!attrsType) - return 0 /* Continue */; + 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(); @@ -158739,13 +142897,14 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} isNewIdentifierLocation = false; return 1 /* Success */; } + function tryGetImportCompletionSymbols() { - if (!importStatementCompletion) - return 0 /* Continue */; + if (!importStatementCompletion) return 0 /* Continue */; isNewIdentifierLocation = true; collectAutoImports(); return 1 /* Success */; } + function getGlobalCompletions() { keywordFilters = tryGetFunctionLikeBodyCompletionContainer(contextToken) ? 5 /* FunctionLikeBodyKeywords */ : 1 /* All */; completionKind = 1 /* Global */; @@ -158762,27 +142921,28 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} Debug.assertEachIsDefined(symbols, "getSymbolsInScope() should all be defined"); for (let i = 0; i < symbols.length; i++) { const symbol = symbols[i]; - if (!typeChecker.isArgumentsSymbol(symbol) && !some(symbol.declarations, (d) => d.getSourceFile() === sourceFile)) { + if (!typeChecker.isArgumentsSymbol(symbol) && !some(symbol.declarations, d => d.getSourceFile() === sourceFile)) { symbolToSortTextMap[getSymbolId(symbol)] = SortText.GlobalsOrKeywords; } if (typeOnlyAliasNeedsPromotion && !(symbol.flags & 111551 /* Value */)) { const typeOnlyAliasDeclaration = symbol.declarations && find(symbol.declarations, isTypeOnlyImportDeclaration); if (typeOnlyAliasDeclaration) { - const origin = { kind: 64 /* TypeOnlyAlias */, declaration: typeOnlyAliasDeclaration }; + const origin = { + kind: 64 /* TypeOnlyAlias */, + declaration: typeOnlyAliasDeclaration + }; symbolToOriginInfoMap[i] = origin; } } } if (preferences.includeCompletionsWithInsertText && scopeNode.kind !== 312 /* SourceFile */) { - const thisType = typeChecker.tryGetThisTypeAt( - scopeNode, - /*includeGlobalThis*/ - false, - isClassLike(scopeNode.parent) ? scopeNode : void 0 - ); + const thisType = typeChecker.tryGetThisTypeAt(scopeNode, /*includeGlobalThis*/ + false, isClassLike(scopeNode.parent) ? scopeNode : void 0); if (thisType && !isProbablyGlobalType(thisType, sourceFile, typeChecker)) { for (const symbol of getPropertiesForCompletion(thisType, typeChecker)) { - symbolToOriginInfoMap[symbols.length] = { kind: 1 /* ThisType */ }; + symbolToOriginInfoMap[symbols.length] = { + kind: 1 /* ThisType */ + }; symbols.push(symbol); symbolToSortTextMap[getSymbolId(symbol)] = SortText.SuggestedClassMembers; } @@ -158793,17 +142953,13 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} keywordFilters = contextToken && isAssertionExpression(contextToken.parent) ? 6 /* TypeAssertionKeywords */ : 7 /* TypeKeywords */; } } + function shouldOfferImportCompletions() { - if (importStatementCompletion) - return true; - if (isNonContextualObjectLiteral) - return false; - if (!preferences.includeCompletionsForModuleExports) - return false; - if (sourceFile.externalModuleIndicator || sourceFile.commonJsModuleIndicator) - return true; - if (compilerOptionsIndicateEsModules(program.getCompilerOptions())) - return true; + if (importStatementCompletion) return true; + if (isNonContextualObjectLiteral) return false; + if (!preferences.includeCompletionsForModuleExports) return false; + if (sourceFile.externalModuleIndicator || sourceFile.commonJsModuleIndicator) return true; + if (compilerOptionsIndicateEsModules(program.getCompilerOptions())) return true; return programContainsModules(program); } function isSnippetScope(scopeNode) { @@ -158823,6 +142979,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} function isContextTokenValueLocation(contextToken2) { return contextToken2 && (contextToken2.kind === 114 /* TypeOfKeyword */ && (contextToken2.parent.kind === 186 /* TypeQuery */ || isTypeOfExpression(contextToken2.parent)) || contextToken2.kind === 131 /* AssertsKeyword */ && contextToken2.parent.kind === 182 /* TypePredicate */); } + function isContextTokenTypeLocation(contextToken2) { if (contextToken2) { const parentKind = contextToken2.parent.kind; @@ -158841,12 +142998,12 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return parentKind === 238 /* SatisfiesExpression */; } } + return false; } 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; @@ -158858,71 +143015,53 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} const exportInfo = getExportInfoMap(sourceFile, host, program, preferences, cancellationToken); const packageJsonAutoImportProvider = (_b = host.getPackageJsonAutoImportProvider) == null ? void 0 : _b.call(host); const packageJsonFilter = detailsEntryId ? void 0 : createPackageJsonImportFilter(sourceFile, preferences, host); - resolvingModuleSpecifiers( - "collectAutoImports", - host, - importSpecifierResolver || (importSpecifierResolver = ts_codefix_exports.createImportSpecifierResolver(sourceFile, program, host, preferences)), - program, - position, - preferences, - !!importStatementCompletion, - isValidTypeOnlyAliasUseSite(location), - (context) => { - exportInfo.search( - sourceFile.path, - /*preferCapitalized*/ - isRightOfOpenTag, - (symbolName2, targetFlags) => { - if (!isIdentifierText(symbolName2, getEmitScriptTarget(host.getCompilationSettings()))) - return false; - if (!detailsEntryId && isStringANonContextualKeyword(symbolName2)) - return false; - if (!isTypeOnlyLocation && !importStatementCompletion && !(targetFlags & 111551 /* Value */)) - return false; - if (isTypeOnlyLocation && !(targetFlags & (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; - return charactersFuzzyMatchInString(symbolName2, lowerCaseTokenText); - }, - (info, symbolName2, isFromAmbientModule, exportMapKey) => { - if (detailsEntryId && !some(info, (i) => detailsEntryId.source === stripQuotes(i.moduleSymbol.name))) { - return; - } - info = filter(info, isImportableExportInfo); - if (!info.length) { - return; - } - const result = context.tryResolve(info, isFromAmbientModule) || {}; - if (result === "failed") - return; - let exportInfo2 = info[0], moduleSpecifier; - if (result !== "skipped") { - ({ exportInfo: exportInfo2 = info[0], moduleSpecifier } = result); - } - const isDefaultExport = exportInfo2.exportKind === 1 /* Default */; - const symbol = isDefaultExport && getLocalSymbolForExportDefault(exportInfo2.symbol) || exportInfo2.symbol; - pushAutoImportSymbol(symbol, { - kind: moduleSpecifier ? 32 /* ResolvedExport */ : 4 /* Export */, - moduleSpecifier, - symbolName: symbolName2, - exportMapKey, - exportName: exportInfo2.exportKind === 2 /* ExportEquals */ ? "export=" /* ExportEquals */ : exportInfo2.symbol.name, - fileName: exportInfo2.moduleFileName, - isDefaultExport, - moduleSymbol: exportInfo2.moduleSymbol, - isFromPackageJson: exportInfo2.isFromPackageJson - }); - } - ); - hasUnresolvedAutoImports = context.skippedAny(); - flags |= context.resolvedAny() ? 8 /* ResolvedModuleSpecifiers */ : 0; - flags |= context.resolvedBeyondLimit() ? 16 /* ResolvedModuleSpecifiersBeyondLimit */ : 0; - } - ); + resolvingModuleSpecifiers("collectAutoImports", host, importSpecifierResolver || (importSpecifierResolver = ts_codefix_exports.createImportSpecifierResolver(sourceFile, program, host, preferences)), program, position, preferences, !!importStatementCompletion, isValidTypeOnlyAliasUseSite(location), context => { + exportInfo.search(sourceFile.path, /*preferCapitalized*/ + isRightOfOpenTag, (symbolName2, targetFlags) => { + if (!isIdentifierText(symbolName2, getEmitScriptTarget(host.getCompilationSettings()))) return false; + if (!detailsEntryId && isStringANonContextualKeyword(symbolName2)) return false; + if (!isTypeOnlyLocation && !importStatementCompletion && !(targetFlags & 111551 /* Value */)) return false; + if (isTypeOnlyLocation && !(targetFlags & (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; + return charactersFuzzyMatchInString(symbolName2, lowerCaseTokenText); + }, (info, symbolName2, isFromAmbientModule, exportMapKey) => { + if (detailsEntryId && !some(info, i => detailsEntryId.source === stripQuotes(i.moduleSymbol.name))) { + return; + } + info = filter(info, isImportableExportInfo); + if (!info.length) { + return; + } + const result = context.tryResolve(info, isFromAmbientModule) || {}; + if (result === "failed") return; + let exportInfo2 = info[0], + moduleSpecifier; + if (result !== "skipped") { + ({ + exportInfo: exportInfo2 = info[0], + moduleSpecifier + } = result); + } + const isDefaultExport = exportInfo2.exportKind === 1 /* Default */; + const symbol = isDefaultExport && getLocalSymbolForExportDefault(exportInfo2.symbol) || exportInfo2.symbol; + pushAutoImportSymbol(symbol, { + kind: moduleSpecifier ? 32 /* ResolvedExport */ : 4 /* Export */, + moduleSpecifier, + symbolName: symbolName2, + exportMapKey, + exportName: exportInfo2.exportKind === 2 /* ExportEquals */ ? "export=" /* ExportEquals */ : exportInfo2.symbol.name, + fileName: exportInfo2.moduleFileName, + isDefaultExport, + moduleSymbol: exportInfo2.moduleSymbol, + isFromPackageJson: exportInfo2.isFromPackageJson + }); + }); + hasUnresolvedAutoImports = context.skippedAny(); + flags |= context.resolvedAny() ? 8 /* ResolvedModuleSpecifiers */ : 0; + flags |= context.resolvedBeyondLimit() ? 16 /* ResolvedModuleSpecifiersBeyondLimit */ : 0; + }); function isImportableExportInfo(info) { const moduleFile = tryCast(info.moduleSymbol.valueDeclaration, isSourceFile); if (!moduleFile) { @@ -158932,15 +143071,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } return packageJsonFilter ? packageJsonFilter.allowsImportingAmbientModule(info.moduleSymbol, getModuleSpecifierResolutionHost(info.isFromPackageJson)) : true; } - return isImportableFile( - info.isFromPackageJson ? packageJsonAutoImportProvider : program, - sourceFile, - moduleFile, - preferences, - packageJsonFilter, - getModuleSpecifierResolutionHost(info.isFromPackageJson), - moduleSpecifierCache - ); + return isImportableFile(info.isFromPackageJson ? packageJsonAutoImportProvider : program, sourceFile, moduleFile, preferences, packageJsonFilter, getModuleSpecifierResolutionHost(info.isFromPackageJson), moduleSpecifierCache); } } function pushAutoImportSymbol(symbol, origin) { @@ -158956,37 +143087,27 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (isInJSFile(location)) { return; } - members.forEach((member) => { + members.forEach(member => { if (!isObjectLiteralMethodSymbol(member)) { return; } - const displayName = getCompletionEntryDisplayNameForSymbol( - member, - getEmitScriptTarget(compilerOptions), - /*origin*/ - void 0, - 0 /* ObjectPropertyDeclaration */, - /*jsxIdentifierExpected*/ - false - ); + const displayName = getCompletionEntryDisplayNameForSymbol(member, getEmitScriptTarget(compilerOptions), /*origin*/ + void 0, 0 /* ObjectPropertyDeclaration */, /*jsxIdentifierExpected*/ + false); if (!displayName) { return; } - const { name } = displayName; - const entryProps = getEntryForObjectLiteralMethodCompletion( - member, - name, - enclosingDeclaration, - program, - host, - compilerOptions, - preferences, - formatContext - ); + const { + name + } = displayName; + const entryProps = getEntryForObjectLiteralMethodCompletion(member, name, enclosingDeclaration, program, host, compilerOptions, preferences, formatContext); if (!entryProps) { return; } - const origin = { kind: 128 /* ObjectLiteralMethod */, ...entryProps }; + const origin = { + kind: 128 /* ObjectLiteralMethod */, + ...entryProps + }; flags |= 32 /* MayIncludeMethodSnippets */; symbolToOriginInfoMap[symbols.length] = origin; symbols.push(member); @@ -159022,10 +143143,12 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (contextToken2.parent.kind === 286 /* JsxOpeningElement */) { return location.parent.kind !== 286 /* JsxOpeningElement */; } + if (contextToken2.parent.kind === 287 /* JsxClosingElement */ || contextToken2.parent.kind === 285 /* JsxSelfClosingElement */) { return !!contextToken2.parent.parent && contextToken2.parent.parent.kind === 284 /* JsxElement */; } } + return false; } function isNewIdentifierDefinitionLocation() { @@ -159058,6 +143181,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} case 42 /* AsteriskToken */: return containingNodeKind === 174 /* MethodDeclaration */; } + if (isClassMemberCompletionKeyword(tokenKind)) { return true; } @@ -159069,28 +143193,26 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } 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); - const existingMemberEscapedNames = /* @__PURE__ */ new Set(); - existingMembers.forEach((s) => existingMemberEscapedNames.add(s.escapedName)); - symbols = concatenate(symbols, filter(members, (s) => !existingMemberEscapedNames.has(s.escapedName))); + const existingMemberEscapedNames = /* @__PURE__ */new Set(); + existingMembers.forEach(s => existingMemberEscapedNames.add(s.escapedName)); + symbols = concatenate(symbols, filter(members, s => !existingMemberEscapedNames.has(s.escapedName))); completionKind = 0 /* ObjectPropertyDeclaration */; isNewIdentifierLocation = true; return 1 /* Success */; } + function tryGetObjectLikeCompletionSymbols() { const symbolsStartIndex = symbols.length; const objectLikeContainer = tryGetObjectLikeCompletionContainer(contextToken, position, sourceFile); - if (!objectLikeContainer) - return 0 /* Continue */; + if (!objectLikeContainer) return 0 /* Continue */; completionKind = 0 /* ObjectPropertyDeclaration */; let typeMembers; let existingMembers; @@ -159100,9 +143222,11 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (objectLikeContainer.flags & 67108864 /* InWithStatement */) { return 2 /* Fail */; } + isNonContextualObjectLiteral = true; return 0 /* Continue */; } + const completionsType = typeChecker.getContextualType(objectLikeContainer, 4 /* Completions */); const hasStringIndexType = (completionsType || instantiatedType).getStringIndexType(); const hasNumberIndextype = (completionsType || instantiatedType).getNumberIndexType(); @@ -159119,8 +143243,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} 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)) { @@ -159131,18 +143254,11 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } if (canGetType) { const typeForObject = typeChecker.getTypeAtLocation(objectLikeContainer); - if (!typeForObject) - return 2 /* Fail */; - typeMembers = typeChecker.getPropertiesOfType(typeForObject).filter((propertySymbol) => { - return typeChecker.isPropertyAccessible( - objectLikeContainer, - /*isSuper*/ - false, - /*isWrite*/ - false, - typeForObject, - propertySymbol - ); + if (!typeForObject) return 2 /* Fail */; + typeMembers = typeChecker.getPropertiesOfType(typeForObject).filter(propertySymbol => { + return typeChecker.isPropertyAccessible(objectLikeContainer, /*isSuper*/ + false, /*isWrite*/ + false, typeForObject, propertySymbol); }); existingMembers = objectLikeContainer.elements; } @@ -159158,42 +143274,49 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } 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 */; } - const { moduleSpecifier } = namedImportsOrExports.kind === 275 /* NamedImports */ ? namedImportsOrExports.parent.parent : namedImportsOrExports.parent; + + const { + moduleSpecifier + } = namedImportsOrExports.kind === 275 /* NamedImports */ ? namedImportsOrExports.parent.parent : namedImportsOrExports.parent; if (!moduleSpecifier) { isNewIdentifierLocation = true; return namedImportsOrExports.kind === 275 /* NamedImports */ ? 2 /* Fail */ : 0 /* Continue */; } + const moduleSpecifierSymbol = typeChecker.getSymbolAtLocation(moduleSpecifier); if (!moduleSpecifierSymbol) { isNewIdentifierLocation = true; return 2 /* Fail */; } + completionKind = 3 /* MemberLike */; isNewIdentifierLocation = false; const exports = typeChecker.getExportsAndPropertiesOfModule(moduleSpecifierSymbol); - const existing = new Set(namedImportsOrExports.elements.filter((n) => !isCurrentlyEditingNode(n)).map((n) => (n.propertyName || n.name).escapedText)); - const uniques = exports.filter((e) => e.escapedName !== "default" /* Default */ && !existing.has(e.escapedName)); + const existing = new Set(namedImportsOrExports.elements.filter(n => !isCurrentlyEditingNode(n)).map(n => (n.propertyName || n.name).escapedText)); + const uniques = exports.filter(e => e.escapedName !== "default" /* Default */ && !existing.has(e.escapedName)); symbols = concatenate(symbols, uniques); if (!uniques.length) { keywordFilters = 0 /* None */; } + return 1 /* Success */; } + function tryGetLocalNamedExportCompletionSymbols() { var _a; const namedExports = contextToken && (contextToken.kind === 19 /* OpenBraceToken */ || contextToken.kind === 28 /* CommaToken */) ? tryCast(contextToken.parent, isNamedExports) : void 0; if (!namedExports) { return 0 /* Continue */; } + const localsContainer = findAncestor(namedExports, or(isSourceFile, isModuleDeclaration)); completionKind = 5 /* None */; isNewIdentifierLocation = false; @@ -159206,15 +143329,14 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} }); return 1 /* Success */; } + 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)) { @@ -159233,9 +143355,10 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (isClassStaticBlockDeclaration(classElement)) { classElementModifierFlags |= 256 /* Static */; } + if (!(classElementModifierFlags & 2 /* Private */)) { const baseTypeNodes = isClassLike(decl) && classElementModifierFlags & 16 /* Override */ ? singleElementArray(getEffectiveBaseTypeNode(decl)) : getAllSuperTypeNodes(decl); - const baseSymbols = flatMap(baseTypeNodes, (baseTypeNode) => { + const baseSymbols = flatMap(baseTypeNodes, baseTypeNode => { const type = typeChecker.getTypeAtLocation(baseTypeNode); return classElementModifierFlags & 256 /* Static */ ? (type == null ? void 0 : type.symbol) && typeChecker.getPropertiesOfType(typeChecker.getTypeOfSymbolAtLocation(type.symbol, decl)) : type && typeChecker.getPropertiesOfType(type); }); @@ -159253,6 +143376,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } return 1 /* Success */; } + function isConstructorParameterCompletion(node2) { return !!node2.parent && isParameter(node2.parent) && isConstructorDeclaration(node2.parent.parent) && (isParameterPropertyModifier(node2.kind) || isDeclarationName(node2)); } @@ -159274,7 +143398,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} function tryGetFunctionLikeBodyCompletionContainer(contextToken2) { if (contextToken2) { let prev; - const container = findAncestor(contextToken2.parent, (node2) => { + const container = findAncestor(contextToken2.parent, node2 => { if (isClassLike(node2)) { return "quit"; } @@ -159301,14 +143425,9 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} case 293 /* JsxSpreadAttribute */: if (parent2 && (parent2.kind === 285 /* JsxSelfClosingElement */ || parent2.kind === 286 /* JsxOpeningElement */)) { if (contextToken2.kind === 32 /* GreaterThanToken */) { - const precedingToken = findPrecedingToken( - contextToken2.pos, - sourceFile, - /*startNode*/ - void 0 - ); - if (!parent2.typeArguments || precedingToken && precedingToken.kind === 44 /* SlashToken */) - break; + const precedingToken = findPrecedingToken(contextToken2.pos, sourceFile, /*startNode*/ + void 0); + if (!parent2.typeArguments || precedingToken && precedingToken.kind === 44 /* SlashToken */) break; } return parent2; } else if (parent2.kind === 291 /* JsxAttribute */) { @@ -159337,10 +143456,14 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} const containingNodeKind = parent2.kind; switch (contextToken2.kind) { case 28 /* CommaToken */: - return containingNodeKind === 260 /* VariableDeclaration */ || isVariableDeclarationListButNotTypeArgument(contextToken2) || containingNodeKind === 243 /* VariableStatement */ || containingNodeKind === 266 /* EnumDeclaration */ || // enum a { foo, | - isFunctionLikeButNotConstructor(containingNodeKind) || containingNodeKind === 264 /* InterfaceDeclaration */ || // interface A= contextToken2.pos; @@ -159355,10 +143478,14 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} case 19 /* OpenBraceToken */: return containingNodeKind === 266 /* EnumDeclaration */; case 30 /* LessThanToken */: - return containingNodeKind === 263 /* ClassDeclaration */ || // class A< | - containingNodeKind === 231 /* ClassExpression */ || // var C = class D< | - containingNodeKind === 264 /* InterfaceDeclaration */ || // interface A< | - containingNodeKind === 265 /* TypeAliasDeclaration */ || // type List< | + return containingNodeKind === 263 /* ClassDeclaration */ || + // class A< | + containingNodeKind === 231 /* ClassExpression */ || + // var C = class D< | + containingNodeKind === 264 /* InterfaceDeclaration */ || + // interface A< | + containingNodeKind === 265 /* TypeAliasDeclaration */ || + // type List< | isFunctionLikeKind(containingNodeKind); case 126 /* StaticKeyword */: return containingNodeKind === 172 /* PropertyDeclaration */ && !isClassLike(parent2.parent); @@ -159439,6 +143566,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} function isFunctionLikeButNotConstructor(kind) { return isFunctionLikeKind(kind) && kind !== 176 /* Constructor */; } + function isDotOfNumericLiteral(contextToken2) { if (contextToken2.kind === 9 /* NumericLiteral */) { const text = contextToken2.getFullText(); @@ -159453,8 +143581,8 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (existingMembers.length === 0) { return contextualMemberSymbols; } - const membersDeclaredBySpreadAssignment = /* @__PURE__ */ new Set(); - const existingMemberNames = /* @__PURE__ */ new Set(); + const membersDeclaredBySpreadAssignment = /* @__PURE__ */new Set(); + const existingMemberNames = /* @__PURE__ */new Set(); for (const m of existingMembers) { if (m.kind !== 303 /* PropertyAssignment */ && m.kind !== 304 /* ShorthandPropertyAssignment */ && m.kind !== 208 /* BindingElement */ && m.kind !== 174 /* MethodDeclaration */ && m.kind !== 177 /* GetAccessor */ && m.kind !== 178 /* SetAccessor */ && m.kind !== 305 /* SpreadAssignment */) { continue; @@ -159477,7 +143605,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} existingMemberNames.add(existingName); } } - const filteredSymbols = contextualMemberSymbols.filter((m) => !existingMemberNames.has(m.escapedName)); + const filteredSymbols = contextualMemberSymbols.filter(m => !existingMemberNames.has(m.escapedName)); setSortTextToMemberDeclaredBySpreadAssignment(membersDeclaredBySpreadAssignment, filteredSymbols); return filteredSymbols; } @@ -159487,16 +143615,17 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} const type = symbol && typeChecker.getTypeOfSymbolAtLocation(symbol, expression); const properties = type && type.properties; if (properties) { - properties.forEach((property) => { + properties.forEach(property => { membersDeclaredBySpreadAssignment.add(property.name); }); } } function setSortTextToOptionalMember() { - symbols.forEach((m) => { + symbols.forEach(m => { if (m.flags & 16777216 /* Optional */) { + var _symbolToSortTextMap$; const symbolId = getSymbolId(m); - symbolToSortTextMap[symbolId] = symbolToSortTextMap[symbolId] ?? SortText.OptionalMember; + symbolToSortTextMap[symbolId] = (_symbolToSortTextMap$ = symbolToSortTextMap[symbolId]) !== null && _symbolToSortTextMap$ !== void 0 ? _symbolToSortTextMap$ : SortText.OptionalMember; } }); } @@ -159516,23 +143645,20 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} const symbolId = getSymbolId(symbol); const origin = symbolToOriginInfoMap == null ? void 0 : symbolToOriginInfoMap[i]; const target = getEmitScriptTarget(compilerOptions); - const displayName = getCompletionEntryDisplayNameForSymbol( - symbol, - target, - origin, - 0 /* ObjectPropertyDeclaration */, - /*jsxIdentifierExpected*/ - false - ); + const displayName = getCompletionEntryDisplayNameForSymbol(symbol, target, origin, 0 /* ObjectPropertyDeclaration */, /*jsxIdentifierExpected*/ + false); if (displayName) { - const originalSortText = symbolToSortTextMap[symbolId] ?? SortText.LocationPriority; - const { name } = displayName; + var _symbolToSortTextMap$2; + const originalSortText = (_symbolToSortTextMap$2 = symbolToSortTextMap[symbolId]) !== null && _symbolToSortTextMap$2 !== void 0 ? _symbolToSortTextMap$2 : SortText.LocationPriority; + const { + name + } = displayName; symbolToSortTextMap[symbolId] = SortText.ObjectLiteralProperty(originalSortText, name); } } } function filterClassMembersList(baseSymbols, existingMembers, currentClassElementModifierFlags) { - const existingMemberNames = /* @__PURE__ */ new Set(); + const existingMemberNames = /* @__PURE__ */new Set(); for (const m of existingMembers) { if (m.kind !== 172 /* PropertyDeclaration */ && m.kind !== 174 /* MethodDeclaration */ && m.kind !== 177 /* GetAccessor */ && m.kind !== 178 /* SetAccessor */) { continue; @@ -159551,13 +143677,11 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} existingMemberNames.add(existingName); } } - return baseSymbols.filter( - (propertySymbol) => !existingMemberNames.has(propertySymbol.escapedName) && !!propertySymbol.declarations && !(getDeclarationModifierFlagsFromSymbol(propertySymbol) & 2 /* Private */) && !(propertySymbol.valueDeclaration && isPrivateIdentifierClassElementDeclaration(propertySymbol.valueDeclaration)) - ); + return baseSymbols.filter(propertySymbol => !existingMemberNames.has(propertySymbol.escapedName) && !!propertySymbol.declarations && !(getDeclarationModifierFlagsFromSymbol(propertySymbol) & 2 /* Private */) && !(propertySymbol.valueDeclaration && isPrivateIdentifierClassElementDeclaration(propertySymbol.valueDeclaration))); } function filterJsxAttributes(symbols2, attributes) { - const seenNames = /* @__PURE__ */ new Set(); - const membersDeclaredBySpreadAssignment = /* @__PURE__ */ new Set(); + const seenNames = /* @__PURE__ */new Set(); + const membersDeclaredBySpreadAssignment = /* @__PURE__ */new Set(); for (const attr of attributes) { if (isCurrentlyEditingNode(attr)) { continue; @@ -159568,7 +143692,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} setMembersDeclaredBySpreadAssignment(attr, membersDeclaredBySpreadAssignment); } } - const filteredSymbols = symbols2.filter((a) => !seenNames.has(a.escapedName)); + const filteredSymbols = symbols2.filter(a => !seenNames.has(a.escapedName)); setSortTextToMemberDeclaredBySpreadAssignment(membersDeclaredBySpreadAssignment, filteredSymbols); return filteredSymbols; } @@ -159579,7 +143703,9 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} function tryGetObjectLikeCompletionContainer(contextToken, position, sourceFile) { var _a; if (contextToken) { - const { parent: parent2 } = contextToken; + const { + parent: parent2 + } = contextToken; switch (contextToken.kind) { case 19 /* OpenBraceToken */: case 28 /* CommaToken */: @@ -159622,28 +143748,31 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} function getRelevantTokens(position, sourceFile) { const previousToken = findPrecedingToken(position, sourceFile); if (previousToken && position <= previousToken.end && (isMemberName(previousToken) || isKeyword(previousToken.kind))) { - const contextToken = findPrecedingToken( - previousToken.getFullStart(), - sourceFile, - /*startNode*/ - void 0 - ); - return { contextToken, previousToken }; + const contextToken = findPrecedingToken(previousToken.getFullStart(), sourceFile, /*startNode*/ + void 0); + return { + contextToken, + previousToken + }; } - return { contextToken: previousToken, previousToken }; + return { + contextToken: previousToken, + previousToken + }; } 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) }; + return { + symbol, + origin: completionEntryDataToSymbolOriginInfo(data, name, moduleSymbol) + }; } function getCompletionEntryDisplayNameForSymbol(symbol, target, origin, kind, jsxIdentifierExpected) { if (originIsIgnore(origin)) { @@ -159653,18 +143782,30 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (name === void 0 || symbol.flags & 1536 /* Module */ && isSingleOrDoubleQuote(name.charCodeAt(0)) || isKnownSymbol(symbol)) { return void 0; } - const validNameResult = { name, needsConvertPropertyAccess: false }; + const validNameResult = { + name, + needsConvertPropertyAccess: false + }; if (isIdentifierText(name, target, jsxIdentifierExpected ? 1 /* JSX */ : 0 /* Standard */) || symbol.valueDeclaration && isPrivateIdentifierClassElementDeclaration(symbol.valueDeclaration)) { return validNameResult; } switch (kind) { case 3 /* MemberLike */: - return originIsComputedPropertyName(origin) ? { name: origin.symbolName, needsConvertPropertyAccess: false } : void 0; + return originIsComputedPropertyName(origin) ? { + name: origin.symbolName, + needsConvertPropertyAccess: false + } : void 0; case 0 /* ObjectPropertyDeclaration */: - return { name: JSON.stringify(name), needsConvertPropertyAccess: false }; + return { + name: JSON.stringify(name), + needsConvertPropertyAccess: false + }; case 2 /* PropertyAccess */: case 1 /* Global */: - return name.charCodeAt(0) === 32 /* space */ ? void 0 : { name, needsConvertPropertyAccess: true }; + return name.charCodeAt(0) === 32 /* space */ ? void 0 : { + name, + needsConvertPropertyAccess: true + }; case 5 /* None */: case 4 /* String */: return validNameResult; @@ -159673,13 +143814,12 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } } 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)))); + return _keywordCompletions[index] || (_keywordCompletions[index] = getTypescriptKeywordCompletions(keywordFilter).filter(entry => !isTypeScriptOnlyKeyword(stringToToken(entry.name)))); } function getTypescriptKeywordCompletions(keywordFilter) { - return _keywordCompletions[keywordFilter] || (_keywordCompletions[keywordFilter] = allKeywordsCompletions().filter((entry) => { + return _keywordCompletions[keywordFilter] || (_keywordCompletions[keywordFilter] = allKeywordsCompletions().filter(entry => { const kind = stringToToken(entry.name); switch (keywordFilter) { case 0 /* None */: @@ -159742,6 +143882,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} function isInterfaceOrTypeLiteralCompletionKeyword(kind) { return kind === 148 /* ReadonlyKeyword */; } + function isClassMemberCompletionKeyword(kind) { switch (kind) { case 128 /* AbstractKeyword */: @@ -159761,7 +143902,8 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return kind === 134 /* AsyncKeyword */ || kind === 135 /* AwaitKeyword */ || kind === 130 /* AsKeyword */ || kind === 152 /* SatisfiesKeyword */ || kind === 156 /* TypeKeyword */ || !isContextualKeyword(kind) && !isClassMemberCompletionKeyword(kind); } function keywordForNode(node) { - return isIdentifier(node) ? identifierToKeywordKind(node) ?? 0 /* Unknown */ : node.kind; + var _identifierToKeywordK; + return isIdentifier(node) ? (_identifierToKeywordK = identifierToKeywordKind(node)) !== null && _identifierToKeywordK !== void 0 ? _identifierToKeywordK : 0 /* Unknown */ : node.kind; } function getContextualKeywords(contextToken, position) { const entries = []; @@ -159782,7 +143924,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return entries; } function getJsDocTagAtPosition(node, position) { - return findAncestor(node, (n) => isJSDocTag(n) && rangeContainsPosition(n, position) ? true : isJSDoc(n) ? "quit" : false); + return findAncestor(node, n => isJSDocTag(n) && rangeContainsPosition(n, position) ? true : isJSDoc(n) ? "quit" : false); } function getPropertiesForObjectExpression(contextualType, completionsType, obj, checker) { const hasCompletionsType = completionsType && completionsType !== contextualType; @@ -159790,19 +143932,18 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} const properties = getApparentProperties(type, obj, checker); return type.isClass() && containsNonPublicProperties(properties) ? [] : hasCompletionsType ? filter(properties, hasDeclarationOtherThanSelf) : properties; function hasDeclarationOtherThanSelf(member) { - if (!length(member.declarations)) - return true; - return some(member.declarations, (decl) => decl.parent !== obj); + 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(); - 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())))); + 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) { - return some(props, (p) => !!(getDeclarationModifierFlagsFromSymbol(p) & 6 /* NonPublicAccessibilityModifier */)); + return some(props, p => !!(getDeclarationModifierFlagsFromSymbol(p) & 6 /* NonPublicAccessibilityModifier */)); } + function getPropertiesForCompletion(type, checker) { return type.isUnion() ? Debug.checkEachDefined(checker.getAllPossiblePropertiesOfTypes(type.types), "getAllPossiblePropertiesOfTypes() should all be defined") : Debug.checkEachDefined(type.getApparentProperties(), "getApparentProperties() should all be defined"); } @@ -159821,21 +143962,21 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return findAncestor(location, isClassLike); } break; - case 80 /* Identifier */: { - const originalKeywordKind = identifierToKeywordKind(location); - if (originalKeywordKind) { - return void 0; + case 80 /* Identifier */: + { + const originalKeywordKind = identifierToKeywordKind(location); + if (originalKeywordKind) { + return void 0; + } + if (isPropertyDeclaration(location.parent) && location.parent.initializer === location) { + return void 0; + } + if (isFromObjectTypeDeclaration(location)) { + return findAncestor(location, isObjectTypeDeclaration); + } } - if (isPropertyDeclaration(location.parent) && location.parent.initializer === location) { - return void 0; - } - if (isFromObjectTypeDeclaration(location)) { - return findAncestor(location, isObjectTypeDeclaration); - } - } } - 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); } @@ -159850,18 +143991,18 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return tryCast(contextToken.parent, isObjectTypeDeclaration); default: if (isObjectTypeDeclaration(location)) { + var _identifierToKeywordK2; if (getLineAndCharacterOfPosition(sourceFile, contextToken.getEnd()).line !== getLineAndCharacterOfPosition(sourceFile, position).line) { return location; } const isValidKeyword = isClassLike(contextToken.parent.parent) ? isClassMemberCompletionKeyword : isInterfaceOrTypeLiteralCompletionKeyword; - return isValidKeyword(contextToken.kind) || contextToken.kind === 42 /* AsteriskToken */ || isIdentifier(contextToken) && isValidKeyword(identifierToKeywordKind(contextToken) ?? 0 /* Unknown */) ? contextToken.parent.parent : void 0; + return isValidKeyword(contextToken.kind) || contextToken.kind === 42 /* AsteriskToken */ || isIdentifier(contextToken) && isValidKeyword((_identifierToKeywordK2 = identifierToKeywordKind(contextToken)) !== null && _identifierToKeywordK2 !== void 0 ? _identifierToKeywordK2 : 0 /* Unknown */) ? contextToken.parent.parent : void 0; } return void 0; } } function tryGetTypeLiteralNode(node) { - if (!node) - return void 0; + if (!node) return void 0; const parent2 = node.parent; switch (node.kind) { case 19 /* OpenBraceToken */: @@ -159880,14 +144021,12 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} 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); @@ -159921,40 +144060,27 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return Debug.assertNever(triggerCharacter); } } - function binaryExpressionMayBeOpenTag({ left }) { + function binaryExpressionMayBeOpenTag({ + left + }) { return nodeIsMissing(left); } function isProbablyGlobalType(type, sourceFile, checker) { - const selfSymbol = checker.resolveName( - "self", - /*location*/ - void 0, - 111551 /* Value */, - /*excludeGlobals*/ - false - ); + const selfSymbol = checker.resolveName("self", /*location*/ + void 0, 111551 /* Value */, /*excludeGlobals*/ + false); if (selfSymbol && checker.getTypeOfSymbolAtLocation(selfSymbol, sourceFile) === type) { return true; } - const globalSymbol = checker.resolveName( - "global", - /*location*/ - void 0, - 111551 /* Value */, - /*excludeGlobals*/ - false - ); + const globalSymbol = checker.resolveName("global", /*location*/ + void 0, 111551 /* Value */, /*excludeGlobals*/ + false); if (globalSymbol && checker.getTypeOfSymbolAtLocation(globalSymbol, sourceFile) === type) { return true; } - const globalThisSymbol = checker.resolveName( - "globalThis", - /*location*/ - void 0, - 111551 /* Value */, - /*excludeGlobals*/ - false - ); + const globalThisSymbol = checker.resolveName("globalThis", /*location*/ + void 0, 111551 /* Value */, /*excludeGlobals*/ + false); if (globalThisSymbol && checker.getTypeOfSymbolAtLocation(globalThisSymbol, sourceFile) === type) { return true; } @@ -160009,6 +144135,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (!parent2.parent.isTypeOnly && (contextToken.kind === 19 /* OpenBraceToken */ || contextToken.kind === 102 /* ImportKeyword */ || contextToken.kind === 28 /* CommaToken */)) { keywordCompletion = 156 /* TypeKeyword */; } + if (canCompleteFromNamedBindings(parent2)) { if (contextToken.kind === 20 /* CloseBraceToken */ || contextToken.kind === 80 /* Identifier */) { isKeywordOnlyCompletion = true; @@ -160031,16 +144158,16 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } } function getSingleLineReplacementSpanForImportCompletionNode(node) { + var _findAncestor2, _getPotentiallyInvali; var _a; - if (!node) - return void 0; - const top = findAncestor(node, or(isImportDeclaration, isImportEqualsDeclaration)) ?? node; + if (!node) return void 0; + const top = (_findAncestor2 = findAncestor(node, or(isImportDeclaration, isImportEqualsDeclaration))) !== null && _findAncestor2 !== void 0 ? _findAncestor2 : node; const sourceFile = top.getSourceFile(); if (rangeIsOnSingleLine(top, sourceFile)) { return createTextSpanFromNode(top, sourceFile); } Debug.assert(top.kind !== 102 /* ImportKeyword */ && top.kind !== 276 /* ImportSpecifier */); - const potentialSplitPoint = top.kind === 272 /* ImportDeclaration */ ? getPotentiallyInvalidImportSpecifier((_a = top.importClause) == null ? void 0 : _a.namedBindings) ?? top.moduleSpecifier : top.moduleReference; + const potentialSplitPoint = top.kind === 272 /* ImportDeclaration */ ? (_getPotentiallyInvali = getPotentiallyInvalidImportSpecifier((_a = top.importClause) == null ? void 0 : _a.namedBindings)) !== null && _getPotentiallyInvali !== void 0 ? _getPotentiallyInvali : top.moduleSpecifier : top.moduleReference; const withoutModuleSpecifier = { pos: top.getFirstToken().getStart(), end: potentialSplitPoint.pos @@ -160051,14 +144178,12 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } function getPotentiallyInvalidImportSpecifier(namedBindings) { var _a; - return find( - (_a = tryCast(namedBindings, isNamedImports)) == null ? void 0 : _a.elements, - (e) => { - var _a2; - return !e.propertyName && isStringANonContextualKeyword(e.name.text) && ((_a2 = findPrecedingToken(e.name.pos, namedBindings.getSourceFile(), namedBindings)) == null ? void 0 : _a2.kind) !== 28 /* CommaToken */; - } - ); + return find((_a = tryCast(namedBindings, isNamedImports)) == null ? void 0 : _a.elements, e => { + var _a2; + return !e.propertyName && isStringANonContextualKeyword(e.name.text) && ((_a2 = findPrecedingToken(e.name.pos, namedBindings.getSourceFile(), namedBindings)) == null ? void 0 : _a2.kind) !== 28 /* CommaToken */; + }); } + function couldBeTypeOnlyImportSpecifier(importSpecifier, contextToken) { return isImportSpecifier(importSpecifier) && (importSpecifier.isTypeOnly || contextToken === importSpecifier.name && isTypeKeywordTokenOrIdentifier(contextToken)); } @@ -160075,25 +144200,25 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } 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; - 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)); + if (!contextToken) return; + const possiblyParameterDeclaration = findAncestor(contextToken, node => isFunctionBlock(node) || isArrowFunctionBody(node) || isBindingPattern(node) ? "quit" : (isParameter(node) || isTypeParameterDeclaration(node)) && !isIndexSignatureDeclaration(node.parent)); + const possiblyVariableDeclaration = findAncestor(location, node => isFunctionBlock(node) || isArrowFunctionBody(node) || isBindingPattern(node) ? "quit" : isVariableDeclaration(node)); return possiblyParameterDeclaration || possiblyVariableDeclaration; } function isArrowFunctionBody(node) { - return node.parent && isArrowFunction(node.parent) && (node.parent.body === node || // const a = () => /**/; + return node.parent && isArrowFunction(node.parent) && (node.parent.body === node || + // const a = () => /**/; node.kind === 39 /* EqualsGreaterThanToken */); } - function symbolCanBeReferencedAtTypeLocation(symbol, checker, seenModules = /* @__PURE__ */ new Map()) { + + function symbolCanBeReferencedAtTypeLocation(symbol, checker, seenModules = /* @__PURE__ */new Map()) { return nonAliasCanBeReferencedAtTypeLocation(symbol) || nonAliasCanBeReferencedAtTypeLocation(skipAlias(symbol.exportSymbol || symbol, checker)); function nonAliasCanBeReferencedAtTypeLocation(symbol2) { - return !!(symbol2.flags & 788968 /* Type */) || checker.isUnknownSymbol(symbol2) || !!(symbol2.flags & 1536 /* Module */) && addToSeen(seenModules, getSymbolId(symbol2)) && checker.getExportsOfModule(symbol2).some((e) => symbolCanBeReferencedAtTypeLocation(e, checker, seenModules)); + return !!(symbol2.flags & 788968 /* Type */) || checker.isUnknownSymbol(symbol2) || !!(symbol2.flags & 1536 /* Module */) && addToSeen(seenModules, getSymbolId(symbol2)) && checker.getExportsOfModule(symbol2).some(e => symbolCanBeReferencedAtTypeLocation(e, checker, seenModules)); } } function isDeprecated(symbol, checker) { @@ -160112,8 +144237,10 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} const strChar = identifierString.charCodeAt(strIndex); const testChar = lowercaseCharacters.charCodeAt(characterIndex); if (strChar === testChar || strChar === toUpperCharCode(testChar)) { - matchedFirstCharacter || (matchedFirstCharacter = prevChar === void 0 || // Beginning of word - 97 /* a */ <= prevChar && prevChar <= 122 /* z */ && 65 /* A */ <= strChar && strChar <= 90 /* Z */ || // camelCase transition + matchedFirstCharacter || (matchedFirstCharacter = prevChar === void 0 || + // Beginning of word + 97 /* a */ <= prevChar && prevChar <= 122 /* z */ && 65 /* A */ <= strChar && strChar <= 90 /* Z */ || + // camelCase transition prevChar === 95 /* _ */ && strChar !== 95 /* _ */); if (matchedFirstCharacter) { characterIndex++; @@ -160139,6 +144266,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} var init_completions = __esm({ "src/services/completions.ts"() { "use strict"; + init_ts4(); init_ts_Completions(); moduleSpecifierResolutionLimit = 100; @@ -160165,7 +144293,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return sortText + "1"; } }; - CompletionSource = /* @__PURE__ */ ((CompletionSource2) => { + CompletionSource = /* @__PURE__ */(CompletionSource2 => { CompletionSource2["ThisProperty"] = "ThisProperty/"; CompletionSource2["ClassMemberSnippet"] = "ClassMemberSnippet/"; CompletionSource2["TypeOnlyAlias"] = "TypeOnlyAlias/"; @@ -160174,7 +144302,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} CompletionSource2["ObjectLiteralMemberWithComma"] = "ObjectLiteralMemberWithComma/"; return CompletionSource2; })(CompletionSource || {}); - SymbolOriginInfoKind = /* @__PURE__ */ ((SymbolOriginInfoKind2) => { + SymbolOriginInfoKind = /* @__PURE__ */(SymbolOriginInfoKind2 => { SymbolOriginInfoKind2[SymbolOriginInfoKind2["ThisType"] = 1] = "ThisType"; SymbolOriginInfoKind2[SymbolOriginInfoKind2["SymbolMember"] = 2] = "SymbolMember"; SymbolOriginInfoKind2[SymbolOriginInfoKind2["Export"] = 4] = "Export"; @@ -160189,7 +144317,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} SymbolOriginInfoKind2[SymbolOriginInfoKind2["SymbolMemberExport"] = 6] = "SymbolMemberExport"; return SymbolOriginInfoKind2; })(SymbolOriginInfoKind || {}); - CompletionKind = /* @__PURE__ */ ((CompletionKind2) => { + CompletionKind = /* @__PURE__ */(CompletionKind2 => { CompletionKind2[CompletionKind2["ObjectPropertyDeclaration"] = 0] = "ObjectPropertyDeclaration"; CompletionKind2[CompletionKind2["Global"] = 1] = "Global"; CompletionKind2[CompletionKind2["PropertyAccess"] = 2] = "PropertyAccess"; @@ -160216,7 +144344,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} // src/services/stringCompletions.ts function createNameAndKindSet() { - const map2 = /* @__PURE__ */ new Map(); + const map2 = /* @__PURE__ */new Map(); function add(value) { const existing = map2.get(value.name); if (!existing || kindPrecedence[existing.kind] < kindPrecedence[value.kind]) { @@ -160235,8 +144363,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} 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.getTypeChecker(), options, host, preferences); return convertStringLiteralCompletions(entries, contextToken, sourceFile, host, program, log, options, preferences, position, includeSymbol); } @@ -160249,82 +144376,70 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} switch (completion.kind) { case 0 /* Paths */: return convertPathCompletions(completion.paths); - case 1 /* Properties */: { - const entries = createSortedArray(); - getCompletionEntriesFromSymbols( - completion.symbols, - entries, - contextToken, - contextToken, - sourceFile, - position, - sourceFile, - host, - program, - 99 /* ESNext */, - log, - 4 /* String */, - preferences, - options, - /*formatContext*/ - void 0, - /*isTypeOnlyLocation*/ - void 0, - /*propertyAccessToConvert*/ - void 0, - /*jsxIdentifierExpected*/ - void 0, - /*isJsxInitializer*/ - void 0, - /*importStatementCompletion*/ - void 0, - /*recommendedCompletion*/ - void 0, - /*symbolToOriginInfoMap*/ - void 0, - /*symbolToSortTextMap*/ - void 0, - /*isJsxIdentifierExpected*/ - void 0, - /*isRightOfOpenTag*/ - void 0, - includeSymbol - ); - return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: completion.hasIndexSignature, optionalReplacementSpan, entries }; - } - case 2 /* Types */: { - const quoteChar = contextToken.kind === 15 /* NoSubstitutionTemplateLiteral */ ? 96 /* backtick */ : startsWith(getTextOfNode(contextToken), "'") ? 39 /* singleQuote */ : 34 /* doubleQuote */; - const entries = completion.types.map((type) => ({ - name: escapeString(type.value, quoteChar), - kindModifiers: "" /* none */, - kind: "string" /* string */, - sortText: SortText.LocationPriority, - replacementSpan: getReplacementSpanForContextToken(contextToken) - })); - return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: completion.isNewIdentifier, optionalReplacementSpan, entries }; - } + case 1 /* Properties */: + { + const entries = createSortedArray(); + getCompletionEntriesFromSymbols(completion.symbols, entries, contextToken, contextToken, sourceFile, position, sourceFile, host, program, 99 /* ESNext */, log, 4 /* String */, preferences, options, /*formatContext*/ + void 0, /*isTypeOnlyLocation*/ + void 0, /*propertyAccessToConvert*/ + void 0, /*jsxIdentifierExpected*/ + void 0, /*isJsxInitializer*/ + void 0, /*importStatementCompletion*/ + void 0, /*recommendedCompletion*/ + void 0, /*symbolToOriginInfoMap*/ + void 0, /*symbolToSortTextMap*/ + void 0, /*isJsxIdentifierExpected*/ + void 0, /*isRightOfOpenTag*/ + void 0, includeSymbol); + return { + isGlobalCompletion: false, + isMemberCompletion: true, + isNewIdentifierLocation: completion.hasIndexSignature, + optionalReplacementSpan, + entries + }; + } + case 2 /* Types */: + { + const quoteChar = contextToken.kind === 15 /* NoSubstitutionTemplateLiteral */ ? 96 /* backtick */ : startsWith(getTextOfNode(contextToken), "'") ? 39 /* singleQuote */ : 34 /* doubleQuote */; + const entries = completion.types.map(type => ({ + name: escapeString(type.value, quoteChar), + kindModifiers: "" /* none */, + kind: "string" /* string */, + sortText: SortText.LocationPriority, + replacementSpan: getReplacementSpanForContextToken(contextToken) + })); + return { + isGlobalCompletion: false, + isMemberCompletion: false, + isNewIdentifierLocation: completion.isNewIdentifier, + optionalReplacementSpan, + entries + }; + } default: return Debug.assertNever(completion); } } function getStringLiteralCompletionDetails(name, sourceFile, position, contextToken, checker, options, host, cancellationToken, preferences) { - if (!contextToken || !isStringLiteralLike(contextToken)) - return void 0; + if (!contextToken || !isStringLiteralLike(contextToken)) return void 0; const completions = getStringLiteralCompletionEntries(sourceFile, contextToken, position, checker, options, host, preferences); return completions && stringLiteralCompletionDetails(name, contextToken, completions, sourceFile, checker, cancellationToken); } function stringLiteralCompletionDetails(name, location, completion, sourceFile, checker, cancellationToken) { switch (completion.kind) { - case 0 /* Paths */: { - const match = find(completion.paths, (p) => p.name === name); - return match && createCompletionDetails(name, kindModifiersFromExtension(match.extension), match.kind, [textPart(name)]); - } - case 1 /* Properties */: { - const match = find(completion.symbols, (s) => s.name === name); - return match && createCompletionDetailsForSymbol(match, match.name, checker, sourceFile, location, cancellationToken); - } + case 0 /* Paths */: + { + const match = find(completion.paths, p => p.name === name); + return match && createCompletionDetails(name, kindModifiersFromExtension(match.extension), match.kind, [textPart(name)]); + } + case 1 /* Properties */: + { + const match = find(completion.symbols, s => s.name === name); + return match && createCompletionDetailsForSymbol(match, match.name, checker, sourceFile, location, cancellationToken); + } case 2 /* Types */: - return find(completion.types, (t) => t.value === name) ? createCompletionDetails(name, "" /* none */, "string" /* string */, [textPart(name)]) : void 0; + return find(completion.types, t => t.value === name) ? createCompletionDetails(name, "" /* none */, "string" /* string */, [textPart(name)]) : void 0; default: return Debug.assertNever(completion); } @@ -160332,8 +144447,24 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} function convertPathCompletions(pathCompletions) { const isGlobalCompletion = false; const isNewIdentifierLocation = true; - const entries = pathCompletions.map(({ name, kind, span, extension }) => ({ name, kind, kindModifiers: kindModifiersFromExtension(extension), sortText: SortText.LocationPriority, replacementSpan: span })); - return { isGlobalCompletion, isMemberCompletion: false, isNewIdentifierLocation, entries }; + const entries = pathCompletions.map(({ + name, + kind, + span, + extension + }) => ({ + name, + kind, + kindModifiers: kindModifiersFromExtension(extension), + sortText: SortText.LocationPriority, + replacementSpan: span + })); + return { + isGlobalCompletion, + isMemberCompletion: false, + isNewIdentifierLocation, + entries + }; } function kindModifiersFromExtension(extension) { switch (extension) { @@ -160372,25 +144503,33 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} function getStringLiteralCompletionEntries(sourceFile, node, position, typeChecker, compilerOptions, host, preferences) { const parent2 = walkUpParentheses(node.parent); switch (parent2.kind) { - case 201 /* LiteralType */: { - const grandParent = walkUpParentheses(parent2.parent); - if (grandParent.kind === 205 /* ImportType */) { - return { kind: 0 /* Paths */, paths: getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker, preferences) }; + case 201 /* LiteralType */: + { + const grandParent = walkUpParentheses(parent2.parent); + if (grandParent.kind === 205 /* ImportType */) { + return { + kind: 0 /* Paths */, + paths: getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker, preferences) + }; + } + return fromUnionableLiteralType(grandParent); } - return fromUnionableLiteralType(grandParent); - } case 303 /* PropertyAssignment */: if (isObjectLiteralExpression(parent2.parent) && parent2.name === node) { return stringLiteralCompletionsForObjectLiteral(typeChecker, parent2.parent); } return fromContextualType() || fromContextualType(0 /* None */); - case 212 /* ElementAccessExpression */: { - const { expression, argumentExpression } = parent2; - if (node === skipParentheses(argumentExpression)) { - return stringLiteralCompletionsFromProperties(typeChecker.getTypeAtLocation(expression)); + case 212 /* ElementAccessExpression */: + { + const { + expression, + argumentExpression + } = parent2; + if (node === skipParentheses(argumentExpression)) { + return stringLiteralCompletionsFromProperties(typeChecker.getTypeAtLocation(expression)); + } + return void 0; } - return void 0; - } case 213 /* CallExpression */: case 214 /* NewExpression */: case 291 /* JsxAttribute */: @@ -160398,48 +144537,74 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} const argumentInfo = ts_SignatureHelp_exports.getArgumentInfoForCompletions(parent2.kind === 291 /* JsxAttribute */ ? parent2.parent : node, position, sourceFile); return argumentInfo && getStringLiteralCompletionsFromSignature(argumentInfo.invocation, node, argumentInfo, typeChecker) || fromContextualType(0 /* None */); } + case 272 /* ImportDeclaration */: case 278 /* ExportDeclaration */: case 283 /* ExternalModuleReference */: - return { kind: 0 /* Paths */, paths: getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker, preferences) }; + return { + kind: 0 /* Paths */, + paths: getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker, preferences) + }; case 296 /* CaseClause */: const tracker = newCaseClauseTracker(typeChecker, parent2.parent.clauses); const contextualTypes = fromContextualType(); if (!contextualTypes) { return; } - const literals = contextualTypes.types.filter((literal) => !tracker.hasValue(literal.value)); - return { kind: 2 /* Types */, types: literals, isNewIdentifier: false }; + const literals = contextualTypes.types.filter(literal => !tracker.hasValue(literal.value)); + return { + kind: 2 /* Types */, + types: literals, + isNewIdentifier: false + }; default: return fromContextualType() || fromContextualType(0 /* None */); } + function fromUnionableLiteralType(grandParent) { switch (grandParent.kind) { case 233 /* ExpressionWithTypeArguments */: - case 183 /* TypeReference */: { - const typeArgument = findAncestor(parent2, (n) => n.parent === grandParent); - if (typeArgument) { - return { kind: 2 /* Types */, types: getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(typeArgument)), isNewIdentifier: false }; + case 183 /* TypeReference */: + { + const typeArgument = findAncestor(parent2, n => n.parent === grandParent); + if (typeArgument) { + return { + kind: 2 /* Types */, + types: getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(typeArgument)), + isNewIdentifier: false + }; + } + return void 0; } - return void 0; - } case 199 /* IndexedAccessType */: - const { indexType, objectType } = grandParent; + const { + indexType, + objectType + } = grandParent; if (!rangeContainsPosition(indexType, position)) { return void 0; } return stringLiteralCompletionsFromProperties(typeChecker.getTypeFromTypeNode(objectType)); - case 192 /* UnionType */: { - const result = fromUnionableLiteralType(walkUpParentheses(grandParent.parent)); - if (!result) { - return void 0; + case 192 /* UnionType */: + { + const result = fromUnionableLiteralType(walkUpParentheses(grandParent.parent)); + if (!result) { + return void 0; + } + const alreadyUsedTypes = getAlreadyUsedTypesInStringLiteralUnion(grandParent, parent2); + if (result.kind === 1 /* Properties */) { + return { + kind: 1 /* Properties */, + symbols: result.symbols.filter(sym => !contains(alreadyUsedTypes, sym.name)), + hasIndexSignature: result.hasIndexSignature + }; + } + return { + kind: 2 /* Types */, + types: result.types.filter(t => !contains(alreadyUsedTypes, t.value)), + isNewIdentifier: false + }; } - const alreadyUsedTypes = getAlreadyUsedTypesInStringLiteralUnion(grandParent, parent2); - if (result.kind === 1 /* Properties */) { - return { kind: 1 /* Properties */, symbols: result.symbols.filter((sym) => !contains(alreadyUsedTypes, sym.name)), hasIndexSignature: result.hasIndexSignature }; - } - return { kind: 2 /* Types */, types: result.types.filter((t) => !contains(alreadyUsedTypes, t.value)), isNewIdentifier: false }; - } default: return void 0; } @@ -160449,7 +144614,11 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (!types.length) { return; } - return { kind: 2 /* Types */, types, isNewIdentifier: false }; + return { + kind: 2 /* Types */, + types, + isNewIdentifier: false + }; } } function walkUpParentheses(node) { @@ -160463,16 +144632,15 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } } function getAlreadyUsedTypesInStringLiteralUnion(union, current) { - return mapDefined(union.types, (type) => type !== current && isLiteralTypeNode(type) && isStringLiteral(type.literal) ? type.literal.text : void 0); + return mapDefined(union.types, type => type !== current && isLiteralTypeNode(type) && isStringLiteral(type.literal) ? type.literal.text : void 0); } function getStringLiteralCompletionsFromSignature(call, arg, argumentInfo, checker) { let isNewIdentifier = false; - const uniques = /* @__PURE__ */ new Map(); + const uniques = /* @__PURE__ */new Map(); 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; + const types = flatMap(candidates, candidate => { + if (!signatureHasRestParameter(candidate) && argumentInfo.argumentCount > candidate.parameters.length) return; let type = candidate.getTypeParameterAtPosition(argumentInfo.argumentIndex); if (isJsxOpeningLikeElement(call)) { const propType = checker.getTypeOfPropertyOfType(type, getTextOfJsxAttributeName(editingArgument.name)); @@ -160483,53 +144651,64 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} isNewIdentifier = isNewIdentifier || !!(type.flags & 4 /* String */); return getStringLiteralTypes(type, uniques); }); - return length(types) ? { kind: 2 /* Types */, types, isNewIdentifier } : void 0; + return length(types) ? { + kind: 2 /* Types */, + types, + isNewIdentifier + } : void 0; } function stringLiteralCompletionsFromProperties(type) { return type && { kind: 1 /* Properties */, - symbols: filter(type.getApparentProperties(), (prop) => !(prop.valueDeclaration && isPrivateIdentifierClassElementDeclaration(prop.valueDeclaration))), + symbols: filter(type.getApparentProperties(), prop => !(prop.valueDeclaration && isPrivateIdentifierClassElementDeclaration(prop.valueDeclaration))), hasIndexSignature: hasIndexSignature(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, - completionsType, - objectLiteralExpression, - checker - ); + const symbols = getPropertiesForObjectExpression(contextualType, completionsType, objectLiteralExpression, checker); return { kind: 1 /* Properties */, symbols, hasIndexSignature: hasIndexSignature(contextualType) }; } - function getStringLiteralTypes(type, uniques = /* @__PURE__ */ new Map()) { - if (!type) - return emptyArray; + function getStringLiteralTypes(type, uniques = /* @__PURE__ */new Map()) { + if (!type) return emptyArray; type = skipConstraint(type); - return type.isUnion() ? flatMap(type.types, (t) => getStringLiteralTypes(t, uniques)) : type.isStringLiteral() && !(type.flags & 1024 /* EnumLiteral */) && addToSeen(uniques, type.value) ? [type] : emptyArray; + return type.isUnion() ? flatMap(type.types, t => getStringLiteralTypes(t, uniques)) : type.isStringLiteral() && !(type.flags & 1024 /* EnumLiteral */) && addToSeen(uniques, type.value) ? [type] : emptyArray; } function nameAndKind(name, kind, extension) { - return { name, kind, extension }; + return { + name, + kind, + extension + }; } function directoryResult(name) { - return nameAndKind( - name, - "directory" /* directory */, - /*extension*/ - void 0 - ); + return nameAndKind(name, "directory" /* directory */, /*extension*/ + void 0); } function addReplacementSpans(text, textStart, names) { const span = getDirectoryFragmentTextSpan(text, textStart); const wholeSpan = text.length === 0 ? void 0 : createTextSpan(textStart, text.length); - return names.map(({ name, kind, extension }) => name.includes(directorySeparator) || name.includes(altDirectorySeparator) ? { name, kind, extension, span: wholeSpan } : { name, kind, extension, span }); + return names.map(({ + name, + kind, + extension + }) => name.includes(directorySeparator) || name.includes(altDirectorySeparator) ? { + name, + kind, + extension, + span: wholeSpan + } : { + name, + kind, + extension, + span + }); } function getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker, preferences) { return addReplacementSpans(node.text, node.getStart(sourceFile) + 1, getStringLiteralCompletionsFromModuleNamesWorker(sourceFile, node, compilerOptions, host, typeChecker, preferences)); @@ -160553,32 +144732,16 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } function getCompletionEntriesForRelativeModules(literalValue, scriptDirectory, compilerOptions, host, scriptPath, extensionOptions) { if (compilerOptions.rootDirs) { - return getCompletionEntriesForDirectoryFragmentWithRootDirs( - compilerOptions.rootDirs, - literalValue, - scriptDirectory, - extensionOptions, - compilerOptions, - host, - scriptPath - ); + return getCompletionEntriesForDirectoryFragmentWithRootDirs(compilerOptions.rootDirs, literalValue, scriptDirectory, extensionOptions, compilerOptions, host, scriptPath); } else { - return arrayFrom(getCompletionEntriesForDirectoryFragment( - literalValue, - scriptDirectory, - extensionOptions, - host, - /*moduleSpecifierIsRelative*/ - true, - scriptPath - ).values()); + return arrayFrom(getCompletionEntriesForDirectoryFragment(literalValue, scriptDirectory, extensionOptions, host, /*moduleSpecifierIsRelative*/ + true, scriptPath).values()); } } function getSupportedExtensionsForModuleResolution(compilerOptions, typeChecker) { - const ambientModulesExtensions = !typeChecker ? [] : mapDefined(typeChecker.getAmbientModules(), (module2) => { + 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]; @@ -160586,27 +144749,16 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return moduleResolutionUsesNodeModules(moduleResolution) ? getSupportedExtensionsWithJsonIfResolveJsonModule(compilerOptions, extensions) : extensions; } function getBaseDirectoriesFromRootDirs(rootDirs, basePath, scriptDirectory, ignoreCase) { - rootDirs = rootDirs.map((rootDirectory) => ensureTrailingDirectorySeparator(normalizePath(isRootedDiskPath(rootDirectory) ? rootDirectory : combinePaths(basePath, rootDirectory)))); - const relativeDirectory = firstDefined(rootDirs, (rootDirectory) => containsPath(rootDirectory, scriptDirectory, basePath, ignoreCase) ? scriptDirectory.substr(rootDirectory.length) : void 0); - return deduplicate( - [...rootDirs.map((rootDirectory) => combinePaths(rootDirectory, relativeDirectory)), scriptDirectory].map((baseDir) => removeTrailingDirectorySeparator(baseDir)), - equateStringsCaseSensitive, - compareStringsCaseSensitive - ); + rootDirs = rootDirs.map(rootDirectory => ensureTrailingDirectorySeparator(normalizePath(isRootedDiskPath(rootDirectory) ? rootDirectory : combinePaths(basePath, rootDirectory)))); + const relativeDirectory = firstDefined(rootDirs, rootDirectory => containsPath(rootDirectory, scriptDirectory, basePath, ignoreCase) ? scriptDirectory.substr(rootDirectory.length) : void 0); + return deduplicate([...rootDirs.map(rootDirectory => combinePaths(rootDirectory, relativeDirectory)), scriptDirectory].map(baseDir => removeTrailingDirectorySeparator(baseDir)), equateStringsCaseSensitive, compareStringsCaseSensitive); } function getCompletionEntriesForDirectoryFragmentWithRootDirs(rootDirs, fragment, scriptDirectory, extensionOptions, compilerOptions, host, exclude) { const basePath = compilerOptions.project || host.getCurrentDirectory(); const ignoreCase = !(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames()); const baseDirectories = getBaseDirectoriesFromRootDirs(rootDirs, basePath, scriptDirectory, ignoreCase); - return flatMap(baseDirectories, (baseDirectory) => arrayFrom(getCompletionEntriesForDirectoryFragment( - fragment, - baseDirectory, - extensionOptions, - host, - /*moduleSpecifierIsRelative*/ - true, - exclude - ).values())); + return flatMap(baseDirectories, baseDirectory => arrayFrom(getCompletionEntriesForDirectoryFragment(fragment, baseDirectory, extensionOptions, host, /*moduleSpecifierIsRelative*/ + true, exclude).values())); } function getCompletionEntriesForDirectoryFragment(fragment, scriptDirectory, extensionOptions, host, moduleSpecifierIsRelative, exclude, result = createNameAndKindSet()) { var _a; @@ -160641,24 +144793,20 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } } const ignoreCase = !(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames()); - if (!tryDirectoryExists(host, baseDirectory)) - return result; - const files = tryReadDirectory( - host, - baseDirectory, - extensionOptions.extensionsToSearch, - /*exclude*/ - void 0, - /*include*/ - ["./*"] - ); + if (!tryDirectoryExists(host, baseDirectory)) return result; + const files = tryReadDirectory(host, baseDirectory, extensionOptions.extensionsToSearch, /*exclude*/ + void 0, /*include*/ + ["./*"]); if (files) { for (let filePath of files) { filePath = normalizePath(filePath); if (exclude && comparePaths(filePath, exclude, scriptDirectory, ignoreCase) === 0 /* EqualTo */) { continue; } - const { name, extension } = getFilenameWithExtensionOption(getBaseFileName(filePath), host.getCompilationSettings(), extensionOptions); + const { + name, + extension + } = getFilenameWithExtensionOption(getBaseFileName(filePath), host.getCompilationSettings(), extensionOptions); result.add(nameAndKind(name, "script" /* scriptElement */, extension)); } } @@ -160676,27 +144824,51 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} function getFilenameWithExtensionOption(name, compilerOptions, extensionOptions) { const nonJsResult = ts_moduleSpecifiers_exports.tryGetRealFileNameForNonJsDeclarationFileName(name); if (nonJsResult) { - return { name: nonJsResult, extension: tryGetExtensionFromPath2(nonJsResult) }; + return { + name: nonJsResult, + extension: tryGetExtensionFromPath2(nonJsResult) + }; } if (extensionOptions.referenceKind === 0 /* Filename */) { - return { name, extension: tryGetExtensionFromPath2(name) }; + return { + name, + extension: tryGetExtensionFromPath2(name) + }; } const endingPreference = getModuleSpecifierEndingPreference(extensionOptions.endingPreference, extensionOptions.resolutionMode, compilerOptions, extensionOptions.importingSourceFile); if (endingPreference === 3 /* TsExtension */) { if (fileExtensionIsOneOf(name, supportedTSImplementationExtensions)) { - return { name, extension: tryGetExtensionFromPath2(name) }; + return { + name, + extension: tryGetExtensionFromPath2(name) + }; } const outputExtension2 = ts_moduleSpecifiers_exports.tryGetJSExtensionForFile(name, compilerOptions); - return outputExtension2 ? { name: changeExtension(name, outputExtension2), extension: outputExtension2 } : { name, extension: tryGetExtensionFromPath2(name) }; + return outputExtension2 ? { + name: changeExtension(name, outputExtension2), + extension: outputExtension2 + } : { + name, + extension: tryGetExtensionFromPath2(name) + }; } if ((endingPreference === 0 /* Minimal */ || endingPreference === 1 /* Index */) && fileExtensionIsOneOf(name, [".js" /* Js */, ".jsx" /* Jsx */, ".ts" /* Ts */, ".tsx" /* Tsx */, ".d.ts" /* Dts */])) { - return { name: removeFileExtension(name), extension: tryGetExtensionFromPath2(name) }; + return { + name: removeFileExtension(name), + extension: tryGetExtensionFromPath2(name) + }; } const outputExtension = ts_moduleSpecifiers_exports.tryGetJSExtensionForFile(name, compilerOptions); - return outputExtension ? { name: changeExtension(name, outputExtension), extension: outputExtension } : { name, extension: tryGetExtensionFromPath2(name) }; + return outputExtension ? { + name: changeExtension(name, outputExtension), + extension: outputExtension + } : { + name, + extension: tryGetExtensionFromPath2(name) + }; } function addCompletionEntriesFromPaths(result, fragment, baseDirectory, extensionOptions, host, paths) { - const getPatternsForKey = (key) => paths[key]; + const getPatternsForKey = key => paths[key]; const comparePaths2 = (a, b) => { const patternA = tryParsePattern(a); const patternB = tryParsePattern(b); @@ -160710,48 +144882,45 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} 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) { matchedPath = key; - pathResults = pathResults.filter((r) => !r.matchedPattern); + pathResults = pathResults.filter(r => !r.matchedPattern); } if (typeof pathPattern === "string" || matchedPath === void 0 || comparePaths2(key, matchedPath) !== 1 /* GreaterThan */) { pathResults.push({ matchedPattern: isMatch, - results: getCompletionsForPathMapping(keyWithoutLeadingDotSlash, patterns, fragment, baseDirectory, extensionOptions, host).map(({ name, kind, extension }) => nameAndKind(name, kind, extension)) + results: getCompletionsForPathMapping(keyWithoutLeadingDotSlash, patterns, fragment, baseDirectory, extensionOptions, host).map(({ + name, + kind, + extension + }) => nameAndKind(name, kind, extension)) }); } } } - pathResults.forEach((pathResult) => pathResult.results.forEach((r) => result.add(r))); + pathResults.forEach(pathResult => pathResult.results.forEach(r => result.add(r))); return matchedPath !== void 0; } function getCompletionEntriesForNonRelativeModules(fragment, scriptPath, mode, compilerOptions, host, extensionOptions, typeChecker) { - const { baseUrl, paths } = compilerOptions; + const { + baseUrl, + paths + } = compilerOptions; const result = createNameAndKindSet(); const moduleResolution = getEmitModuleResolutionKind(compilerOptions); if (baseUrl) { const absolute = normalizePath(combinePaths(host.getCurrentDirectory(), baseUrl)); - getCompletionEntriesForDirectoryFragment( - fragment, - absolute, - extensionOptions, - host, - /*moduleSpecifierIsRelative*/ - false, - /*exclude*/ - void 0, - result - ); + getCompletionEntriesForDirectoryFragment(fragment, absolute, extensionOptions, host, /*moduleSpecifierIsRelative*/ + false, /*exclude*/ + void 0, result); } if (paths) { const absolute = getPathsBasePath(compilerOptions, host); @@ -160759,24 +144928,16 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } const fragmentDirectory = getFragmentDirectory(fragment); for (const ambientName of getAmbientModuleCompletions(fragment, fragmentDirectory, typeChecker)) { - result.add(nameAndKind( - ambientName, - "external module name" /* externalModuleName */, - /*extension*/ - void 0 - )); + result.add(nameAndKind(ambientName, "external module name" /* externalModuleName */, /*extension*/ + void 0)); } getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, fragmentDirectory, extensionOptions, result); if (moduleResolutionUsesNodeModules(moduleResolution)) { let foundGlobal = false; if (fragmentDirectory === void 0) { for (const moduleName of enumerateNodeModulesVisibleToScript(host, scriptPath)) { - const moduleResult = nameAndKind( - moduleName, - "external module name" /* externalModuleName */, - /*extension*/ - void 0 - ); + const moduleResult = nameAndKind(moduleName, "external module name" /* externalModuleName */, /*extension*/ + void 0); if (!result.has(moduleResult.name)) { foundGlobal = true; result.add(moduleResult); @@ -160784,25 +144945,17 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } } if (!foundGlobal) { - let ancestorLookup = (ancestor) => { + let ancestorLookup = ancestor => { const nodeModules = combinePaths(ancestor, "node_modules"); if (tryDirectoryExists(host, nodeModules)) { - getCompletionEntriesForDirectoryFragment( - fragment, - nodeModules, - extensionOptions, - host, - /*moduleSpecifierIsRelative*/ - false, - /*exclude*/ - void 0, - result - ); + getCompletionEntriesForDirectoryFragment(fragment, nodeModules, extensionOptions, host, /*moduleSpecifierIsRelative*/ + false, /*exclude*/ + void 0, result); } }; if (fragmentDirectory && getResolvePackageJsonExports(compilerOptions)) { const nodeModulesDirectoryLookup = ancestorLookup; - ancestorLookup = (ancestor) => { + ancestorLookup = ancestor => { const components = getPathComponents(fragment); components.shift(); let packagePath = components.shift(); @@ -160828,16 +144981,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} const keys = getOwnKeys(exports); const fragmentSubpath = components.join("/") + (components.length && hasTrailingDirectorySeparator(fragment) ? "/" : ""); const conditions = getConditions(compilerOptions, mode); - addCompletionEntriesFromPathsOrExports( - result, - fragmentSubpath, - packageDirectory, - extensionOptions, - host, - keys, - (key) => singleElementArray(getPatternFromFirstMatchingCondition(exports[key], conditions)), - comparePatternKeys - ); + addCompletionEntriesFromPathsOrExports(result, fragmentSubpath, packageDirectory, extensionOptions, host, keys, key => singleElementArray(getPatternFromFirstMatchingCondition(exports[key], conditions)), comparePatternKeys); return; } } @@ -160873,14 +145017,24 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} const remainingFragment = tryRemovePrefix(fragment, pathPrefix); if (remainingFragment === void 0) { const starIsFullPathComponent = path[path.length - 2] === "/"; - return starIsFullPathComponent ? justPathMappingName(pathPrefix, "directory" /* directory */) : flatMap(patterns, (pattern) => { + return starIsFullPathComponent ? justPathMappingName(pathPrefix, "directory" /* directory */) : flatMap(patterns, pattern => { var _a; - return (_a = getModulesForPathsPattern("", packageDirectory, pattern, extensionOptions, host)) == null ? void 0 : _a.map(({ name, ...rest }) => ({ name: pathPrefix + name, ...rest })); + return (_a = getModulesForPathsPattern("", packageDirectory, pattern, extensionOptions, host)) == null ? void 0 : _a.map(({ + name, + ...rest + }) => ({ + name: pathPrefix + name, + ...rest + })); }); } - return flatMap(patterns, (pattern) => getModulesForPathsPattern(remainingFragment, packageDirectory, pattern, extensionOptions, host)); + return flatMap(patterns, pattern => getModulesForPathsPattern(remainingFragment, packageDirectory, pattern, extensionOptions, host)); function justPathMappingName(name, kind) { - return startsWith(name, fragment) ? [{ name: removeTrailingDirectorySeparator(name), kind, extension: void 0 }] : emptyArray; + return startsWith(name, fragment) ? [{ + name: removeTrailingDirectorySeparator(name), + kind, + extension: void 0 + }] : emptyArray; } } function getModulesForPathsPattern(fragment, packageDirectory, pattern, extensionOptions, host) { @@ -160902,28 +145056,25 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} const matchingSuffixes = declarationExtension ? [changeExtension(normalizedSuffix, declarationExtension), normalizedSuffix] : [normalizedSuffix]; const baseDirectory = normalizePath(combinePaths(packageDirectory, expandedPrefixDirectory)); const completePrefix = fragmentHasPath ? baseDirectory : ensureTrailingDirectorySeparator(baseDirectory) + normalizedPrefixBase; - const includeGlobs = normalizedSuffix ? matchingSuffixes.map((suffix) => "**/*" + suffix) : ["./*"]; - const matches = mapDefined(tryReadDirectory( - host, - baseDirectory, - extensionOptions.extensionsToSearch, - /*exclude*/ - void 0, - includeGlobs - ), (match) => { + const includeGlobs = normalizedSuffix ? matchingSuffixes.map(suffix => "**/*" + suffix) : ["./*"]; + const matches = mapDefined(tryReadDirectory(host, baseDirectory, extensionOptions.extensionsToSearch, /*exclude*/ + void 0, includeGlobs), match => { const trimmedWithPattern = trimPrefixAndSuffix(match); if (trimmedWithPattern) { if (containsSlash(trimmedWithPattern)) { return directoryResult(getPathComponents(removeLeadingDirectorySeparator(trimmedWithPattern))[1]); } - const { name, extension } = getFilenameWithExtensionOption(trimmedWithPattern, host.getCompilationSettings(), extensionOptions); + const { + name, + extension + } = getFilenameWithExtensionOption(trimmedWithPattern, host.getCompilationSettings(), extensionOptions); return nameAndKind(name, "script" /* scriptElement */, extension); } }); - const directories = normalizedSuffix ? emptyArray : mapDefined(tryGetDirectories(host, baseDirectory), (dir) => dir === "node_modules" ? void 0 : directoryResult(dir)); + const directories = normalizedSuffix ? emptyArray : mapDefined(tryGetDirectories(host, baseDirectory), dir => dir === "node_modules" ? void 0 : directoryResult(dir)); return [...matches, ...directories]; function trimPrefixAndSuffix(path) { - return firstDefined(matchingSuffixes, (suffix) => { + return firstDefined(matchingSuffixes, suffix => { const inner = withoutStartAndEnd(normalizePath(path), completePrefix, suffix); return inner === void 0 ? void 0 : removeLeadingDirectorySeparator(inner); }); @@ -160936,18 +145087,18 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return path[0] === directorySeparator ? path.slice(1) : path; } function getAmbientModuleCompletions(fragment, fragmentDirectory, checker) { - const ambientModules = checker.getAmbientModules().map((sym) => stripQuotes(sym.name)); - const nonRelativeModuleNames = ambientModules.filter((moduleName) => startsWith(moduleName, fragment) && !moduleName.includes("*")); + const ambientModules = checker.getAmbientModules().map(sym => stripQuotes(sym.name)); + const nonRelativeModuleNames = ambientModules.filter(moduleName => startsWith(moduleName, fragment) && !moduleName.includes("*")); if (fragmentDirectory !== void 0) { const moduleNameWithSeparator = ensureTrailingDirectorySeparator(fragmentDirectory); - return nonRelativeModuleNames.map((nonRelativeModuleName) => removePrefix(nonRelativeModuleName, moduleNameWithSeparator)); + return nonRelativeModuleNames.map(nonRelativeModuleName => removePrefix(nonRelativeModuleName, moduleNameWithSeparator)); } return nonRelativeModuleNames; } function getTripleSlashReferenceCompletion(sourceFile, position, compilerOptions, host) { const token = getTokenAtPosition(sourceFile, position); const commentRanges = getLeadingCommentRanges(sourceFile.text, token.pos); - const range = commentRanges && find(commentRanges, (commentRange) => position >= commentRange.pos && position <= commentRange.end); + const range = commentRanges && find(commentRanges, commentRange => position >= commentRange.pos && position <= commentRange.end); if (!range) { return void 0; } @@ -160958,19 +145109,12 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } const [, prefix, kind, toComplete] = match; const scriptPath = getDirectoryPath(sourceFile.path); - const names = kind === "path" ? getCompletionEntriesForDirectoryFragment( - toComplete, - scriptPath, - getExtensionOptions(compilerOptions, 0 /* Filename */, sourceFile), - host, - /*moduleSpecifierIsRelative*/ - true, - sourceFile.path - ) : kind === "types" ? getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, getFragmentDirectory(toComplete), getExtensionOptions(compilerOptions, 1 /* ModuleSpecifier */, sourceFile)) : Debug.fail(); + const names = kind === "path" ? getCompletionEntriesForDirectoryFragment(toComplete, scriptPath, getExtensionOptions(compilerOptions, 0 /* Filename */, sourceFile), host, /*moduleSpecifierIsRelative*/ + true, sourceFile.path) : kind === "types" ? getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, getFragmentDirectory(toComplete), getExtensionOptions(compilerOptions, 1 /* ModuleSpecifier */, sourceFile)) : Debug.fail(); return addReplacementSpans(toComplete, range.pos + prefix.length, arrayFrom(names.values())); } function getCompletionEntriesFromTypings(host, options, scriptPath, fragmentDirectory, extensionOptions, result = createNameAndKindSet()) { - const seen = /* @__PURE__ */ new Map(); + const seen = /* @__PURE__ */new Map(); const typeRoots = tryAndIgnoreErrors(() => getEffectiveTypeRoots(options, host)) || emptyArray; for (const root of typeRoots) { getCompletionEntriesFromDirectories(root); @@ -160981,52 +145125,36 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } 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( - packageName, - "external module name" /* externalModuleName */, - /*extension*/ - void 0 - )); + result.add(nameAndKind(packageName, "external module name" /* externalModuleName */, /*extension*/ + void 0)); seen.set(packageName, true); } } else { const baseDirectory = combinePaths(directory, typeDirectoryName); const remainingFragment = tryRemoveDirectoryPrefix(fragmentDirectory, packageName, hostGetCanonicalFileName(host)); if (remainingFragment !== void 0) { - getCompletionEntriesForDirectoryFragment( - remainingFragment, - baseDirectory, - extensionOptions, - host, - /*moduleSpecifierIsRelative*/ - false, - /*exclude*/ - void 0, - result - ); + getCompletionEntriesForDirectoryFragment(remainingFragment, baseDirectory, extensionOptions, host, /*moduleSpecifierIsRelative*/ + false, /*exclude*/ + void 0, result); } } } } } 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); @@ -161048,6 +145176,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} const slashCharCode = path.charCodeAt(slashIndex); return slashCharCode === 47 /* slash */ || slashCharCode === 92 /* backslash */; } + return false; } function containsSlash(fragment) { @@ -161060,6 +145189,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} var init_stringCompletions = __esm({ "src/services/stringCompletions.ts"() { "use strict"; + init_ts4(); init_ts_Completions(); kindPrecedence = { @@ -161081,6 +145211,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} var init_ts_Completions_StringCompletions = __esm({ "src/services/_namespaces/ts.Completions.StringCompletions.ts"() { "use strict"; + init_stringCompletions(); } }); @@ -161106,6 +145237,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} var init_ts_Completions = __esm({ "src/services/_namespaces/ts.Completions.ts"() { "use strict"; + init_completions(); init_ts_Completions_StringCompletions(); } @@ -161115,18 +145247,30 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} function createImportTracker(sourceFiles, sourceFilesSet, checker, cancellationToken) { const allDirectImports = getDirectImportsMap(sourceFiles, checker, cancellationToken); return (exportSymbol, exportInfo, isForRename) => { - const { directImports, indirectUsers } = getImportersForExport(sourceFiles, sourceFilesSet, allDirectImports, exportInfo, checker, cancellationToken); - return { indirectUsers, ...getSearchesFromDirectImports(directImports, exportSymbol, exportInfo.exportKind, checker, isForRename) }; + const { + directImports, + indirectUsers + } = getImportersForExport(sourceFiles, sourceFilesSet, allDirectImports, exportInfo, checker, cancellationToken); + return { + indirectUsers, + ...getSearchesFromDirectImports(directImports, exportSymbol, exportInfo.exportKind, checker, isForRename) + }; }; } - function getImportersForExport(sourceFiles, sourceFilesSet, allDirectImports, { exportingModuleSymbol, exportKind }, checker, cancellationToken) { + function getImportersForExport(sourceFiles, sourceFilesSet, allDirectImports, { + exportingModuleSymbol, + exportKind + }, checker, cancellationToken) { const markSeenDirectImport = nodeSeenTracker(); const markSeenIndirectUser = nodeSeenTracker(); const directImports = []; const isAvailableThroughGlobal = !!exportingModuleSymbol.globalExports; const indirectUserDeclarations = isAvailableThroughGlobal ? void 0 : []; handleDirectImports(exportingModuleSymbol); - return { directImports, indirectUsers: getIndirectUsers() }; + return { + directImports, + indirectUsers: getIndirectUsers() + }; function getIndirectUsers() { if (isAvailableThroughGlobal) { return sourceFiles; @@ -161147,8 +145291,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (!markSeenDirectImport(direct)) { continue; } - if (cancellationToken) - cancellationToken.throwIfCancellationRequested(); + if (cancellationToken) cancellationToken.throwIfCancellationRequested(); switch (direct.kind) { case 213 /* CallExpression */: if (isImportCall(direct)) { @@ -161158,7 +145301,9 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (!isAvailableThroughGlobal) { const parent2 = direct.parent; if (exportKind === 2 /* ExportEquals */ && parent2.kind === 260 /* VariableDeclaration */) { - const { name } = parent2; + const { + name + } = parent2; if (name.kind === 80 /* Identifier */) { directImports.push(name); break; @@ -161169,26 +145314,16 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} case 80 /* Identifier */: break; case 271 /* ImportEqualsDeclaration */: - handleNamespaceImport( - direct, - direct.name, - hasSyntacticModifier(direct, 32 /* Export */), - /*alreadyAddedDirect*/ - false - ); + handleNamespaceImport(direct, direct.name, hasSyntacticModifier(direct, 32 /* Export */), /*alreadyAddedDirect*/ + false); break; case 272 /* ImportDeclaration */: directImports.push(direct); const namedBindings = direct.importClause && direct.importClause.namedBindings; if (namedBindings && namedBindings.kind === 274 /* NamespaceImport */) { - handleNamespaceImport( - direct, - namedBindings.name, - /*isReExport*/ - false, - /*alreadyAddedDirect*/ - true - ); + handleNamespaceImport(direct, namedBindings.name, /*isReExport*/ + false, /*alreadyAddedDirect*/ + true); } else if (!isAvailableThroughGlobal && isDefaultImport(direct)) { addIndirectUser(getSourceFileLikeForImportDeclaration(direct)); } @@ -161197,22 +145332,16 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (!direct.exportClause) { handleDirectImports(getContainingModuleSymbol(direct, checker)); } else if (direct.exportClause.kind === 280 /* NamespaceExport */) { - addIndirectUser( - getSourceFileLikeForImportDeclaration(direct), - /*addTransitiveDependencies*/ - true - ); + addIndirectUser(getSourceFileLikeForImportDeclaration(direct), /*addTransitiveDependencies*/ + true); } else { directImports.push(direct); } break; case 205 /* ImportType */: if (!isAvailableThroughGlobal && direct.isTypeOf && !direct.qualifier && isExported2(direct)) { - addIndirectUser( - direct.getSourceFile(), - /*addTransitiveDependencies*/ - true - ); + addIndirectUser(direct.getSourceFile(), /*addTransitiveDependencies*/ + true); } directImports.push(direct); break; @@ -161224,36 +145353,25 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } function handleImportCall(importCall) { const top = findAncestor(importCall, isAmbientModuleDeclaration) || importCall.getSourceFile(); - addIndirectUser( - top, - /** addTransitiveDependencies */ - !!isExported2( - importCall, - /*stopAtAmbientModule*/ - true - ) - ); + addIndirectUser(top, /** addTransitiveDependencies */ + !!isExported2(importCall, /*stopAtAmbientModule*/ + true)); } function isExported2(node, stopAtAmbientModule = false) { - return findAncestor(node, (node2) => { - if (stopAtAmbientModule && isAmbientModuleDeclaration(node2)) - return "quit"; + return findAncestor(node, node2 => { + if (stopAtAmbientModule && isAmbientModuleDeclaration(node2)) return "quit"; return canHaveModifiers(node2) && some(node2.modifiers, isExportModifier); }); } function handleNamespaceImport(importDeclaration, name, isReExport, alreadyAddedDirect) { if (exportKind === 2 /* ExportEquals */) { - if (!alreadyAddedDirect) - directImports.push(importDeclaration); + if (!alreadyAddedDirect) directImports.push(importDeclaration); } else if (!isAvailableThroughGlobal) { const sourceFileLike = getSourceFileLikeForImportDeclaration(importDeclaration); Debug.assert(sourceFileLike.kind === 312 /* SourceFile */ || sourceFileLike.kind === 267 /* ModuleDeclaration */); if (isReExport || findNamespaceReExports(sourceFileLike, name, checker)) { - addIndirectUser( - sourceFileLike, - /*addTransitiveDependencies*/ - true - ); + addIndirectUser(sourceFileLike, /*addTransitiveDependencies*/ + true); } else { addIndirectUser(sourceFileLike); } @@ -161262,24 +145380,18 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} 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) { for (const directImport of directImports2) { if (!isImportTypeNode(directImport)) { - addIndirectUser( - getSourceFileLikeForImportDeclaration(directImport), - /*addTransitiveDependencies*/ - true - ); + addIndirectUser(getSourceFileLikeForImportDeclaration(directImport), /*addTransitiveDependencies*/ + true); } } } @@ -161299,7 +145411,10 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} handleImport(decl); } } - return { importSearches, singleReferences }; + return { + importSearches, + singleReferences + }; function handleImport(decl) { if (decl.kind === 271 /* ImportEqualsDeclaration */) { if (isExternalModuleImportEquals(decl)) { @@ -161331,7 +145446,13 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } return; } - const { name, namedBindings } = decl.importClause || { name: void 0, namedBindings: void 0 }; + const { + name, + namedBindings + } = decl.importClause || { + name: void 0, + namedBindings: void 0 + }; if (namedBindings) { switch (namedBindings.kind) { case 274 /* NamespaceImport */: @@ -161361,7 +145482,10 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return; } for (const element of namedBindings.elements) { - const { name, propertyName } = element; + const { + name, + propertyName + } = element; if (!isNameMatch((propertyName || name).escapedText)) { continue; } @@ -161380,13 +145504,16 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return name === exportSymbol.escapedName || exportKind !== 0 /* Named */ && name === "default" /* Default */; } } + function findNamespaceReExports(sourceFileLike, name, checker) { const namespaceImportSymbol = checker.getSymbolAtLocation(name); - return !!forEachPossibleImportOrExportStatement(sourceFileLike, (statement) => { - if (!isExportDeclaration(statement)) - return; - const { exportClause, moduleSpecifier } = statement; - return !moduleSpecifier && exportClause && isNamedExports(exportClause) && exportClause.elements.some((element) => checker.getExportSpecifierLocalTargetSymbol(element) === namespaceImportSymbol); + return !!forEachPossibleImportOrExportStatement(sourceFileLike, statement => { + if (!isExportDeclaration(statement)) return; + const { + exportClause, + moduleSpecifier + } = statement; + return !moduleSpecifier && exportClause && isNamedExports(exportClause) && exportClause.elements.some(element => checker.getExportSpecifierLocalTargetSymbol(element) === namespaceImportSymbol); }); } function findModuleReferences(program, sourceFiles, searchModuleSymbol) { @@ -161398,30 +145525,44 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if ((searchSourceFile == null ? void 0 : searchSourceFile.kind) === 312 /* SourceFile */) { for (const ref of referencingFile.referencedFiles) { if (program.getSourceFileFromReference(referencingFile, ref) === searchSourceFile) { - refs.push({ kind: "reference", referencingFile, ref }); + refs.push({ + kind: "reference", + referencingFile, + ref + }); } } for (const ref of referencingFile.typeReferenceDirectives) { const referenced = (_a = program.getResolvedTypeReferenceDirectives().get(ref.fileName, ref.resolutionMode || referencingFile.impliedNodeFormat)) == null ? void 0 : _a.resolvedTypeReferenceDirective; if (referenced !== void 0 && referenced.resolvedFileName === searchSourceFile.fileName) { - refs.push({ kind: "reference", referencingFile, ref }); + refs.push({ + kind: "reference", + referencingFile, + ref + }); } } } forEachImport(referencingFile, (importDecl, moduleSpecifier) => { const moduleSymbol = checker.getSymbolAtLocation(moduleSpecifier); if (moduleSymbol === searchModuleSymbol) { - refs.push(nodeIsSynthesized(importDecl) ? { kind: "implicit", literal: moduleSpecifier, referencingFile } : { kind: "import", literal: moduleSpecifier }); + refs.push(nodeIsSynthesized(importDecl) ? { + kind: "implicit", + literal: moduleSpecifier, + referencingFile + } : { + kind: "import", + literal: moduleSpecifier + }); } }); } return refs; } function getDirectImportsMap(sourceFiles, checker, cancellationToken) { - const map2 = /* @__PURE__ */ new Map(); + 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) { @@ -161437,10 +145578,9 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return map2; } function forEachPossibleImportOrExportStatement(sourceFileLike, action) { - return forEach(sourceFileLike.kind === 312 /* SourceFile */ ? sourceFileLike.statements : sourceFileLike.body.statements, (statement) => ( - // TODO: GH#18217 - action(statement) || isAmbientModuleDeclaration(statement) && forEach(statement.body && statement.body.statements, action) - )); + return forEach(sourceFileLike.kind === 312 /* SourceFile */ ? sourceFileLike.statements : sourceFileLike.body.statements, statement => + // TODO: GH#18217 + action(statement) || isAmbientModuleDeclaration(statement) && forEach(statement.body && statement.body.statements, action)); } function forEachImport(sourceFile, action) { if (sourceFile.externalModuleIndicator || sourceFile.imports !== void 0) { @@ -161448,23 +145588,25 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} action(importFromModuleSpecifier(i), i); } } else { - forEachPossibleImportOrExportStatement(sourceFile, (statement) => { + forEachPossibleImportOrExportStatement(sourceFile, statement => { switch (statement.kind) { case 278 /* ExportDeclaration */: - case 272 /* ImportDeclaration */: { - const decl = statement; - if (decl.moduleSpecifier && isStringLiteral(decl.moduleSpecifier)) { - action(decl, decl.moduleSpecifier); + case 272 /* ImportDeclaration */: + { + const decl = statement; + if (decl.moduleSpecifier && isStringLiteral(decl.moduleSpecifier)) { + action(decl, decl.moduleSpecifier); + } + break; } - break; - } - case 271 /* ImportEqualsDeclaration */: { - const decl = statement; - if (isExternalModuleImportEquals(decl)) { - action(decl, decl.moduleReference.expression); + case 271 /* ImportEqualsDeclaration */: + { + const decl = statement; + if (isExternalModuleImportEquals(decl)) { + action(decl, decl.moduleReference.expression); + } + break; } - break; - } } }); } @@ -161473,15 +145615,14 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return comingFromExport ? getExport() : getExport() || getImport(); function getExport() { var _a; - const { parent: parent2 } = node; + const { + parent: parent2 + } = node; const grandparent = parent2.parent; if (symbol.exportSymbol) { if (parent2.kind === 211 /* PropertyAccessExpression */) { - return ((_a = symbol.declarations) == null ? void 0 : _a.some((d) => d === parent2)) && isBinaryExpression(grandparent) ? getSpecialPropertyExport( - grandparent, - /*useLhsSymbol*/ - false - ) : void 0; + return ((_a = symbol.declarations) == null ? void 0 : _a.some(d => d === parent2)) && isBinaryExpression(grandparent) ? getSpecialPropertyExport(grandparent, /*useLhsSymbol*/ + false) : void 0; } else { return exportInfo(symbol.exportSymbol, getExportKindForDeclaration(parent2)); } @@ -161493,7 +145634,10 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return void 0; } const lhsSymbol = checker.getSymbolAtLocation(exportNode.name); - return { kind: 0 /* Import */, symbol: lhsSymbol }; + return { + kind: 0 /* Import */, + symbol: lhsSymbol + }; } else { return exportInfo(symbol, getExportKindForDeclaration(exportNode)); } @@ -161504,26 +145648,27 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } else if (isExportAssignment(grandparent)) { return getExportAssignmentExport(grandparent); } else if (isBinaryExpression(parent2)) { - return getSpecialPropertyExport( - parent2, - /*useLhsSymbol*/ - true - ); + return getSpecialPropertyExport(parent2, /*useLhsSymbol*/ + true); } else if (isBinaryExpression(grandparent)) { - return getSpecialPropertyExport( - grandparent, - /*useLhsSymbol*/ - true - ); + return getSpecialPropertyExport(grandparent, /*useLhsSymbol*/ + true); } else if (isJSDocTypedefTag(parent2) || isJSDocCallbackTag(parent2)) { return exportInfo(symbol, 0 /* Named */); } } + function getExportAssignmentExport(ex) { - if (!ex.symbol.parent) - return void 0; + 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 } }; + return { + kind: 1 /* Export */, + symbol, + exportInfo: { + exportingModuleSymbol: ex.symbol.parent, + exportKind + } + }; } function getSpecialPropertyExport(node2, useLhsSymbol) { let kind; @@ -161543,30 +145688,35 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } 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) { - return { kind: 0 /* Import */, symbol: importedSymbol }; + return { + kind: 0 /* Import */, + symbol: importedSymbol + }; } } function exportInfo(symbol2, kind) { const exportInfo2 = getExportInfo(symbol2, kind, checker); - return exportInfo2 && { kind: 1 /* Export */, symbol: symbol2, exportInfo: exportInfo2 }; + return exportInfo2 && { + kind: 1 /* Export */, + symbol: symbol2, + exportInfo: exportInfo2 + }; } function getExportKindForDeclaration(node2) { return hasSyntacticModifier(node2, 2048 /* Default */) ? 1 /* Default */ : 0 /* Named */; } } + function getExportEqualsLocalSymbol(importedSymbol, checker) { var _a, _b; if (importedSymbol.flags & 2097152 /* Alias */) { @@ -161591,7 +145741,9 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } } function isNodeImport(node) { - const { parent: parent2 } = node; + const { + parent: parent2 + } = node; switch (parent2.kind) { case 271 /* ImportEqualsDeclaration */: return parent2.name === node && isExternalModuleImportEquals(parent2); @@ -161609,10 +145761,12 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } 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; + return isExternalModuleSymbol(exportingModuleSymbol) ? { + exportingModuleSymbol, + exportKind + } : void 0; } function skipExportSpecifierSymbol(symbol, checker) { if (symbol.declarations) { @@ -161635,7 +145789,9 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (node.kind === 213 /* CallExpression */) { return node.getSourceFile(); } - const { parent: parent2 } = node; + const { + parent: parent2 + } = node; if (parent2.kind === 312 /* SourceFile */) { return parent2; } @@ -161645,21 +145801,24 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} function isAmbientModuleDeclaration(node) { return node.kind === 267 /* ModuleDeclaration */ && node.name.kind === 11 /* StringLiteral */; } + function isExternalModuleImportEquals(eq) { return eq.moduleReference.kind === 283 /* ExternalModuleReference */ && eq.moduleReference.expression.kind === 11 /* StringLiteral */; } + var ExportKind2, ImportExport; var init_importTracker = __esm({ "src/services/importTracker.ts"() { "use strict"; + init_ts4(); - ExportKind2 = /* @__PURE__ */ ((ExportKind3) => { + ExportKind2 = /* @__PURE__ */(ExportKind3 => { ExportKind3[ExportKind3["Named"] = 0] = "Named"; ExportKind3[ExportKind3["Default"] = 1] = "Default"; ExportKind3[ExportKind3["ExportEquals"] = 2] = "ExportEquals"; return ExportKind3; })(ExportKind2 || {}); - ImportExport = /* @__PURE__ */ ((ImportExport2) => { + ImportExport = /* @__PURE__ */(ImportExport2 => { ImportExport2[ImportExport2["Import"] = 0] = "Import"; ImportExport2[ImportExport2["Export"] = 1] = "Export"; return ImportExport2; @@ -161682,8 +145841,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} 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; @@ -161698,24 +145856,26 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } else if (isStringLiteralLike(node)) { const validImport = tryGetImportFromModuleSpecifier(node); if (validImport) { - const declOrStatement = findAncestor(validImport, (node2) => isDeclaration(node2) || isStatement(node2) || isJSDocTag(node2)); + const declOrStatement = findAncestor(validImport, node2 => isDeclaration(node2) || isStatement(node2) || isJSDocTag(node2)); return isDeclaration(declOrStatement) ? getContextNode(declOrStatement) : declOrStatement; } } const propertyName = findAncestor(node, isComputedPropertyName); return propertyName ? getContextNode(propertyName.parent) : void 0; } - if (node.parent.name === node || // node is name of declaration, use parent - isConstructorDeclaration(node.parent) || isExportAssignment(node.parent) || // Property name of the import export specifier or binding pattern, use parent - (isImportOrExportSpecifier(node.parent) || isBindingElement(node.parent)) && node.parent.propertyName === node || // Is default export + if (node.parent.name === node || + // node is name of declaration, use parent + isConstructorDeclaration(node.parent) || isExportAssignment(node.parent) || + // Property name of the import export specifier or binding pattern, use parent + (isImportOrExportSpecifier(node.parent) || isBindingElement(node.parent)) && node.parent.propertyName === node || + // Is default export node.kind === 90 /* DefaultKeyword */ && hasSyntacticModifier(node.parent, 2080 /* ExportDefault */)) { return getContextNode(node.parent); } 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; @@ -161739,33 +145899,36 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} }; case 303 /* PropertyAssignment */: case 304 /* ShorthandPropertyAssignment */: - return isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent) ? getContextNode( - findAncestor(node.parent, (node2) => isBinaryExpression(node2) || isForInOrOfStatement(node2)) - ) : node; + return isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent) ? getContextNode(findAncestor(node.parent, node2 => isBinaryExpression(node2) || isForInOrOfStatement(node2))) : node; default: return 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; + return contextSpan.start !== textSpan.start || contextSpan.length !== textSpan.length ? { + contextSpan + } : void 0; } function findReferencedSymbols(program, cancellationToken, sourceFiles, sourceFile, position) { const node = getTouchingPropertyName(sourceFile, position); - const options = { use: 1 /* References */ }; + const options = { + use: 1 /* References */ + }; const referencedSymbols = Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options); const checker = program.getTypeChecker(); const adjustedNode = Core.getAdjustedNode(node, options); const symbol = isDefinitionForReference(adjustedNode) ? checker.getSymbolAtLocation(adjustedNode) : void 0; - return !referencedSymbols || !referencedSymbols.length ? void 0 : mapDefined(referencedSymbols, ({ definition, references }) => ( - // Only include referenced symbols that have a valid definition. - definition && { - definition: checker.runWithCancellationToken(cancellationToken, (checker2) => definitionToReferencedSymbolDefinitionInfo(definition, checker2, node)), - references: references.map((r) => toReferencedSymbolEntry(r, symbol)) - } - )); + return !referencedSymbols || !referencedSymbols.length ? void 0 : mapDefined(referencedSymbols, ({ + definition, + references + }) => + // Only include referenced symbols that have a valid definition. + definition && { + definition: checker.runWithCancellationToken(cancellationToken, checker2 => definitionToReferencedSymbolDefinitionInfo(definition, checker2, node)), + references: references.map(r => toReferencedSymbolEntry(r, symbol)) + }); } function isDefinitionForReference(node) { return node.kind === 90 /* DefaultKeyword */ || !!getDeclarationFromName(node) || isLiteralComputedPropertyDeclarationName(node) || node.kind === 137 /* ConstructorKeyword */ && isConstructorDeclaration(node.parent); @@ -161778,7 +145941,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} referenceEntries = entries && [...entries]; } else if (entries) { const queue = createQueue(entries); - const seenNodes = /* @__PURE__ */ new Map(); + const seenNodes = /* @__PURE__ */new Map(); while (!queue.isEmpty()) { const entry = queue.dequeue(); if (!addToSeen(seenNodes, getNodeId(entry.node))) { @@ -161792,7 +145955,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } } const checker = program.getTypeChecker(); - return map(referenceEntries, (entry) => toImplementationLocation(entry, checker)); + return map(referenceEntries, entry => toImplementationLocation(entry, checker)); } function getImplementationReferenceEntries(program, cancellationToken, sourceFiles, node, position) { if (node.kind === 312 /* SourceFile */) { @@ -161801,85 +145964,131 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} const checker = program.getTypeChecker(); if (node.parent.kind === 304 /* ShorthandPropertyAssignment */) { const result = []; - Core.getReferenceEntriesForShorthandPropertyAssignment(node, checker, (node2) => result.push(nodeEntry(node2))); + Core.getReferenceEntriesForShorthandPropertyAssignment(node, checker, node2 => result.push(nodeEntry(node2))); return result; } else if (node.kind === 108 /* SuperKeyword */ || isSuperProperty(node.parent)) { const symbol = checker.getSymbolAtLocation(node); return symbol.valueDeclaration && [nodeEntry(symbol.valueDeclaration)]; } else { - return getReferenceEntriesForNode(position, node, program, sourceFiles, cancellationToken, { implementations: true, use: 1 /* References */ }); + return getReferenceEntriesForNode(position, node, program, sourceFiles, cancellationToken, { + implementations: true, + use: 1 /* References */ + }); } } + function findReferenceOrRenameEntries(program, cancellationToken, sourceFiles, node, position, options, convertEntry) { - return map(flattenEntries(Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options)), (entry) => convertEntry(entry, node, program.getTypeChecker())); + return map(flattenEntries(Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options)), entry => convertEntry(entry, node, program.getTypeChecker())); } - function getReferenceEntriesForNode(position, node, program, sourceFiles, cancellationToken, options = {}, sourceFilesSet = new Set(sourceFiles.map((f) => f.fileName))) { + function getReferenceEntriesForNode(position, node, program, sourceFiles, cancellationToken, options = {}, sourceFilesSet = new Set(sourceFiles.map(f => f.fileName))) { return flattenEntries(Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options, sourceFilesSet)); } function flattenEntries(referenceSymbols) { - return referenceSymbols && flatMap(referenceSymbols, (r) => r.references); + return referenceSymbols && flatMap(referenceSymbols, r => r.references); } function definitionToReferencedSymbolDefinitionInfo(def, checker, originalNode) { const info = (() => { switch (def.type) { - case 0 /* Symbol */: { - const { symbol } = def; - const { displayParts: displayParts2, kind: kind2 } = getDefinitionKindAndDisplayParts(symbol, checker, originalNode); - const name2 = displayParts2.map((p) => p.text).join(""); - const declaration = symbol.declarations && firstOrUndefined(symbol.declarations); - const node = declaration ? getNameOfDeclaration(declaration) || declaration : originalNode; - return { - ...getFileAndTextSpanFromNode(node), - name: name2, - kind: kind2, - displayParts: displayParts2, - context: getContextNode(declaration) - }; - } - case 1 /* Label */: { - const { node } = def; - return { ...getFileAndTextSpanFromNode(node), name: node.text, kind: "label" /* label */, displayParts: [displayPart(node.text, 17 /* text */)] }; - } - case 2 /* Keyword */: { - const { node } = def; - const name2 = tokenToString(node.kind); - return { ...getFileAndTextSpanFromNode(node), name: name2, kind: "keyword" /* keyword */, displayParts: [{ text: name2, kind: "keyword" /* keyword */ }] }; - } - case 3 /* This */: { - const { node } = def; - const symbol = checker.getSymbolAtLocation(node); - const displayParts2 = symbol && ts_SymbolDisplay_exports.getSymbolDisplayPartsDocumentationAndSymbolKind( - checker, - symbol, - node.getSourceFile(), - getContainerNode(node), - node - ).displayParts || [textPart("this")]; - return { ...getFileAndTextSpanFromNode(node), name: "this", kind: "var" /* variableElement */, displayParts: displayParts2 }; - } - case 4 /* String */: { - const { node } = def; - return { - ...getFileAndTextSpanFromNode(node), - name: node.text, - kind: "var" /* variableElement */, - displayParts: [displayPart(getTextOfNode(node), 8 /* stringLiteral */)] - }; - } - case 5 /* TripleSlashReference */: { - return { - textSpan: createTextSpanFromRange(def.reference), - sourceFile: def.file, - name: def.reference.fileName, - kind: "string" /* string */, - displayParts: [displayPart(`"${def.reference.fileName}"`, 8 /* stringLiteral */)] - }; - } + case 0 /* Symbol */: + { + const { + symbol + } = def; + const { + displayParts: displayParts2, + kind: kind2 + } = getDefinitionKindAndDisplayParts(symbol, checker, originalNode); + const name2 = displayParts2.map(p => p.text).join(""); + const declaration = symbol.declarations && firstOrUndefined(symbol.declarations); + const node = declaration ? getNameOfDeclaration(declaration) || declaration : originalNode; + return { + ...getFileAndTextSpanFromNode(node), + name: name2, + kind: kind2, + displayParts: displayParts2, + context: getContextNode(declaration) + }; + } + case 1 /* Label */: + { + const { + node + } = def; + return { + ...getFileAndTextSpanFromNode(node), + name: node.text, + kind: "label" /* label */, + displayParts: [displayPart(node.text, 17 /* text */)] + }; + } + + case 2 /* Keyword */: + { + const { + node + } = def; + const name2 = tokenToString(node.kind); + return { + ...getFileAndTextSpanFromNode(node), + name: name2, + kind: "keyword" /* keyword */, + displayParts: [{ + text: name2, + kind: "keyword" /* keyword */ + }] + }; + } + + case 3 /* This */: + { + const { + node + } = def; + const symbol = checker.getSymbolAtLocation(node); + const displayParts2 = symbol && ts_SymbolDisplay_exports.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, node.getSourceFile(), getContainerNode(node), node).displayParts || [textPart("this")]; + return { + ...getFileAndTextSpanFromNode(node), + name: "this", + kind: "var" /* variableElement */, + displayParts: displayParts2 + }; + } + case 4 /* String */: + { + const { + node + } = def; + return { + ...getFileAndTextSpanFromNode(node), + name: node.text, + kind: "var" /* variableElement */, + displayParts: [displayPart(getTextOfNode(node), 8 /* stringLiteral */)] + }; + } + + case 5 /* TripleSlashReference */: + { + return { + textSpan: createTextSpanFromRange(def.reference), + sourceFile: def.file, + name: def.reference.fileName, + kind: "string" /* string */, + displayParts: [displayPart(`"${def.reference.fileName}"`, 8 /* stringLiteral */)] + }; + } + default: return Debug.assertNever(def); } })(); - const { sourceFile, textSpan, name, kind, displayParts, context } = info; + const { + sourceFile, + textSpan, + name, + kind, + displayParts, + context + } = info; return { containerKind: "" /* unknown */, containerName: "", @@ -161901,16 +146110,24 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} function getDefinitionKindAndDisplayParts(symbol, checker, node) { const meaning = Core.getIntersectingMeaningFromDeclarations(node, symbol); const enclosingDeclaration = symbol.declarations && firstOrUndefined(symbol.declarations) || node; - const { displayParts, symbolKind } = ts_SymbolDisplay_exports.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, enclosingDeclaration.getSourceFile(), enclosingDeclaration, enclosingDeclaration, meaning); - return { displayParts, kind: symbolKind }; + const { + displayParts, + symbolKind + } = ts_SymbolDisplay_exports.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, enclosingDeclaration.getSourceFile(), enclosingDeclaration, enclosingDeclaration, meaning); + return { + displayParts, + kind: symbolKind + }; } function toRenameLocation(entry, originalNode, checker, providePrefixAndSuffixText, quotePreference) { - return { ...entryToDocumentSpan(entry), ...providePrefixAndSuffixText && getPrefixAndSuffixText(entry, originalNode, checker, quotePreference) }; + return { + ...entryToDocumentSpan(entry), + ...(providePrefixAndSuffixText && getPrefixAndSuffixText(entry, originalNode, checker, quotePreference)) + }; } 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) @@ -161919,9 +146136,15 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} function toReferenceEntry(entry) { const documentSpan = entryToDocumentSpan(entry); if (entry.kind === 0 /* Span */) { - return { ...documentSpan, isWriteAccess: false }; + return { + ...documentSpan, + isWriteAccess: false + }; } - const { kind, node } = entry; + const { + kind, + node + } = entry; return { ...documentSpan, isWriteAccess: isWriteAccessForReference(node), @@ -161930,7 +146153,10 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } function entryToDocumentSpan(entry) { if (entry.kind === 0 /* Span */) { - return { textSpan: entry.textSpan, fileName: entry.fileName }; + return { + textSpan: entry.textSpan, + fileName: entry.fileName + }; } else { const sourceFile = entry.node.getSourceFile(); const textSpan = getTextSpan(entry.node, sourceFile); @@ -161943,13 +146169,20 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } function getPrefixAndSuffixText(entry, originalNode, checker, quotePreference) { if (entry.kind !== 0 /* Span */ && isIdentifier(originalNode)) { - const { node, kind } = entry; + const { + node, + kind + } = entry; const parent2 = node.parent; const name = originalNode.text; const isShorthandAssignment = isShorthandPropertyAssignment(parent2); if (isShorthandAssignment || isObjectBindingElementWithoutPropertyName(parent2) && parent2.name === node && parent2.dotDotDotToken === void 0) { - const prefixColon = { prefixText: name + ": " }; - const suffixColon = { suffixText: ": " + name }; + const prefixColon = { + prefixText: name + ": " + }; + const suffixColon = { + suffixText: ": " + name + }; if (kind === 3 /* SearchedLocalFoundProperty */) { return prefixColon; } @@ -161967,27 +146200,42 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } } else if (isImportSpecifier(parent2) && !parent2.propertyName) { const originalSymbol = isExportSpecifier(originalNode.parent) ? checker.getExportSpecifierLocalTargetSymbol(originalNode.parent) : checker.getSymbolAtLocation(originalNode); - return contains(originalSymbol.declarations, parent2) ? { prefixText: name + " as " } : emptyOptions; + return contains(originalSymbol.declarations, parent2) ? { + prefixText: name + " as " + } : emptyOptions; } else if (isExportSpecifier(parent2) && !parent2.propertyName) { - return originalNode === entry.node || checker.getSymbolAtLocation(originalNode) === checker.getSymbolAtLocation(entry.node) ? { prefixText: name + " as " } : { suffixText: " as " + name }; + return originalNode === entry.node || checker.getSymbolAtLocation(originalNode) === checker.getSymbolAtLocation(entry.node) ? { + prefixText: name + " as " + } : { + suffixText: " as " + name + }; } } if (entry.kind !== 0 /* Span */ && isNumericLiteral(entry.node) && isAccessExpression(entry.node.parent)) { const quote2 = getQuoteFromPreference(quotePreference); - return { prefixText: quote2, suffixText: quote2 }; + return { + prefixText: quote2, + suffixText: quote2 + }; } return emptyOptions; } function toImplementationLocation(entry, checker) { const documentSpan = entryToDocumentSpan(entry); if (entry.kind !== 0 /* Span */) { - const { node } = entry; + const { + node + } = entry; return { ...documentSpan, ...implementationKindDisplayParts(node, checker) }; } else { - return { ...documentSpan, kind: "" /* unknown */, displayParts: [] }; + return { + ...documentSpan, + kind: "" /* unknown */, + displayParts: [] + }; } } function implementationKindDisplayParts(node, checker) { @@ -162005,7 +146253,10 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} displayParts: [punctuationPart(21 /* OpenParenToken */), textPart("anonymous local class"), punctuationPart(22 /* CloseParenToken */)] }; } else { - return { kind: getNodeKind(node), displayParts: [] }; + return { + kind: getNodeKind(node), + displayParts: [] + }; } } function toHighlightSpan(entry) { @@ -162019,14 +146270,20 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } }; } + const writeAccess = isWriteAccessForReference(entry.node); const span = { textSpan: documentSpan.textSpan, kind: writeAccess ? "writtenReference" /* writtenReference */ : "reference" /* reference */, isInString: entry.kind === 2 /* StringLiteral */ ? true : void 0, - ...documentSpan.contextSpan && { contextSpan: documentSpan.contextSpan } + ...(documentSpan.contextSpan && { + contextSpan: documentSpan.contextSpan + }) + }; + return { + fileName: documentSpan.fileName, + span }; - return { fileName: documentSpan.fileName, span }; } function getTextSpan(node, sourceFile, endNode2) { let start = node.getStart(sourceFile); @@ -162047,15 +146304,13 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } 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))); + 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 */: @@ -162106,9 +146361,10 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} var init_findAllReferences = __esm({ "src/services/findAllReferences.ts"() { "use strict"; + init_ts4(); init_ts_FindAllReferences(); - DefinitionKind = /* @__PURE__ */ ((DefinitionKind2) => { + DefinitionKind = /* @__PURE__ */(DefinitionKind2 => { DefinitionKind2[DefinitionKind2["Symbol"] = 0] = "Symbol"; DefinitionKind2[DefinitionKind2["Label"] = 1] = "Label"; DefinitionKind2[DefinitionKind2["Keyword"] = 2] = "Keyword"; @@ -162117,7 +146373,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} DefinitionKind2[DefinitionKind2["TripleSlashReference"] = 5] = "TripleSlashReference"; return DefinitionKind2; })(DefinitionKind || {}); - EntryKind = /* @__PURE__ */ ((EntryKind2) => { + EntryKind = /* @__PURE__ */(EntryKind2 => { EntryKind2[EntryKind2["Span"] = 0] = "Span"; EntryKind2[EntryKind2["Node"] = 1] = "Node"; EntryKind2[EntryKind2["StringLiteral"] = 2] = "StringLiteral"; @@ -162125,14 +146381,14 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} EntryKind2[EntryKind2["SearchedPropertyFoundLocal"] = 4] = "SearchedPropertyFoundLocal"; return EntryKind2; })(EntryKind || {}); - FindReferencesUse = /* @__PURE__ */ ((FindReferencesUse2) => { + FindReferencesUse = /* @__PURE__ */(FindReferencesUse2 => { FindReferencesUse2[FindReferencesUse2["Other"] = 0] = "Other"; FindReferencesUse2[FindReferencesUse2["References"] = 1] = "References"; FindReferencesUse2[FindReferencesUse2["Rename"] = 2] = "Rename"; return FindReferencesUse2; })(FindReferencesUse || {}); - ((Core2) => { - function getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options = {}, sourceFilesSet = new Set(sourceFiles.map((f) => f.fileName))) { + (Core2 => { + function getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options = {}, sourceFilesSet = new Set(sourceFiles.map(f => f.fileName))) { var _a, _b; node = getAdjustedNode2(node, options); if (isSourceFile(node)) { @@ -162142,21 +146398,19 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } const moduleSymbol = program.getTypeChecker().getMergedSymbol(resolvedRef.file.symbol); if (moduleSymbol) { - return getReferencedSymbolsForModule( - program, - moduleSymbol, - /*excludeImportTypeOfExportEquals*/ - false, - sourceFiles, - sourceFilesSet - ); + return getReferencedSymbolsForModule(program, moduleSymbol, /*excludeImportTypeOfExportEquals*/ + false, sourceFiles, sourceFilesSet); } const fileIncludeReasons = program.getFileIncludeReasons(); if (!fileIncludeReasons) { return void 0; } return [{ - definition: { type: 5 /* TripleSlashReference */, reference: resolvedRef.reference, file: node }, + definition: { + type: 5 /* TripleSlashReference */, + reference: resolvedRef.reference, + file: node + }, references: getReferencesForNonModule(resolvedRef.file, fileIncludeReasons, program) || emptyArray }]; } @@ -162175,7 +146429,13 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} const referencedFileName = (_b = (_a = program.getResolvedModule(node.getSourceFile(), node.text, getModeForUsageLocation(node.getSourceFile(), node))) == null ? void 0 : _a.resolvedModule) == null ? void 0 : _b.resolvedFileName; const referencedFile = referencedFileName ? program.getSourceFile(referencedFileName) : void 0; if (referencedFile) { - return [{ definition: { type: 4 /* String */, node }, references: getReferencesForNonModule(referencedFile, fileIncludeReasons, program) || emptyArray }]; + return [{ + definition: { + type: 4 /* String */, + node + }, + references: getReferencesForNonModule(referencedFile, fileIncludeReasons, program) || emptyArray + }]; } } return getReferencesForStringLiteral(node, sourceFiles, checker, cancellationToken); @@ -162183,14 +146443,8 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return void 0; } if (symbol.escapedName === "export=" /* ExportEquals */) { - return getReferencedSymbolsForModule( - program, - symbol.parent, - /*excludeImportTypeOfExportEquals*/ - false, - sourceFiles, - sourceFilesSet - ); + return getReferencedSymbolsForModule(program, symbol.parent, /*excludeImportTypeOfExportEquals*/ + false, sourceFiles, sourceFilesSet); } const moduleReferences = getReferencedSymbolsForModuleIfDeclaredBySourceFile(symbol, program, sourceFiles, cancellationToken, options, sourceFilesSet); if (moduleReferences && !(symbol.flags & 33554432 /* Transient */)) { @@ -162211,18 +146465,12 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return node; } Core2.getAdjustedNode = getAdjustedNode2; - function getReferencesForFileName(fileName, program, sourceFiles, sourceFilesSet = new Set(sourceFiles.map((f) => f.fileName))) { + function getReferencesForFileName(fileName, program, sourceFiles, sourceFilesSet = new Set(sourceFiles.map(f => f.fileName))) { var _a, _b; const moduleSymbol = (_a = program.getSourceFile(fileName)) == null ? void 0 : _a.symbol; if (moduleSymbol) { - return ((_b = getReferencedSymbolsForModule( - program, - moduleSymbol, - /*excludeImportTypeOfExportEquals*/ - false, - sourceFiles, - sourceFilesSet - )[0]) == null ? void 0 : _b.references) || emptyArray; + return ((_b = getReferencedSymbolsForModule(program, moduleSymbol, /*excludeImportTypeOfExportEquals*/ + false, sourceFiles, sourceFilesSet)[0]) == null ? void 0 : _b.references) || emptyArray; } const fileIncludeReasons = program.getFileIncludeReasons(); const referencedFile = program.getSourceFile(fileName); @@ -162259,30 +146507,19 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } 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( - symbol, - /*node*/ - void 0, - sourceFiles, - sourceFilesSet, - checker, - cancellationToken, - options - )); + return mergeReferences(program, moduleReferences, getReferencedSymbolsForSymbol(symbol, /*node*/ + void 0, sourceFiles, sourceFilesSet, checker, cancellationToken, options)); } function mergeReferences(program, ...referencesToMerge) { let result; for (const references of referencesToMerge) { - if (!references || !references.length) - continue; + if (!references || !references.length) continue; if (!result) { result = references; continue; @@ -162293,7 +146530,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} continue; } const symbol = entry.definition.symbol; - const refIndex = findIndex(result, (ref) => !!ref.definition && ref.definition.type === 0 /* Symbol */ && ref.definition.symbol === symbol); + const refIndex = findIndex(result, ref => !!ref.definition && ref.definition.type === 0 /* Symbol */ && ref.definition.symbol === symbol); if (refIndex === -1) { result.push(entry); continue; @@ -162322,7 +146559,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } function getReferencedSymbolsForModule(program, symbol, excludeImportTypeOfExportEquals, sourceFiles, sourceFilesSet) { Debug.assert(!!symbol.valueDeclaration); - const references = mapDefined(findModuleReferences(program, sourceFiles, symbol), (reference) => { + const references = mapDefined(findModuleReferences(program, sourceFiles, symbol), reference => { if (reference.kind === "import") { const parent2 = reference.literal.parent; if (isLiteralTypeNode(parent2)) { @@ -162333,10 +146570,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } return nodeEntry(reference.literal); } else if (reference.kind === "implicit") { - const range = reference.literal.text !== externalHelpersModuleNameText && forEachChildRecursively( - reference.referencingFile, - (n) => !(n.transformFlags & 2 /* ContainsJsx */) ? "skip" : isJsxElement(n) || isJsxSelfClosingElement(n) || isJsxFragment(n) ? n : void 0 - ) || reference.referencingFile.statements[0] || reference.referencingFile; + const range = reference.literal.text !== externalHelpersModuleNameText && forEachChildRecursively(reference.referencingFile, n => !(n.transformFlags & 2 /* ContainsJsx */) ? "skip" : isJsxElement(n) || isJsxSelfClosingElement(n) || isJsxFragment(n) ? n : void 0) || reference.referencingFile.statements[0] || reference.referencingFile; return nodeEntry(range); } else { return { @@ -162371,11 +146605,18 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } } } - return references.length ? [{ definition: { type: 0 /* Symbol */, symbol }, references }] : emptyArray; + return references.length ? [{ + definition: { + type: 0 /* Symbol */, + symbol + }, + references + }] : emptyArray; } function isReadonlyTypeOperator(node) { return node.kind === 148 /* ReadonlyKeyword */ && isTypeOperatorNode(node.parent) && node.parent.operator === 148 /* ReadonlyKeyword */; } + function getReferencedSymbolsSpecial(node, sourceFiles, cancellationToken) { if (isTypeKeyword(node.kind)) { if (node.kind === 116 /* VoidKeyword */ && isVoidExpression(node.parent)) { @@ -162384,18 +146625,19 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (node.kind === 148 /* ReadonlyKeyword */ && !isReadonlyTypeOperator(node)) { return void 0; } - return getAllReferencesForKeyword( - sourceFiles, - node.kind, - cancellationToken, - node.kind === 148 /* ReadonlyKeyword */ ? isReadonlyTypeOperator : void 0 - ); + return getAllReferencesForKeyword(sourceFiles, node.kind, cancellationToken, node.kind === 148 /* ReadonlyKeyword */ ? isReadonlyTypeOperator : void 0); } if (isImportMeta(node.parent) && node.parent.name === node) { return getAllReferencesForImportMeta(sourceFiles, cancellationToken); } if (isStaticModifier(node) && isClassStaticBlockDeclaration(node.parent)) { - return [{ definition: { type: 2 /* Keyword */, node }, references: [nodeEntry(node)] }]; + return [{ + definition: { + type: 2 /* Keyword */, + node + }, + references: [nodeEntry(node)] + }]; } if (isJumpStatementTarget(node)) { const labelDefinition = getTargetLabel(node.parent, node.text); @@ -162412,45 +146654,28 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return void 0; } function getReferencedSymbolsForSymbol(originalSymbol, node, sourceFiles, sourceFilesSet, checker, cancellationToken, options) { - const symbol = node && skipPastExportOrImportSpecifierOrUnion( - originalSymbol, - node, - checker, - /*useLocalSymbolForExportSpecifier*/ - !isForRenameWithPrefixAndSuffixText(options) - ) || originalSymbol; + const symbol = node && skipPastExportOrImportSpecifierOrUnion(originalSymbol, node, checker, /*useLocalSymbolForExportSpecifier*/ + !isForRenameWithPrefixAndSuffixText(options)) || originalSymbol; const searchMeaning = node ? getIntersectingMeaningFromDeclarations(node, symbol) : 7 /* All */; const result = []; const state = new State(sourceFiles, sourceFilesSet, node ? getSpecialSearchKind(node) : 0 /* None */, checker, cancellationToken, searchMeaning, options, result); const exportSpecifier = !isForRenameWithPrefixAndSuffixText(options) || !symbol.declarations ? void 0 : find(symbol.declarations, isExportSpecifier); if (exportSpecifier) { - getReferencesAtExportSpecifier( - exportSpecifier.name, - symbol, - exportSpecifier, - state.createSearch( - node, - originalSymbol, - /*comingFrom*/ - void 0 - ), - state, - /*addReferencesHere*/ - true, - /*alwaysGetReferences*/ - true - ); + getReferencesAtExportSpecifier(exportSpecifier.name, symbol, exportSpecifier, state.createSearch(node, originalSymbol, /*comingFrom*/ + void 0), state, /*addReferencesHere*/ + true, /*alwaysGetReferences*/ + true); } else if (node && node.kind === 90 /* DefaultKeyword */ && symbol.escapedName === "default" /* Default */ && symbol.parent) { addReference(node, symbol, state); - searchForImportsOfExport(node, symbol, { exportingModuleSymbol: symbol.parent, exportKind: 1 /* Default */ }, state); + searchForImportsOfExport(node, symbol, { + exportingModuleSymbol: symbol.parent, + exportKind: 1 /* Default */ + }, state); } else { - const search = state.createSearch( - node, - symbol, - /*comingFrom*/ - void 0, - { allSearchSymbols: node ? populateSearchSymbolSet(symbol, node, checker, options.use === 2 /* Rename */, !!options.providePrefixAndSuffixTextForRename, !!options.implementations) : [symbol] } - ); + const search = state.createSearch(node, symbol, /*comingFrom*/ + void 0, { + allSearchSymbols: node ? populateSearchSymbolSet(symbol, node, checker, options.use === 2 /* Rename */, !!options.providePrefixAndSuffixTextForRename, !!options.implementations) : [symbol] + }); getReferencesInContainerOrFiles(symbol, state, search); } return result; @@ -162458,14 +146683,8 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} function getReferencesInContainerOrFiles(symbol, state, search) { const scope = getSymbolScope(symbol); if (scope) { - getReferencesInContainer( - scope, - scope.getSourceFile(), - search, - state, - /*addReferencesHere*/ - !(isSourceFile(scope) && !contains(state.sourceFiles, scope)) - ); + getReferencesInContainer(scope, scope.getSourceFile(), search, state, /*addReferencesHere*/ + !(isSourceFile(scope) && !contains(state.sourceFiles, scope))); } else { for (const sourceFile of state.sourceFiles) { state.cancellationToken.throwIfCancellationRequested(); @@ -162483,34 +146702,36 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} Debug.assert(node.parent.name === node); return 2 /* Class */; } + default: return 0 /* None */; } } + function skipPastExportOrImportSpecifierOrUnion(symbol, node, checker, useLocalSymbolForExportSpecifier) { - const { parent: parent2 } = node; + const { + parent: parent2 + } = node; if (isExportSpecifier(parent2) && useLocalSymbolForExportSpecifier) { return getLocalSymbolForExportSpecifier(node, symbol, parent2, checker); } - return firstDefined(symbol.declarations, (decl) => { + 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; }); } let SpecialSearchKind; - ((SpecialSearchKind2) => { + (SpecialSearchKind2 => { SpecialSearchKind2[SpecialSearchKind2["None"] = 0] = "None"; SpecialSearchKind2[SpecialSearchKind2["Constructor"] = 1] = "Constructor"; SpecialSearchKind2[SpecialSearchKind2["Class"] = 2] = "Class"; })(SpecialSearchKind || (SpecialSearchKind = {})); function getNonModuleSymbolOfMergedModuleSymbol(symbol) { - if (!(symbol.flags & (1536 /* Module */ | 33554432 /* Transient */))) - return void 0; - const decl = symbol.declarations && find(symbol.declarations, (d) => !isSourceFile(d) && !isModuleDeclaration(d)); + 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; } class State { @@ -162524,7 +146745,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} this.options = options; this.result = result; /** Cache for `explicitlyinheritsFrom`. */ - this.inheritsFromCache = /* @__PURE__ */ new Map(); + this.inheritsFromCache = /* @__PURE__ */new Map(); /** * Type nodes can contain multiple references to the same type. For example: * let x: Foo & (Foo & Bar) = ... @@ -162554,8 +146775,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } /** 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`. */ @@ -162566,7 +146786,15 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } = searchOptions; const escapedText = escapeLeadingUnderscores(text); const parents = this.options.implementations && location ? getParentSymbolsOfPropertyAccess(location, symbol, this.checker) : void 0; - return { symbol, comingFrom, text, escapedText, parents, allSearchSymbols, includes: (sym) => contains(allSearchSymbols, sym) }; + return { + symbol, + comingFrom, + text, + escapedText, + parents, + allSearchSymbols, + includes: sym => contains(allSearchSymbols, sym) + }; } /** * Callback to add references for a particular searched symbol. @@ -162577,7 +146805,13 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} let references = this.symbolIdToReferences[symbolId]; if (!references) { references = this.symbolIdToReferences[symbolId] = []; - this.result.push({ definition: { type: 0 /* Symbol */, symbol: searchSymbol }, references }); + this.result.push({ + definition: { + type: 0 /* Symbol */, + symbol: searchSymbol + }, + references + }); } return (node, kind) => references.push(nodeEntry(node, kind)); } @@ -162585,13 +146819,17 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} addStringOrCommentReference(fileName, textSpan) { this.result.push({ definition: void 0, - references: [{ kind: 0 /* Span */, fileName, textSpan }] + references: [{ + kind: 0 /* Span */, + fileName, + textSpan + }] }); } /** Returns `true` the first time we search for a symbol in a file and `false` afterwards. */ markSearchedSymbols(sourceFile, symbols) { const sourceId = getNodeId(sourceFile); - const seenSymbols = this.sourceFileToSeenSymbols[sourceId] || (this.sourceFileToSeenSymbols[sourceId] = /* @__PURE__ */ new Set()); + const seenSymbols = this.sourceFileToSeenSymbols[sourceId] || (this.sourceFileToSeenSymbols[sourceId] = /* @__PURE__ */new Set()); let anyNewSymbols = false; for (const sym of symbols) { anyNewSymbols = tryAddToSet(seenSymbols, getSymbolId(sym)) || anyNewSymbols; @@ -162600,12 +146838,15 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } } function searchForImportsOfExport(exportLocation, exportSymbol, exportInfo, state) { - const { importSearches, singleReferences, indirectUsers } = state.getImportSearches(exportSymbol, exportInfo); + const { + importSearches, + singleReferences, + indirectUsers + } = state.getImportSearches(exportSymbol, exportInfo); 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) { @@ -162618,7 +146859,9 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} indirectSearch = state.createSearch(exportLocation, exportSymbol, 1 /* Export */); break; case 1 /* Default */: - indirectSearch = state.options.use === 2 /* Rename */ ? void 0 : state.createSearch(exportLocation, exportSymbol, 1 /* Export */, { text: "default" }); + indirectSearch = state.options.use === 2 /* Rename */ ? void 0 : state.createSearch(exportLocation, exportSymbol, 1 /* Export */, { + text: "default" + }); break; case 2 /* ExportEquals */: break; @@ -162631,13 +146874,16 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } } function eachExportReference(sourceFiles, checker, cancellationToken, exportSymbol, exportingModuleSymbol, exportName, isDefaultExport, cb) { - const importTracker = createImportTracker(sourceFiles, new Set(sourceFiles.map((f) => f.fileName)), checker, cancellationToken); - const { importSearches, indirectUsers, singleReferences } = importTracker( - exportSymbol, - { exportKind: isDefaultExport ? 1 /* Default */ : 0 /* Named */, exportingModuleSymbol }, - /*isForRename*/ - false - ); + const importTracker = createImportTracker(sourceFiles, new Set(sourceFiles.map(f => f.fileName)), checker, cancellationToken); + const { + importSearches, + indirectUsers, + singleReferences + } = importTracker(exportSymbol, { + exportKind: isDefaultExport ? 1 /* Default */ : 0 /* Named */, + exportingModuleSymbol + }, /*isForRename*/ + false); for (const [importLocation] of importSearches) { cb(importLocation); } @@ -162649,7 +146895,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} for (const indirectUser of indirectUsers) { for (const node of getPossibleSymbolReferenceNodes(indirectUser, isDefaultExport ? "default" : exportName)) { const symbol = checker.getSymbolAtLocation(node); - const hasExportAssignmentDeclaration = some(symbol == null ? void 0 : symbol.declarations, (d) => tryCast(d, isExportAssignment) ? true : false); + const hasExportAssignmentDeclaration = some(symbol == null ? void 0 : symbol.declarations, d => tryCast(d, isExportAssignment) ? true : false); if (isIdentifier(node) && !isImportOrExportSpecifier(node.parent) && (symbol === exportSymbol || hasExportAssignmentDeclaration)) { cb(node); } @@ -162658,17 +146904,14 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } 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)); @@ -162683,7 +146926,12 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return isArrayLiteralOrObjectLiteralDestructuringPattern(location.parent.parent) ? checker.getPropertySymbolOfDestructuringAssignment(location) : void 0; } function getSymbolScope(symbol) { - const { declarations, flags, parent: parent2, valueDeclaration } = symbol; + const { + declarations, + flags, + parent: parent2, + valueDeclaration + } = symbol; if (valueDeclaration && (valueDeclaration.kind === 218 /* FunctionExpression */ || valueDeclaration.kind === 231 /* ClassExpression */)) { return valueDeclaration; } @@ -162691,10 +146939,11 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return void 0; } if (flags & (4 /* Property */ | 8192 /* Method */)) { - const privateDeclaration = find(declarations, (d) => hasEffectiveModifier(d, 2 /* Private */) || isPrivateIdentifierClassElementDeclaration(d)); + const privateDeclaration = find(declarations, d => hasEffectiveModifier(d, 2 /* Private */) || isPrivateIdentifierClassElementDeclaration(d)); if (privateDeclaration) { return getAncestor(privateDeclaration, 263 /* ClassDeclaration */); } + return void 0; } if (declarations.some(isObjectBindingElementWithoutPropertyName)) { @@ -162729,22 +146978,19 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} 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; } } } Core2.eachSymbolReferenceInFile = eachSymbolReferenceInFile; function getTopMostDeclarationNamesInFile(declarationName, sourceFile) { - const candidates = filter(getPossibleSymbolReferenceNodes(sourceFile, declarationName), (name) => !!getDeclarationFromName(name)); + const candidates = filter(getPossibleSymbolReferenceNodes(sourceFile, declarationName), name => !!getDeclarationFromName(name)); return candidates.reduce((topMost, decl) => { const depth = getDepth(decl); if (!some(topMost.declarationNames) || depth === topMost.depth) { @@ -162755,7 +147001,10 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} topMost.depth = depth; } return topMost; - }, { depth: Infinity, declarationNames: [] }).declarationNames; + }, { + depth: Infinity, + declarationNames: [] + }).declarationNames; function getDepth(declaration) { let depth = 0; while (declaration) { @@ -162767,17 +147016,15 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } 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); - if (referenceSymbol && checker.getRootSymbols(referenceSymbol).some((s) => s === symbol)) { + if (referenceSymbol && checker.getRootSymbols(referenceSymbol).some(s => s === symbol)) { if (cb(name, call)) { return true; } @@ -162788,7 +147035,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } Core2.someSignatureUsage = someSignatureUsage; function getPossibleSymbolReferenceNodes(sourceFile, symbolName2, container = sourceFile) { - return mapDefined(getPossibleSymbolReferencePositions(sourceFile, symbolName2, container), (pos) => { + return mapDefined(getPossibleSymbolReferencePositions(sourceFile, symbolName2, container), pos => { const referenceLocation = getTouchingPropertyName(sourceFile, pos); return referenceLocation === sourceFile ? void 0 : referenceLocation; }); @@ -162803,8 +147050,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} 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); @@ -162816,11 +147062,16 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} function getLabelReferencesInNode(container, targetLabel) { const sourceFile = container.getSourceFile(); const labelName = targetLabel.text; - const references = mapDefined(getPossibleSymbolReferenceNodes(sourceFile, labelName, container), (node) => ( - // Only pick labels that are either the target label, or have a target that is the target label - node === targetLabel || isJumpStatementTarget(node) && getTargetLabel(node, labelName) === targetLabel ? nodeEntry(node) : void 0 - )); - return [{ definition: { type: 1 /* Label */, node: targetLabel }, references }]; + const references = mapDefined(getPossibleSymbolReferenceNodes(sourceFile, labelName, container), node => + // Only pick labels that are either the target label, or have a target that is the target label + node === targetLabel || isJumpStatementTarget(node) && getTargetLabel(node, labelName) === targetLabel ? nodeEntry(node) : void 0); + return [{ + definition: { + type: 1 /* Label */, + node: targetLabel + }, + references + }]; } function isValidReferencePosition(node, searchSymbolName) { switch (node.kind) { @@ -162831,10 +147082,11 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} case 80 /* Identifier */: return node.text.length === searchSymbolName.length; case 15 /* NoSubstitutionTemplateLiteral */: - case 11 /* StringLiteral */: { - const str = node; - return (isLiteralNameOfPropertyDeclarationOrIndexAccess(str) || isNameOfModuleDeclaration(node) || isExpressionOfExternalModuleImportEqualsDeclaration(node) || isCallExpression(node.parent) && isBindableObjectDefinePropertyCall(node.parent) && node.parent.arguments[1] === node) && str.text.length === searchSymbolName.length; - } + case 11 /* StringLiteral */: + { + const str = node; + return (isLiteralNameOfPropertyDeclarationOrIndexAccess(str) || isNameOfModuleDeclaration(node) || isExpressionOfExternalModuleImportEqualsDeclaration(node) || isCallExpression(node.parent) && isBindableObjectDefinePropertyCall(node.parent) && node.parent.arguments[1] === node) && str.text.length === searchSymbolName.length; + } case 9 /* NumericLiteral */: return isLiteralNameOfPropertyDeclarationOrIndexAccess(node) && node.text.length === searchSymbolName.length; case 90 /* DefaultKeyword */: @@ -162844,27 +147096,39 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } } function getAllReferencesForImportMeta(sourceFiles, cancellationToken) { - const references = flatMap(sourceFiles, (sourceFile) => { + const references = flatMap(sourceFiles, sourceFile => { cancellationToken.throwIfCancellationRequested(); - return mapDefined(getPossibleSymbolReferenceNodes(sourceFile, "meta", sourceFile), (node) => { + return mapDefined(getPossibleSymbolReferenceNodes(sourceFile, "meta", sourceFile), node => { const parent2 = node.parent; if (isImportMeta(parent2)) { return nodeEntry(parent2); } }); }); - return references.length ? [{ definition: { type: 2 /* Keyword */, node: references[0].node }, references }] : void 0; + return references.length ? [{ + definition: { + type: 2 /* Keyword */, + node: references[0].node + }, + references + }] : void 0; } function getAllReferencesForKeyword(sourceFiles, keywordKind, cancellationToken, filter2) { - const references = flatMap(sourceFiles, (sourceFile) => { + const references = flatMap(sourceFiles, sourceFile => { cancellationToken.throwIfCancellationRequested(); - return mapDefined(getPossibleSymbolReferenceNodes(sourceFile, tokenToString(keywordKind), sourceFile), (referenceLocation) => { + return mapDefined(getPossibleSymbolReferenceNodes(sourceFile, tokenToString(keywordKind), sourceFile), referenceLocation => { if (referenceLocation.kind === keywordKind && (!filter2 || filter2(referenceLocation))) { return nodeEntry(referenceLocation); } }); }); - return references.length ? [{ definition: { type: 2 /* Keyword */, node: references[0].node }, references }] : void 0; + return references.length ? [{ + definition: { + type: 2 /* Keyword */, + node: references[0].node + }, + references + }] : void 0; } function getReferencesInSourceFile(sourceFile, search, state, addReferencesHere = true) { state.cancellationToken.throwIfCancellationRequested(); @@ -162889,8 +147153,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } return; } - if (!hasMatchingMeaning(referenceLocation, state)) - return; + if (!hasMatchingMeaning(referenceLocation, state)) return; let referenceSymbol = state.checker.getSymbolAtLocation(referenceLocation); if (!referenceSymbol) { return; @@ -162911,8 +147174,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } 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); @@ -162925,14 +147187,17 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } 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); } function getReferencesAtExportSpecifier(referenceLocation, referenceSymbol, exportSpecifier, search, state, addReferencesHere, alwaysGetReferences) { Debug.assert(!alwaysGetReferences || !!state.options.providePrefixAndSuffixTextForRename, "If alwaysGetReferences is true, then prefix/suffix text must be enabled"); - const { parent: parent2, propertyName, name } = exportSpecifier; + const { + parent: parent2, + propertyName, + name + } = exportSpecifier; const exportDeclaration = parent2.parent; const localSymbol = getLocalSymbolForExportSpecifier(referenceLocation, referenceSymbol, exportSpecifier, state.checker); if (!alwaysGetReferences && !search.includes(localSymbol)) { @@ -162965,19 +147230,21 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } 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) { return isExportSpecifierAlias(referenceLocation, exportSpecifier) && checker.getExportSpecifierLocalTargetSymbol(exportSpecifier) || referenceSymbol; } function isExportSpecifierAlias(referenceLocation, exportSpecifier) { - const { parent: parent2, propertyName, name } = exportSpecifier; + const { + parent: parent2, + propertyName, + name + } = exportSpecifier; Debug.assert(propertyName === referenceLocation || name === referenceLocation); if (propertyName) { return propertyName === referenceLocation; @@ -162987,9 +147254,10 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } function getImportOrExportReferences(referenceLocation, referenceSymbol, search, state) { const importOrExport = getImportOrExportSymbol(referenceLocation, referenceSymbol, state.checker, search.comingFrom === 1 /* Export */); - if (!importOrExport) - return; - const { symbol } = importOrExport; + if (!importOrExport) return; + const { + symbol + } = importOrExport; if (importOrExport.kind === 0 /* Import */) { if (!isForRenameWithPrefixAndSuffixText(state.options)) { searchForImportedSymbol(symbol, state); @@ -162998,7 +147266,10 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} searchForImportsOfExport(referenceLocation, symbol, importOrExport.exportInfo, state); } } - function getReferenceForShorthandProperty({ flags, valueDeclaration }, search, state) { + function getReferenceForShorthandProperty({ + flags, + valueDeclaration + }, search, state) { const shorthandValueSymbol = state.checker.getShorthandAssignmentValueSymbol(valueDeclaration); const name = valueDeclaration && getNameOfDeclaration(valueDeclaration); if (!(flags & 33554432 /* Transient */) && name && search.includes(shorthandValueSymbol)) { @@ -163006,7 +147277,13 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } } function addReference(referenceLocation, relatedSymbol, state) { - const { kind, symbol } = "kind" in relatedSymbol ? relatedSymbol : { kind: void 0, symbol: relatedSymbol }; + const { + kind, + symbol + } = "kind" in relatedSymbol ? relatedSymbol : { + kind: void 0, + symbol: relatedSymbol + }; if (state.options.use === 2 /* Rename */ && referenceLocation.kind === 90 /* DefaultKeyword */) { return; } @@ -163036,8 +147313,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} 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) { @@ -163065,12 +147341,12 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } } if (classSymbol.exports) { - classSymbol.exports.forEach((member) => { + classSymbol.exports.forEach(member => { const decl = member.valueDeclaration; if (decl && decl.kind === 174 /* MethodDeclaration */) { const body = decl.body; if (body) { - forEachDescendantOfKind(body, 110 /* ThisKeyword */, (thisKeyword) => { + forEachDescendantOfKind(body, 110 /* ThisKeyword */, thisKeyword => { if (isNewExpressionTarget(thisKeyword)) { addNode(thisKeyword); } @@ -163083,6 +147359,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} function getClassConstructorSymbol(classSymbol) { return classSymbol.members && classSymbol.members.get("__constructor" /* Constructor */); } + function findSuperConstructorAccesses(classDeclaration, addNode) { const constructor = getClassConstructorSymbol(classDeclaration.symbol); if (!(constructor && constructor.declarations)) { @@ -163092,7 +147369,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} Debug.assert(decl.kind === 176 /* Constructor */); const body = decl.body; if (body) { - forEachDescendantOfKind(body, 108 /* SuperKeyword */, (node) => { + forEachDescendantOfKind(body, 108 /* SuperKeyword */, node => { if (isCallExpressionTarget(node)) { addNode(node); } @@ -163104,16 +147381,11 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} 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*/ - void 0, - classSymbol, - /*comingFrom*/ - void 0 - ); + const search = state.createSearch( /*location*/ + void 0, classSymbol, /*comingFrom*/ + void 0); getReferencesInContainerOrFiles(classSymbol, state, search); } function addImplementationReferences(refNode, addReference2, state) { @@ -163132,7 +147404,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} addReference2(containingNode); return; } - const typeNode = findAncestor(refNode, (a) => !isQualifiedName(a.parent) && !isTypeNode(a.parent) && !isTypeElement(a.parent)); + const typeNode = findAncestor(refNode, a => !isQualifiedName(a.parent) && !isTypeNode(a.parent) && !isTypeElement(a.parent)); const typeHavingNode = typeNode.parent; if (hasType(typeHavingNode) && typeHavingNode.type === typeNode && state.markSeenContainingTypeReference(typeHavingNode)) { if (hasInitializer(typeHavingNode)) { @@ -163140,9 +147412,8 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } else if (isFunctionLike(typeHavingNode) && typeHavingNode.body) { const body = typeHavingNode.body; if (body.kind === 241 /* Block */) { - forEachReturnStatement(body, (returnStatement) => { - if (returnStatement.expression) - addIfImplementation(returnStatement.expression); + forEachReturnStatement(body, returnStatement => { + if (returnStatement.expression) addIfImplementation(returnStatement.expression); }); } else { addIfImplementation(body); @@ -163152,8 +147423,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } } function addIfImplementation(e) { - if (isImplementationExpression(e)) - addReference2(e); + if (isImplementationExpression(e)) addReference2(e); } } function getContainingNodeIfInHeritageClause(node) { @@ -163183,21 +147453,16 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return cached; } cachedResults.set(key, false); - const inherits = !!symbol.declarations && symbol.declarations.some( - (declaration) => getAllSuperTypeNodes(declaration).some((typeReference) => { - const type = checker.getTypeAtLocation(typeReference); - return !!type && !!type.symbol && explicitlyInheritsFrom(type.symbol, parent2, cachedResults, checker); - }) - ); + const inherits = !!symbol.declarations && symbol.declarations.some(declaration => getAllSuperTypeNodes(declaration).some(typeReference => { + const type = checker.getTypeAtLocation(typeReference); + return !!type && !!type.symbol && explicitlyInheritsFrom(type.symbol, parent2, cachedResults, checker); + })); cachedResults.set(key, inherits); return inherits; } function getReferencesForSuperKeyword(superKeyword) { - let searchSpaceNode = getSuperContainer( - superKeyword, - /*stopOnFunctions*/ - false - ); + let searchSpaceNode = getSuperContainer(superKeyword, /*stopOnFunctions*/ + false); if (!searchSpaceNode) { return void 0; } @@ -163217,30 +147482,29 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return void 0; } const sourceFile = searchSpaceNode.getSourceFile(); - const references = mapDefined(getPossibleSymbolReferenceNodes(sourceFile, "super", searchSpaceNode), (node) => { + const references = mapDefined(getPossibleSymbolReferenceNodes(sourceFile, "super", searchSpaceNode), node => { if (node.kind !== 108 /* SuperKeyword */) { return; } - const container = getSuperContainer( - node, - /*stopOnFunctions*/ - false - ); + const container = getSuperContainer(node, /*stopOnFunctions*/ + false); return container && isStatic(container) === !!staticFlag && container.parent.symbol === searchSpaceNode.symbol ? nodeEntry(node) : void 0; }); - return [{ definition: { type: 0 /* Symbol */, symbol: searchSpaceNode.symbol }, references }]; + return [{ + definition: { + type: 0 /* Symbol */, + symbol: searchSpaceNode.symbol + }, + references + }]; } function isParameterName(node) { return node.kind === 80 /* Identifier */ && node.parent.kind === 169 /* Parameter */ && node.parent.name === node; } function getReferencesForThisKeyword(thisOrSuperKeyword, sourceFiles, cancellationToken) { - let searchSpaceNode = getThisContainer( - thisOrSuperKeyword, - /*includeArrowFunctions*/ - false, - /*includeClassComputedPropertyName*/ - false - ); + let searchSpaceNode = getThisContainer(thisOrSuperKeyword, /*includeArrowFunctions*/ + false, /*includeClassComputedPropertyName*/ + false); let staticFlag = 256 /* Static */; switch (searchSpaceNode.kind) { case 174 /* MethodDeclaration */: @@ -163268,21 +147532,16 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} default: return void 0; } - const references = flatMap(searchSpaceNode.kind === 312 /* SourceFile */ ? sourceFiles : [searchSpaceNode.getSourceFile()], (sourceFile) => { + const references = flatMap(searchSpaceNode.kind === 312 /* SourceFile */ ? sourceFiles : [searchSpaceNode.getSourceFile()], sourceFile => { cancellationToken.throwIfCancellationRequested(); - return getPossibleSymbolReferenceNodes(sourceFile, "this", isSourceFile(searchSpaceNode) ? sourceFile : searchSpaceNode).filter((node) => { + return getPossibleSymbolReferenceNodes(sourceFile, "this", isSourceFile(searchSpaceNode) ? sourceFile : searchSpaceNode).filter(node => { if (!isThis(node)) { return false; } - const container = getThisContainer( - node, - /*includeArrowFunctions*/ - false, - /*includeClassComputedPropertyName*/ - false - ); - if (!canHaveSymbol(container)) - return false; + const container = getThisContainer(node, /*includeArrowFunctions*/ + false, /*includeClassComputedPropertyName*/ + false); + if (!canHaveSymbol(container)) return false; switch (searchSpaceNode.kind) { case 218 /* FunctionExpression */: case 262 /* FunctionDeclaration */: @@ -163298,18 +147557,21 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return container.kind === 312 /* SourceFile */ && !isExternalModule(container) && !isParameterName(node); } }); - }).map((n) => nodeEntry(n)); - const thisParameter = firstDefined(references, (r) => isParameter(r.node.parent) ? r.node : void 0); + }).map(n => nodeEntry(n)); + const thisParameter = firstDefined(references, r => isParameter(r.node.parent) ? r.node : void 0); return [{ - definition: { type: 3 /* This */, node: thisParameter || thisOrSuperKeyword }, + definition: { + type: 3 /* This */, + node: thisParameter || thisOrSuperKeyword + }, references }]; } function getReferencesForStringLiteral(node, sourceFiles, checker, cancellationToken) { const type = getContextualTypeFromParentOrAncestorTypeNode(node, checker); - const references = flatMap(sourceFiles, (sourceFile) => { + const references = flatMap(sourceFiles, sourceFile => { cancellationToken.throwIfCancellationRequested(); - return mapDefined(getPossibleSymbolReferenceNodes(sourceFile, node.text), (ref) => { + return mapDefined(getPossibleSymbolReferenceNodes(sourceFile, node.text), ref => { if (isStringLiteralLike(ref) && ref.text === node.text) { if (type) { const refType = getContextualTypeFromParentOrAncestorTypeNode(ref, checker); @@ -163322,31 +147584,28 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } }); }); + return [{ - definition: { type: 4 /* String */, node }, + definition: { + type: 4 /* String */, + node + }, references }]; } function populateSearchSymbolSet(symbol, location, checker, isForRename, providePrefixAndSuffixText, implementations) { const result = []; - forEachRelatedSymbol( - symbol, - location, - checker, - isForRename, - !(isForRename && providePrefixAndSuffixText), - (sym, root, base) => { - if (base) { - if (isStaticSymbol(symbol) !== isStaticSymbol(base)) { - base = void 0; - } + forEachRelatedSymbol(symbol, location, checker, isForRename, !(isForRename && providePrefixAndSuffixText), (sym, root, base) => { + if (base) { + if (isStaticSymbol(symbol) !== isStaticSymbol(base)) { + base = void 0; } - result.push(base || root || sym); - }, - // when try to find implementation, implementations is true, and not allowed to find base class - /*allowBaseTypes*/ - () => !implementations - ); + } + result.push(base || root || sym); + }, + // when try to find implementation, implementations is true, and not allowed to find base class + /*allowBaseTypes*/ + () => !implementations); return result; } function forEachRelatedSymbol(symbol, location, checker, isForRenamePopulateSearchSymbolSet, onlyIncludeBindingElementAtReferenceLocation, cbSymbol, allowBaseTypes) { @@ -163354,66 +147613,38 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (containingObjectLiteralElement) { const shorthandValueSymbol = checker.getShorthandAssignmentValueSymbol(location.parent); if (shorthandValueSymbol && isForRenamePopulateSearchSymbolSet) { - return cbSymbol( - shorthandValueSymbol, - /*rootSymbol*/ - void 0, - /*baseSymbol*/ - void 0, - 3 /* SearchedLocalFoundProperty */ - ); + return cbSymbol(shorthandValueSymbol, /*rootSymbol*/ + void 0, /*baseSymbol*/ + void 0, 3 /* SearchedLocalFoundProperty */); } + const contextualType = checker.getContextualType(containingObjectLiteralElement.parent); - const res2 = contextualType && firstDefined( - getPropertySymbolsFromContextualType( - containingObjectLiteralElement, - checker, - contextualType, - /*unionSymbolOk*/ - true - ), - (sym) => fromRoot(sym, 4 /* SearchedPropertyFoundLocal */) - ); - if (res2) - return res2; + const res2 = contextualType && firstDefined(getPropertySymbolsFromContextualType(containingObjectLiteralElement, checker, contextualType, /*unionSymbolOk*/ + true), sym => fromRoot(sym, 4 /* SearchedPropertyFoundLocal */)); + + if (res2) return res2; const propertySymbol = getPropertySymbolOfDestructuringAssignment(location, checker); - const res1 = propertySymbol && cbSymbol( - propertySymbol, - /*rootSymbol*/ - void 0, - /*baseSymbol*/ - void 0, - 4 /* SearchedPropertyFoundLocal */ - ); - if (res1) - return res1; - const res22 = shorthandValueSymbol && cbSymbol( - shorthandValueSymbol, - /*rootSymbol*/ - void 0, - /*baseSymbol*/ - void 0, - 3 /* SearchedLocalFoundProperty */ - ); - if (res22) - return res22; + const res1 = propertySymbol && cbSymbol(propertySymbol, /*rootSymbol*/ + void 0, /*baseSymbol*/ + void 0, 4 /* SearchedPropertyFoundLocal */); + + if (res1) return res1; + const res22 = shorthandValueSymbol && cbSymbol(shorthandValueSymbol, /*rootSymbol*/ + void 0, /*baseSymbol*/ + void 0, 3 /* SearchedLocalFoundProperty */); + + if (res22) return res22; } const aliasedSymbol = getMergedAliasedSymbolOfNamespaceExportDeclaration(location, symbol, checker); if (aliasedSymbol) { - const res2 = cbSymbol( - aliasedSymbol, - /*rootSymbol*/ - void 0, - /*baseSymbol*/ - void 0, - 1 /* Node */ - ); - if (res2) - return res2; + const res2 = cbSymbol(aliasedSymbol, /*rootSymbol*/ + void 0, /*baseSymbol*/ + void 0, 1 /* Node */); + + 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 */)); @@ -163423,16 +147654,11 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (!isForRenamePopulateSearchSymbolSet || exportSpecifier && !exportSpecifier.propertyName) { const localSymbol = exportSpecifier && checker.getExportSpecifierLocalTargetSymbol(exportSpecifier); if (localSymbol) { - const res2 = cbSymbol( - localSymbol, - /*rootSymbol*/ - void 0, - /*baseSymbol*/ - void 0, - 1 /* Node */ - ); - if (res2) - return res2; + const res2 = cbSymbol(localSymbol, /*rootSymbol*/ + void 0, /*baseSymbol*/ + void 0, 1 /* Node */); + + if (res2) return res2; } } if (!isForRenamePopulateSearchSymbolSet) { @@ -163444,20 +147670,17 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } return bindingElementPropertySymbol && fromRoot(bindingElementPropertySymbol, 4 /* SearchedPropertyFoundLocal */); } + Debug.assert(isForRenamePopulateSearchSymbolSet); const includeOriginalSymbolOfBindingElement = onlyIncludeBindingElementAtReferenceLocation; if (includeOriginalSymbolOfBindingElement) { const bindingElementPropertySymbol = getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol, checker); return bindingElementPropertySymbol && fromRoot(bindingElementPropertySymbol, 4 /* SearchedPropertyFoundLocal */); } + function fromRoot(sym, kind) { - return firstDefined(checker.getRootSymbols(sym), (rootSymbol) => cbSymbol( - sym, - rootSymbol, - /*baseSymbol*/ - void 0, - kind - ) || (rootSymbol.parent && rootSymbol.parent.flags & (32 /* Class */ | 64 /* Interface */) && allowBaseTypes(rootSymbol) ? getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.name, checker, (base) => cbSymbol(sym, rootSymbol, base, kind)) : void 0)); + return firstDefined(checker.getRootSymbols(sym), rootSymbol => cbSymbol(sym, rootSymbol, /*baseSymbol*/ + void 0, kind) || (rootSymbol.parent && rootSymbol.parent.flags & (32 /* Class */ | 64 /* Interface */) && allowBaseTypes(rootSymbol) ? getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.name, checker, base => cbSymbol(sym, rootSymbol, base, kind)) : void 0)); } function getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol2, checker2) { const bindingElement = getDeclarationOfKind(symbol2, 208 /* BindingElement */); @@ -163467,12 +147690,11 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } } function getPropertySymbolsFromBaseTypes(symbol, propertyName, checker, cb) { - const seen = /* @__PURE__ */ new Map(); + const seen = /* @__PURE__ */new Map(); return recur(symbol); function recur(symbol2) { - if (!(symbol2.flags & (32 /* Class */ | 64 /* Interface */)) || !addToSeen(seen, getSymbolId(symbol2))) - return; - return firstDefined(symbol2.declarations, (declaration) => firstDefined(getAllSuperTypeNodes(declaration), (typeReference) => { + 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); return type && propertySymbol && (firstDefined(checker.getRootSymbols(propertySymbol), cb) || recur(type.symbol)); @@ -163480,36 +147702,35 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } } function isStaticSymbol(symbol) { - if (!symbol.valueDeclaration) - return false; + if (!symbol.valueDeclaration) return false; const modifierFlags = getEffectiveModifierFlags(symbol.valueDeclaration); return !!(modifierFlags & 256 /* Static */); } + function getRelatedSymbol(search, referenceSymbol, referenceLocation, state) { - const { checker } = state; - return forEachRelatedSymbol( - referenceSymbol, - referenceLocation, - checker, - /*isForRenamePopulateSearchSymbolSet*/ - false, - /*onlyIncludeBindingElementAtReferenceLocation*/ - state.options.use !== 2 /* Rename */ || !!state.options.providePrefixAndSuffixTextForRename, - (sym, rootSymbol, baseSymbol, kind) => { - if (baseSymbol) { - if (isStaticSymbol(referenceSymbol) !== isStaticSymbol(baseSymbol)) { - baseSymbol = void 0; - } + const { + checker + } = state; + return forEachRelatedSymbol(referenceSymbol, referenceLocation, checker, /*isForRenamePopulateSearchSymbolSet*/ + false, /*onlyIncludeBindingElementAtReferenceLocation*/ + state.options.use !== 2 /* Rename */ || !!state.options.providePrefixAndSuffixTextForRename, (sym, rootSymbol, baseSymbol, kind) => { + if (baseSymbol) { + if (isStaticSymbol(referenceSymbol) !== isStaticSymbol(baseSymbol)) { + baseSymbol = void 0; } - return search.includes(baseSymbol || rootSymbol || sym) ? { symbol: rootSymbol && !(getCheckFlags(sym) & 6 /* Synthetic */) ? rootSymbol : sym, kind } : void 0; - }, - /*allowBaseTypes*/ - (rootSymbol) => !(search.parents && !search.parents.some((parent2) => explicitlyInheritsFrom(rootSymbol.parent, parent2, state.inheritsFromCache, checker))) - ); + } + return search.includes(baseSymbol || rootSymbol || sym) ? { + symbol: rootSymbol && !(getCheckFlags(sym) & 6 /* Synthetic */) ? rootSymbol : sym, + kind + } : void 0; + }, /*allowBaseTypes*/ + rootSymbol => !(search.parents && !search.parents.some(parent2 => explicitlyInheritsFrom(rootSymbol.parent, parent2, state.inheritsFromCache, checker)))); } function getIntersectingMeaningFromDeclarations(node, symbol) { let meaning = getMeaningFromLocation(node); - const { declarations } = symbol; + const { + declarations + } = symbol; if (declarations) { let lastIterationMeaning; do { @@ -163541,7 +147762,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } Core2.getReferenceEntriesForShorthandPropertyAssignment = getReferenceEntriesForShorthandPropertyAssignment; function forEachDescendantOfKind(node, kind, action) { - forEachChild(node, (child) => { + forEachChild(node, child => { if (child.kind === kind) { action(child); } @@ -163554,7 +147775,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} function getParentSymbolsOfPropertyAccess(location, symbol, checker) { const propertyAccessExpression = isRightSideOfPropertyAccess(location) ? location.parent : void 0; const lhsType = propertyAccessExpression && checker.getTypeAtLocation(propertyAccessExpression.expression); - const res = mapDefined(lhsType && (lhsType.isUnionOrIntersection() ? lhsType.types : lhsType.symbol === symbol.parent ? void 0 : [lhsType]), (t) => t.symbol && t.symbol.flags & (32 /* Class */ | 64 /* Interface */) ? t.symbol : void 0); + const res = mapDefined(lhsType && (lhsType.isUnionOrIntersection() ? lhsType.types : lhsType.symbol === symbol.parent ? void 0 : [lhsType]), t => t.symbol && t.symbol.flags & (32 /* Class */ | 64 /* Interface */) ? t.symbol : void 0); return res.length === 0 ? void 0 : res; } function isForRenameWithPrefixAndSuffixText(options) { @@ -163595,6 +147816,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} var init_ts_FindAllReferences = __esm({ "src/services/_namespaces/ts.FindAllReferences.ts"() { "use strict"; + init_importTracker(); init_findAllReferences(); } @@ -163612,65 +147834,66 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (node === sourceFile) { return void 0; } - const { parent: parent2 } = node; + const { + parent: parent2 + } = node; const typeChecker = program.getTypeChecker(); if (node.kind === 164 /* OverrideKeyword */ || isIdentifier(node) && isJSDocOverrideTag(parent2) && parent2.tagName === node) { return getDefinitionFromOverriddenMember(typeChecker, node) || emptyArray; } if (isJumpStatementTarget(node)) { const label = getTargetLabel(node.parent, node.text); - return label ? [createDefinitionInfoFromName( - typeChecker, - label, - "label" /* label */, - node.text, - /*containerName*/ - void 0 - )] : void 0; + return label ? [createDefinitionInfoFromName(typeChecker, label, "label" /* label */, node.text, /*containerName*/ + void 0)] : void 0; } if (node.kind === 107 /* ReturnKeyword */) { - const functionDeclaration = findAncestor(node.parent, (n) => isClassStaticBlockDeclaration(n) ? "quit" : isFunctionLikeDeclaration(n)); + const functionDeclaration = findAncestor(node.parent, n => isClassStaticBlockDeclaration(n) ? "quit" : isFunctionLikeDeclaration(n)); return functionDeclaration ? [createDefinitionFromSignatureDeclaration(typeChecker, functionDeclaration)] : void 0; } if (node.kind === 135 /* AwaitKeyword */) { - const functionDeclaration = findAncestor(node, (n) => isFunctionLikeDeclaration(n)); - const isAsyncFunction2 = functionDeclaration && some(functionDeclaration.modifiers, (node2) => node2.kind === 134 /* AsyncKeyword */); + const functionDeclaration = findAncestor(node, n => isFunctionLikeDeclaration(n)); + const isAsyncFunction2 = functionDeclaration && some(functionDeclaration.modifiers, node2 => node2.kind === 134 /* AsyncKeyword */); return isAsyncFunction2 ? [createDefinitionFromSignatureDeclaration(typeChecker, functionDeclaration)] : void 0; } if (node.kind === 127 /* YieldKeyword */) { - const functionDeclaration = findAncestor(node, (n) => isFunctionLikeDeclaration(n)); + const functionDeclaration = findAncestor(node, n => isFunctionLikeDeclaration(n)); const isGeneratorFunction = functionDeclaration && functionDeclaration.asteriskToken; return isGeneratorFunction ? [createDefinitionFromSignatureDeclaration(typeChecker, functionDeclaration)] : void 0; } if (isStaticModifier(node) && isClassStaticBlockDeclaration(node.parent)) { const classDecl = node.parent.parent; - const { symbol: symbol2, failedAliasResolution: failedAliasResolution2 } = getSymbol(classDecl, typeChecker, stopAtAlias); + const { + symbol: symbol2, + failedAliasResolution: failedAliasResolution2 + } = getSymbol(classDecl, typeChecker, stopAtAlias); const staticBlocks = filter(classDecl.members, isClassStaticBlockDeclaration); const containerName = symbol2 ? typeChecker.symbolToString(symbol2, classDecl) : ""; const sourceFile2 = node.getSourceFile(); - return map(staticBlocks, (staticBlock) => { - let { pos } = moveRangePastModifiers(staticBlock); + return map(staticBlocks, staticBlock => { + let { + pos + } = moveRangePastModifiers(staticBlock); pos = skipTrivia(sourceFile2.text, pos); - return createDefinitionInfoFromName( - typeChecker, - staticBlock, - "constructor" /* constructorImplementationElement */, - "static {}", - containerName, - /*unverified*/ - false, - failedAliasResolution2, - { start: pos, length: "static".length } - ); + return createDefinitionInfoFromName(typeChecker, staticBlock, "constructor" /* constructorImplementationElement */, "static {}", containerName, /*unverified*/ + false, failedAliasResolution2, { + start: pos, + length: "static".length + }); }); } - let { symbol, failedAliasResolution } = getSymbol(node, typeChecker, stopAtAlias); + let { + symbol, + failedAliasResolution + } = getSymbol(node, typeChecker, stopAtAlias); let fallbackNode = node; if (searchOtherFilesOnly && failedAliasResolution) { - const importDeclaration = forEach([node, ...(symbol == null ? void 0 : symbol.declarations) || emptyArray], (n) => findAncestor(n, isAnyImportOrBareOrAccessedRequire)); + const importDeclaration = forEach([node, ...((symbol == null ? void 0 : symbol.declarations) || emptyArray)], n => findAncestor(n, isAnyImportOrBareOrAccessedRequire)); const moduleSpecifier = importDeclaration && tryGetModuleSpecifierFromDeclaration(importDeclaration); if (moduleSpecifier) { - ({ symbol, failedAliasResolution } = getSymbol(moduleSpecifier, typeChecker, stopAtAlias)); + ({ + symbol, + failedAliasResolution + } = getSymbol(moduleSpecifier, typeChecker, stopAtAlias)); fallbackNode = moduleSpecifier; } } @@ -163693,12 +147916,11 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} 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))) { const sigInfo = createDefinitionFromSignatureDeclaration(typeChecker, calledDeclaration, failedAliasResolution); - if (typeChecker.getRootSymbols(symbol).some((s) => symbolMatchesSignature(s, calledDeclaration))) { + if (typeChecker.getRootSymbols(symbol).some(s => symbolMatchesSignature(s, calledDeclaration))) { return [sigInfo]; } else { const defs = getDefinitionFromSymbol(typeChecker, symbol, node, failedAliasResolution, calledDeclaration) || emptyArray; @@ -163707,21 +147929,14 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } if (node.parent.kind === 304 /* ShorthandPropertyAssignment */) { const shorthandSymbol = typeChecker.getShorthandAssignmentValueSymbol(symbol.valueDeclaration); - const definitions = (shorthandSymbol == null ? void 0 : shorthandSymbol.declarations) ? shorthandSymbol.declarations.map((decl) => createDefinitionInfo( - decl, - typeChecker, - shorthandSymbol, - node, - /*unverified*/ - false, - failedAliasResolution - )) : emptyArray; + const definitions = (shorthandSymbol == null ? void 0 : shorthandSymbol.declarations) ? shorthandSymbol.declarations.map(decl => createDefinitionInfo(decl, typeChecker, shorthandSymbol, node, /*unverified*/ + false, failedAliasResolution)) : emptyArray; return concatenate(definitions, getDefinitionFromObjectLiteralElement(typeChecker, node)); } if (isPropertyName(node) && isBindingElement(parent2) && isObjectBindingPattern(parent2.parent) && node === (parent2.propertyName || parent2.name)) { const name = getNameFromPropertyName(node); const type = typeChecker.getTypeAtLocation(parent2.parent); - return name === void 0 ? emptyArray : flatMap(type.isUnion() ? type.types : [type], (t) => { + return name === void 0 ? emptyArray : flatMap(type.isUnion() ? type.types : [type], t => { const prop = t.getProperty(name); return prop && getDefinitionFromSymbol(typeChecker, prop, node); }); @@ -163738,35 +147953,25 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (element) { const contextualType = element && typeChecker.getContextualType(element.parent); if (contextualType) { - return flatMap(getPropertySymbolsFromContextualType( - element, - typeChecker, - contextualType, - /*unionSymbolOk*/ - false - ), (propertySymbol) => getDefinitionFromSymbol(typeChecker, propertySymbol, node)); + return flatMap(getPropertySymbolsFromContextualType(element, typeChecker, contextualType, /*unionSymbolOk*/ + false), propertySymbol => getDefinitionFromSymbol(typeChecker, propertySymbol, node)); } } return emptyArray; } 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) { @@ -163774,18 +147979,33 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} const referencePath = findReferenceInPosition(sourceFile.referencedFiles, position); if (referencePath) { const file = program.getSourceFileFromReference(sourceFile, referencePath); - return file && { reference: referencePath, fileName: file.fileName, file, unverified: false }; + return file && { + reference: referencePath, + fileName: file.fileName, + file, + unverified: false + }; } const typeReferenceDirective = findReferenceInPosition(sourceFile.typeReferenceDirectives, position); if (typeReferenceDirective) { const reference = (_a = program.getResolvedTypeReferenceDirectives().get(typeReferenceDirective.fileName, typeReferenceDirective.resolutionMode || sourceFile.impliedNodeFormat)) == null ? void 0 : _a.resolvedTypeReferenceDirective; const file = reference && program.getSourceFile(reference.resolvedFileName); - return file && { reference: typeReferenceDirective, fileName: file.fileName, file, unverified: false }; + return file && { + reference: typeReferenceDirective, + fileName: file.fileName, + file, + unverified: false + }; } const libReferenceDirective = findReferenceInPosition(sourceFile.libReferenceDirectives, position); if (libReferenceDirective) { const file = program.getLibFileFromReference(libReferenceDirective); - return file && { reference: libReferenceDirective, fileName: file.fileName, file, unverified: false }; + return file && { + reference: libReferenceDirective, + fileName: file.fileName, + file, + unverified: false + }; } if (sourceFile.imports.length || sourceFile.moduleAugmentations.length) { const node = getTouchingToken(sourceFile, position); @@ -163812,14 +148032,9 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (!typesWithUnwrappedTypeArguments.has(referenceName)) { return false; } - const globalType = typeChecker.resolveName( - referenceName, - /*location*/ - void 0, - 788968 /* Type */, - /*excludeGlobals*/ - false - ); + const globalType = typeChecker.resolveName(referenceName, /*location*/ + void 0, 788968 /* Type */, /*excludeGlobals*/ + false); return !!globalType && globalType === type.target.symbol; } function shouldUnwrapFirstTypeArgumentTypeDefinitionFromAlias(typeChecker, type) { @@ -163830,14 +148045,9 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (!typesWithUnwrappedTypeArguments.has(referenceName)) { return false; } - const globalType = typeChecker.resolveName( - referenceName, - /*location*/ - void 0, - 788968 /* Type */, - /*excludeGlobals*/ - false - ); + const globalType = typeChecker.resolveName(referenceName, /*location*/ + void 0, 788968 /* Type */, /*excludeGlobals*/ + false); return !!globalType && globalType === type.aliasSymbol; } function getFirstTypeArgumentDefinitions(typeChecker, type, node, failedAliasResolution) { @@ -163862,22 +148072,15 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return void 0; } if (isImportMeta(node.parent) && node.parent.name === node) { - return definitionFromType( - typeChecker.getTypeAtLocation(node.parent), - typeChecker, - node.parent, - /*failedAliasResolution*/ - false - ); + return definitionFromType(typeChecker.getTypeAtLocation(node.parent), typeChecker, node.parent, /*failedAliasResolution*/ + false); } - const { symbol, failedAliasResolution } = getSymbol( - node, - typeChecker, - /*stopAtAlias*/ - false - ); - if (!symbol) - return void 0; + const { + symbol, + failedAliasResolution + } = getSymbol(node, typeChecker, /*stopAtAlias*/ + false); + if (!symbol) return void 0; const typeAtLocation = typeChecker.getTypeOfSymbolAtLocation(symbol, node); const returnType = tryGetReturnTypeOfFunction(symbol, typeAtLocation, typeChecker); const fromReturnType = returnType && definitionFromType(returnType, typeChecker, node, failedAliasResolution); @@ -163885,14 +148088,14 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return typeDefinitions.length ? [...getFirstTypeArgumentDefinitions(typeChecker, resolvedType, node, failedAliasResolution), ...typeDefinitions] : !(symbol.flags & 111551 /* Value */) && symbol.flags & 788968 /* Type */ ? getDefinitionFromSymbol(typeChecker, skipAlias(symbol, typeChecker), node, failedAliasResolution) : void 0; } function definitionFromType(type, checker, node, failedAliasResolution) { - return flatMap(type.isUnion() && !(type.flags & 32 /* Enum */) ? type.types : [type], (t) => t.symbol && getDefinitionFromSymbol(checker, t.symbol, node, failedAliasResolution)); + return flatMap(type.isUnion() && !(type.flags & 32 /* Enum */) ? type.types : [type], t => t.symbol && getDefinitionFromSymbol(checker, t.symbol, node, failedAliasResolution)); } function tryGetReturnTypeOfFunction(symbol, type, checker) { - if (type.symbol === symbol || // At `const f = () => {}`, the symbol is `f` and the type symbol is at `() => {}` + 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; } @@ -163903,14 +148106,20 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } const comment = findReferenceInPosition(sourceFile.referencedFiles, position) || findReferenceInPosition(sourceFile.typeReferenceDirectives, position) || findReferenceInPosition(sourceFile.libReferenceDirectives, position); if (comment) { - return { definitions, textSpan: createTextSpanFromRange(comment) }; + return { + definitions, + textSpan: createTextSpanFromRange(comment) + }; } const node = getTouchingPropertyName(sourceFile, position); const textSpan = createTextSpan(node.getStart(), node.getWidth()); - return { definitions, textSpan }; + return { + definitions, + textSpan + }; } function getDefinitionInfoForIndexSignatures(node, checker) { - return mapDefined(checker.getIndexInfosAtLocation(node), (info) => info.declaration && createDefinitionFromSignatureDeclaration(checker, info.declaration)); + return mapDefined(checker.getIndexInfosAtLocation(node), info => info.declaration && createDefinitionFromSignatureDeclaration(checker, info.declaration)); } function getSymbol(node, checker, stopAtAlias) { const symbol = checker.getSymbolAtLocation(node); @@ -163918,12 +148127,17 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if ((symbol == null ? void 0 : symbol.declarations) && symbol.flags & 2097152 /* Alias */ && !stopAtAlias && shouldSkipAlias(node, symbol.declarations[0])) { const aliased = checker.getAliasedSymbol(symbol); if (aliased.declarations) { - return { symbol: aliased }; + return { + symbol: aliased + }; } else { failedAliasResolution = true; } } - return { symbol, failedAliasResolution }; + return { + symbol, + failedAliasResolution + }; } function shouldSkipAlias(node, declaration) { if (node.kind !== 80 /* Identifier */) { @@ -163938,62 +148152,40 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return true; } function isExpandoDeclaration(node) { - if (!isAssignmentDeclaration(node)) - return false; - const containingAssignment = findAncestor(node, (p) => { - if (isAssignmentExpression(p)) - return true; - if (!isAssignmentDeclaration(p)) - return "quit"; + if (!isAssignmentDeclaration(node)) return false; + const containingAssignment = findAncestor(node, p => { + if (isAssignmentExpression(p)) return true; + if (!isAssignmentDeclaration(p)) return "quit"; return false; }); return !!containingAssignment && getAssignmentDeclarationKind(containingAssignment) === 5 /* Property */; } + function getDefinitionFromSymbol(typeChecker, symbol, node, failedAliasResolution, excludeDeclaration) { - const filteredDeclarations = filter(symbol.declarations, (d) => d !== excludeDeclaration); - const withoutExpandos = filter(filteredDeclarations, (d) => !isExpandoDeclaration(d)); + const filteredDeclarations = filter(symbol.declarations, d => d !== excludeDeclaration); + const withoutExpandos = filter(filteredDeclarations, d => !isExpandoDeclaration(d)); const results = some(withoutExpandos) ? withoutExpandos : filteredDeclarations; - return getConstructSignatureDefinition() || getCallSignatureDefinition() || map(results, (declaration) => createDefinitionInfo( - declaration, - typeChecker, - symbol, - node, - /*unverified*/ - false, - failedAliasResolution - )); + return getConstructSignatureDefinition() || getCallSignatureDefinition() || map(results, declaration => createDefinitionInfo(declaration, typeChecker, symbol, node, /*unverified*/ + false, failedAliasResolution)); function getConstructSignatureDefinition() { if (symbol.flags & 32 /* Class */ && !(symbol.flags & (16 /* Function */ | 3 /* Variable */)) && (isNewExpressionTarget(node) || node.kind === 137 /* ConstructorKeyword */)) { const cls = find(filteredDeclarations, isClassLike) || Debug.fail("Expected declaration to have at least one class-like declaration"); - return getSignatureDefinition( - cls.members, - /*selectConstructors*/ - true - ); + return getSignatureDefinition(cls.members, /*selectConstructors*/ + true); } } function getCallSignatureDefinition() { - return isCallOrNewExpressionTarget(node) || isNameOfFunctionDeclaration(node) ? getSignatureDefinition( - filteredDeclarations, - /*selectConstructors*/ - false - ) : void 0; + return isCallOrNewExpressionTarget(node) || isNameOfFunctionDeclaration(node) ? getSignatureDefinition(filteredDeclarations, /*selectConstructors*/ + false) : void 0; } function getSignatureDefinition(signatureDeclarations, selectConstructors) { if (!signatureDeclarations) { return void 0; } const declarations = signatureDeclarations.filter(selectConstructors ? isConstructorDeclaration : isFunctionLike); - const declarationsWithBody = declarations.filter((d) => !!d.body); - return declarations.length ? declarationsWithBody.length !== 0 ? declarationsWithBody.map((x) => createDefinitionInfo(x, typeChecker, symbol, node)) : [createDefinitionInfo( - last(declarations), - typeChecker, - symbol, - node, - /*unverified*/ - false, - failedAliasResolution - )] : void 0; + const declarationsWithBody = declarations.filter(d => !!d.body); + return declarations.length ? declarationsWithBody.length !== 0 ? declarationsWithBody.map(x => createDefinitionInfo(x, typeChecker, symbol, node)) : [createDefinitionInfo(last(declarations), typeChecker, symbol, node, /*unverified*/ + false, failedAliasResolution)] : void 0; } } function createDefinitionInfo(declaration, checker, symbol, node, unverified, failedAliasResolution) { @@ -164016,11 +148208,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} containerKind: void 0, // TODO: GH#18217 containerName, - ...ts_FindAllReferences_exports.toContextSpan( - textSpan, - sourceFile, - ts_FindAllReferences_exports.getContextNode(declaration) - ), + ...ts_FindAllReferences_exports.toContextSpan(textSpan, sourceFile, ts_FindAllReferences_exports.getContextNode(declaration)), isLocal: !isDefinitionVisible(checker, declaration), isAmbient: !!(declaration.flags & 33554432 /* Ambient */), unverified, @@ -164028,19 +148216,15 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} }; } 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 */: @@ -164054,18 +148238,11 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } } function createDefinitionFromSignatureDeclaration(typeChecker, decl, failedAliasResolution) { - return createDefinitionInfo( - decl, - typeChecker, - decl.symbol, - decl, - /*unverified*/ - false, - failedAliasResolution - ); + return createDefinitionInfo(decl, typeChecker, decl.symbol, decl, /*unverified*/ + false, failedAliasResolution); } function findReferenceInPosition(refs, pos) { - return find(refs, (ref) => textRangeContainsPositionInclusive(ref, pos)); + return find(refs, ref => textRangeContainsPositionInclusive(ref, pos)); } function getDefinitionInfoForFileReference(name, targetFileName, unverified) { return { @@ -164080,14 +148257,14 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} }; } function getAncestorCallLikeExpression(node) { - const target = findAncestor(node, (n) => !isRightSideOfPropertyAccess(n)); + const target = findAncestor(node, n => !isRightSideOfPropertyAccess(n)); const callLike = target == null ? void 0 : target.parent; return callLike && isCallLikeExpression(callLike) && getInvokedExpression(callLike) === target ? callLike : void 0; } function tryGetSignatureDeclaration(typeChecker, node) { const callLike = getAncestorCallLikeExpression(node); const signature = callLike && typeChecker.getResolvedSignature(callLike); - return tryCast(signature && signature.declaration, (d) => isFunctionLike(d) && !isFunctionTypeNode(d)); + return tryCast(signature && signature.declaration, d => isFunctionLike(d) && !isFunctionTypeNode(d)); } function isConstructorLike(node) { switch (node.kind) { @@ -164103,28 +148280,9 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} var init_goToDefinition = __esm({ "src/services/goToDefinition.ts"() { "use strict"; + init_ts4(); - typesWithUnwrappedTypeArguments = /* @__PURE__ */ new Set([ - "Array", - "ArrayLike", - "ReadonlyArray", - "Promise", - "PromiseLike", - "Iterable", - "IterableIterator", - "AsyncIterable", - "Set", - "WeakSet", - "ReadonlySet", - "Map", - "WeakMap", - "ReadonlyMap", - "Partial", - "Required", - "Readonly", - "Pick", - "Omit" - ]); + typesWithUnwrappedTypeArguments = /* @__PURE__ */new Set(["Array", "ArrayLike", "ReadonlyArray", "Promise", "PromiseLike", "Iterable", "IterableIterator", "AsyncIterable", "Set", "WeakSet", "ReadonlySet", "Map", "WeakMap", "ReadonlyMap", "Partial", "Required", "Readonly", "Pick", "Omit"]); } }); @@ -164141,6 +148299,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} var init_ts_GoToDefinition = __esm({ "src/services/_namespaces/ts.GoToDefinition.ts"() { "use strict"; + init_goToDefinition(); } }); @@ -164156,7 +148315,13 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return preferences.interactiveInlayHints === true; } function provideInlayHints(context) { - const { file, program, span, cancellationToken, preferences } = context; + const { + file, + program, + span, + cancellationToken, + preferences + } = context; const sourceFileText = file.text; const compilerOptions = program.getCompilerOptions(); const quotePreference = getQuotePreference(file, preferences); @@ -164210,7 +148375,9 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} let hintText = `${isFirstVariadicArgument ? "..." : ""}${text}`; let displayParts; if (shouldUseInteractiveInlayHints(preferences)) { - displayParts = [getNodeDisplayPart(hintText, parameter), { text: ":" }]; + displayParts = [getNodeDisplayPart(hintText, parameter), { + text: ":" + }]; hintText = ""; } else { hintText += ":"; @@ -164226,7 +148393,9 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} function addTypeHints(hintText, position) { result.push({ text: typeof hintText === "string" ? `: ${hintText}` : "", - displayParts: typeof hintText === "string" ? void 0 : [{ text: ": " }, ...hintText], + displayParts: typeof hintText === "string" ? void 0 : [{ + text: ": " + }, ...hintText], position, kind: "Type" /* Type */, whitespaceBefore: true @@ -164252,6 +148421,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} function isModuleReferenceType(type) { return type.symbol && type.symbol.flags & 1536 /* Module */; } + function visitVariableLikeDeclaration(decl) { if (!decl.initializer || isBindingPattern(decl.name) || isVariableDeclaration(decl) && !isHintableDeclaration(decl)) { return; @@ -164266,7 +148436,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } const hintParts = typeToInlayHintParts(declarationType); if (hintParts) { - const hintText = typeof hintParts === "string" ? hintParts : hintParts.map((part) => part.text).join(""); + const hintText = typeof hintParts === "string" ? hintParts : hintParts.map(part => part.text).join(""); const isVariableNameMatchesType = preferences.includeInlayVariableTypeHintsWhenTypeMatchesName === false && equateStringsCaseInsensitive(decl.name.getText(), hintText); if (isVariableNameMatchesType) { return; @@ -164295,11 +148465,14 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (isSpreadElement(arg)) { const spreadType = checker.getTypeAtLocation(arg.expression); if (checker.isTupleType(spreadType)) { - const { elementFlags, fixedLength } = spreadType.target; + const { + elementFlags, + fixedLength + } = spreadType.target; if (fixedLength === 0) { continue; } - const firstOptionalIndex = findIndex(elementFlags, (f) => !(f & 1 /* Required */)); + const firstOptionalIndex = findIndex(elementFlags, f => !(f & 1 /* Required */)); const requiredArgs = firstOptionalIndex < 0 ? fixedLength : firstOptionalIndex; if (requiredArgs > 0) { spreadArgs = firstOptionalIndex < 0 ? fixedLength : firstOptionalIndex; @@ -164309,7 +148482,11 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} const identifierInfo = checker.getParameterIdentifierInfoAtPosition(signature, signatureParamPos); signatureParamPos = signatureParamPos + (spreadArgs || 1); if (identifierInfo) { - const { parameter, parameterName, isRestParameter: isFirstVariadicArgument } = identifierInfo; + const { + parameter, + parameterName, + isRestParameter: isFirstVariadicArgument + } = identifierInfo; const isParameterNameNotSameAsArgument = preferences.includeInlayParameterNameHintsWhenArgumentMatchesName || !identifierOrAccessExpressionPostfixMatchesParameterName(arg, parameterName); if (!isParameterNameNotSameAsArgument && !isFirstVariadicArgument) { continue; @@ -164340,24 +148517,26 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return false; } const regex = leadingParameterNameCommentRegexFactory(name); - return some(ranges, (range) => regex.test(sourceFileText.substring(range.pos, range.end))); + return some(ranges, range => regex.test(sourceFileText.substring(range.pos, range.end))); } function isHintableLiteral(node) { switch (node.kind) { - case 224 /* PrefixUnaryExpression */: { - const operand = node.operand; - return isLiteralExpression(operand) || isIdentifier(operand) && isInfinityOrNaNString(operand.escapedText); - } + case 224 /* PrefixUnaryExpression */: + { + const operand = node.operand; + return isLiteralExpression(operand) || isIdentifier(operand) && isInfinityOrNaNString(operand.escapedText); + } case 112 /* TrueKeyword */: case 97 /* FalseKeyword */: case 106 /* NullKeyword */: case 15 /* NoSubstitutionTemplateLiteral */: case 228 /* TemplateExpression */: return true; - case 80 /* Identifier */: { - const name = node.escapedText; - return isUndefined(name) || isInfinityOrNaNString(name); - } + case 80 /* Identifier */: + { + const name = node.escapedText; + return isUndefined(name) || isInfinityOrNaNString(name); + } } return isLiteralExpression(node); } @@ -164426,21 +148605,12 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} function printTypeInSingleLine(type) { const flags = 70221824 /* IgnoreErrors */ | 1048576 /* AllowUniqueESSymbolType */ | 16384 /* UseAliasDefinedOutsideCurrentScope */; const printer = createPrinterWithRemoveComments(); - return usingSingleLineStringWriter((writer) => { - const typeNode = checker.typeToTypeNode( - type, - /*enclosingDeclaration*/ - void 0, - flags - ); + return usingSingleLineStringWriter(writer => { + const typeNode = checker.typeToTypeNode(type, /*enclosingDeclaration*/ + void 0, flags); Debug.assertIsDefined(typeNode, "should always get typenode"); - printer.writeNode( - 4 /* Unspecified */, - typeNode, - /*sourceFile*/ - file, - writer - ); + printer.writeNode(4 /* Unspecified */, typeNode, /*sourceFile*/ + file, writer); }); } function typeToInlayHintParts(type) { @@ -164448,12 +148618,8 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return printTypeInSingleLine(type); } const flags = 70221824 /* IgnoreErrors */ | 1048576 /* AllowUniqueESSymbolType */ | 16384 /* UseAliasDefinedOutsideCurrentScope */; - const typeNode = checker.typeToTypeNode( - type, - /*enclosingDeclaration*/ - void 0, - flags - ); + const typeNode = checker.typeToTypeNode(type, /*enclosingDeclaration*/ + void 0, flags); Debug.assertIsDefined(typeNode, "should always get typenode"); const parts = []; visitForDisplayParts(typeNode); @@ -164464,11 +148630,15 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } const tokenString = tokenToString(node.kind); if (tokenString) { - parts.push({ text: tokenString }); + parts.push({ + text: tokenString + }); return; } if (isLiteralExpression(node)) { - parts.push({ text: getLiteralText2(node) }); + parts.push({ + text: getLiteralText2(node) + }); return; } switch (node.kind) { @@ -164479,23 +148649,31 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (name) { parts.push(getNodeDisplayPart(identifierText, name)); } else { - parts.push({ text: identifierText }); + parts.push({ + text: identifierText + }); } break; case 166 /* QualifiedName */: const qualifiedName = node; visitForDisplayParts(qualifiedName.left); - parts.push({ text: "." }); + parts.push({ + text: "." + }); visitForDisplayParts(qualifiedName.right); break; case 182 /* TypePredicate */: const predicate = node; if (predicate.assertsModifier) { - parts.push({ text: "asserts " }); + parts.push({ + text: "asserts " + }); } visitForDisplayParts(predicate.parameterName); if (predicate.type) { - parts.push({ text: " is " }); + parts.push({ + text: " is " + }); visitForDisplayParts(predicate.type); } break; @@ -164503,9 +148681,13 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} const typeReference = node; visitForDisplayParts(typeReference.typeName); if (typeReference.typeArguments) { - parts.push({ text: "<" }); + parts.push({ + text: "<" + }); visitDisplayPartList(typeReference.typeArguments, ", "); - parts.push({ text: ">" }); + parts.push({ + text: ">" + }); } break; case 168 /* TypeParameter */: @@ -164515,11 +148697,15 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } visitForDisplayParts(typeParameter.name); if (typeParameter.constraint) { - parts.push({ text: " extends " }); + parts.push({ + text: " extends " + }); visitForDisplayParts(typeParameter.constraint); } if (typeParameter.default) { - parts.push({ text: " = " }); + parts.push({ + text: " = " + }); visitForDisplayParts(typeParameter.default); } break; @@ -164529,78 +148715,126 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} visitDisplayPartList(parameter.modifiers, " "); } if (parameter.dotDotDotToken) { - parts.push({ text: "..." }); + parts.push({ + text: "..." + }); } visitForDisplayParts(parameter.name); if (parameter.questionToken) { - parts.push({ text: "?" }); + parts.push({ + text: "?" + }); } if (parameter.type) { - parts.push({ text: ": " }); + parts.push({ + text: ": " + }); visitForDisplayParts(parameter.type); } break; case 185 /* ConstructorType */: const constructorType = node; - parts.push({ text: "new " }); + parts.push({ + text: "new " + }); if (constructorType.typeParameters) { - parts.push({ text: "<" }); + parts.push({ + text: "<" + }); visitDisplayPartList(constructorType.typeParameters, ", "); - parts.push({ text: ">" }); + parts.push({ + text: ">" + }); } - parts.push({ text: "(" }); + parts.push({ + text: "(" + }); visitDisplayPartList(constructorType.parameters, ", "); - parts.push({ text: ")" }); - parts.push({ text: " => " }); + parts.push({ + text: ")" + }); + parts.push({ + text: " => " + }); visitForDisplayParts(constructorType.type); break; case 186 /* TypeQuery */: const typeQuery = node; - parts.push({ text: "typeof " }); + parts.push({ + text: "typeof " + }); visitForDisplayParts(typeQuery.exprName); if (typeQuery.typeArguments) { - parts.push({ text: "<" }); + parts.push({ + text: "<" + }); visitDisplayPartList(typeQuery.typeArguments, ", "); - parts.push({ text: ">" }); + parts.push({ + text: ">" + }); } break; case 187 /* TypeLiteral */: const typeLiteral = node; - parts.push({ text: "{" }); + parts.push({ + text: "{" + }); if (typeLiteral.members.length) { - parts.push({ text: " " }); + parts.push({ + text: " " + }); visitDisplayPartList(typeLiteral.members, "; "); - parts.push({ text: " " }); + parts.push({ + text: " " + }); } - parts.push({ text: "}" }); + parts.push({ + text: "}" + }); break; case 188 /* ArrayType */: visitForDisplayParts(node.elementType); - parts.push({ text: "[]" }); + parts.push({ + text: "[]" + }); break; case 189 /* TupleType */: - parts.push({ text: "[" }); + parts.push({ + text: "[" + }); visitDisplayPartList(node.elements, ", "); - parts.push({ text: "]" }); + parts.push({ + text: "]" + }); break; case 202 /* NamedTupleMember */: const member = node; if (member.dotDotDotToken) { - parts.push({ text: "..." }); + parts.push({ + text: "..." + }); } visitForDisplayParts(member.name); if (member.questionToken) { - parts.push({ text: "?" }); + parts.push({ + text: "?" + }); } - parts.push({ text: ": " }); + parts.push({ + text: ": " + }); visitForDisplayParts(member.type); break; case 190 /* OptionalType */: visitForDisplayParts(node.type); - parts.push({ text: "?" }); + parts.push({ + text: "?" + }); break; case 191 /* RestType */: - parts.push({ text: "..." }); + parts.push({ + text: "..." + }); visitForDisplayParts(node.type); break; case 192 /* UnionType */: @@ -164612,65 +148846,107 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} case 194 /* ConditionalType */: const conditionalType = node; visitForDisplayParts(conditionalType.checkType); - parts.push({ text: " extends " }); + parts.push({ + text: " extends " + }); visitForDisplayParts(conditionalType.extendsType); - parts.push({ text: " ? " }); + parts.push({ + text: " ? " + }); visitForDisplayParts(conditionalType.trueType); - parts.push({ text: " : " }); + parts.push({ + text: " : " + }); visitForDisplayParts(conditionalType.falseType); break; case 195 /* InferType */: - parts.push({ text: "infer " }); + parts.push({ + text: "infer " + }); visitForDisplayParts(node.typeParameter); break; case 196 /* ParenthesizedType */: - parts.push({ text: "(" }); + parts.push({ + text: "(" + }); visitForDisplayParts(node.type); - parts.push({ text: ")" }); + parts.push({ + text: ")" + }); break; case 198 /* TypeOperator */: const typeOperator = node; - parts.push({ text: `${tokenToString(typeOperator.operator)} ` }); + parts.push({ + text: `${tokenToString(typeOperator.operator)} ` + }); visitForDisplayParts(typeOperator.type); break; case 199 /* IndexedAccessType */: const indexedAccess = node; visitForDisplayParts(indexedAccess.objectType); - parts.push({ text: "[" }); + parts.push({ + text: "[" + }); visitForDisplayParts(indexedAccess.indexType); - parts.push({ text: "]" }); + parts.push({ + text: "]" + }); break; case 200 /* MappedType */: const mappedType = node; - parts.push({ text: "{ " }); + parts.push({ + text: "{ " + }); if (mappedType.readonlyToken) { if (mappedType.readonlyToken.kind === 40 /* PlusToken */) { - parts.push({ text: "+" }); + parts.push({ + text: "+" + }); } else if (mappedType.readonlyToken.kind === 41 /* MinusToken */) { - parts.push({ text: "-" }); + parts.push({ + text: "-" + }); } - parts.push({ text: "readonly " }); + parts.push({ + text: "readonly " + }); } - parts.push({ text: "[" }); + parts.push({ + text: "[" + }); visitForDisplayParts(mappedType.typeParameter); if (mappedType.nameType) { - parts.push({ text: " as " }); + parts.push({ + text: " as " + }); visitForDisplayParts(mappedType.nameType); } - parts.push({ text: "]" }); + parts.push({ + text: "]" + }); if (mappedType.questionToken) { if (mappedType.questionToken.kind === 40 /* PlusToken */) { - parts.push({ text: "+" }); + parts.push({ + text: "+" + }); } else if (mappedType.questionToken.kind === 41 /* MinusToken */) { - parts.push({ text: "-" }); + parts.push({ + text: "-" + }); } - parts.push({ text: "?" }); + parts.push({ + text: "?" + }); } - parts.push({ text: ": " }); + parts.push({ + text: ": " + }); if (mappedType.type) { visitForDisplayParts(mappedType.type); } - parts.push({ text: "; }" }); + parts.push({ + text: "; }" + }); break; case 201 /* LiteralType */: visitForDisplayParts(node.literal); @@ -164678,37 +148954,63 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} case 184 /* FunctionType */: const functionType = node; if (functionType.typeParameters) { - parts.push({ text: "<" }); + parts.push({ + text: "<" + }); visitDisplayPartList(functionType.typeParameters, ", "); - parts.push({ text: ">" }); + parts.push({ + text: ">" + }); } - parts.push({ text: "(" }); + parts.push({ + text: "(" + }); visitDisplayPartList(functionType.parameters, ", "); - parts.push({ text: ")" }); - parts.push({ text: " => " }); + parts.push({ + text: ")" + }); + parts.push({ + text: " => " + }); visitForDisplayParts(functionType.type); break; case 205 /* ImportType */: const importType = node; if (importType.isTypeOf) { - parts.push({ text: "typeof " }); + parts.push({ + text: "typeof " + }); } - parts.push({ text: "import(" }); + parts.push({ + text: "import(" + }); visitForDisplayParts(importType.argument); if (importType.assertions) { - parts.push({ text: ", { assert: " }); + parts.push({ + text: ", { assert: " + }); visitDisplayPartList(importType.assertions.assertClause.elements, ", "); - parts.push({ text: " }" }); + parts.push({ + text: " }" + }); } - parts.push({ text: ")" }); + parts.push({ + text: ")" + }); if (importType.qualifier) { - parts.push({ text: "." }); + parts.push({ + text: "." + }); visitForDisplayParts(importType.qualifier); } if (importType.typeArguments) { - parts.push({ text: "<" }); + parts.push({ + text: "<" + }); visitDisplayPartList(importType.typeArguments, ", "); - parts.push({ text: ">" }); + parts.push({ + text: ">" + }); } break; case 171 /* PropertySignature */: @@ -164718,10 +149020,14 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } visitForDisplayParts(propertySignature.name); if (propertySignature.questionToken) { - parts.push({ text: "?" }); + parts.push({ + text: "?" + }); } if (propertySignature.type) { - parts.push({ text: ": " }); + parts.push({ + text: ": " + }); visitForDisplayParts(propertySignature.type); } break; @@ -164732,7 +149038,9 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} function visitDisplayPartList(nodes, separator) { nodes.forEach((node, index) => { if (index > 0) { - parts.push({ text: separator }); + parts.push({ + text: separator + }); } visitForDisplayParts(node); }); @@ -164767,8 +149075,9 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} var init_inlayHints = __esm({ "src/services/inlayHints.ts"() { "use strict"; + init_ts4(); - leadingParameterNameCommentRegexFactory = (name) => { + leadingParameterNameCommentRegexFactory = name => { return new RegExp(`^\\s?/\\*\\*?\\s?${name}\\s?\\*\\/\\s?$`); }; } @@ -164782,6 +149091,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} var init_ts_InlayHints = __esm({ "src/services/_namespaces/ts.InlayHints.ts"() { "use strict"; + init_inlayHints(); } }); @@ -164789,10 +149099,10 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} // src/services/jsDoc.ts function getJsDocCommentsFromDeclarations(declarations, checker) { const parts = []; - forEachUnique(declarations, (declaration) => { + forEachUnique(declarations, declaration => { for (const jsdoc of getCommentHavingNodes(declaration)) { - const inheritDoc = isJSDoc(jsdoc) && jsdoc.tags && find(jsdoc.tags, (t) => t.kind === 334 /* JSDocTag */ && (t.tagName.escapedText === "inheritDoc" || t.tagName.escapedText === "inheritdoc")); - if (jsdoc.comment === void 0 && !inheritDoc || isJSDoc(jsdoc) && declaration.kind !== 353 /* JSDocTypedefTag */ && declaration.kind !== 345 /* JSDocCallbackTag */ && jsdoc.tags && jsdoc.tags.some((t) => t.kind === 353 /* JSDocTypedefTag */ || t.kind === 345 /* JSDocCallbackTag */) && !jsdoc.tags.some((t) => t.kind === 348 /* JSDocParameterTag */ || t.kind === 349 /* JSDocReturnTag */)) { + const inheritDoc = isJSDoc(jsdoc) && jsdoc.tags && find(jsdoc.tags, t => t.kind === 334 /* JSDocTag */ && (t.tagName.escapedText === "inheritDoc" || t.tagName.escapedText === "inheritdoc")); + if (jsdoc.comment === void 0 && !inheritDoc || isJSDoc(jsdoc) && declaration.kind !== 353 /* JSDocTypedefTag */ && declaration.kind !== 345 /* JSDocCallbackTag */ && jsdoc.tags && jsdoc.tags.some(t => t.kind === 353 /* JSDocTypedefTag */ || t.kind === 345 /* JSDocCallbackTag */) && !jsdoc.tags.some(t => t.kind === 348 /* JSDocParameterTag */ || t.kind === 349 /* JSDocReturnTag */)) { continue; } let newparts = jsdoc.comment ? getDisplayPartsFromComment(jsdoc.comment, checker) : []; @@ -164827,16 +149137,22 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } function getJsDocTagsFromDeclarations(declarations, checker) { const infos = []; - forEachUnique(declarations, (declaration) => { + forEachUnique(declarations, declaration => { const tags = getJSDocTags(declaration); - if (tags.some((t) => t.kind === 353 /* JSDocTypedefTag */ || t.kind === 345 /* JSDocCallbackTag */) && !tags.some((t) => t.kind === 348 /* JSDocParameterTag */ || t.kind === 349 /* JSDocReturnTag */)) { + if (tags.some(t => t.kind === 353 /* JSDocTypedefTag */ || t.kind === 345 /* JSDocCallbackTag */) && !tags.some(t => t.kind === 348 /* JSDocParameterTag */ || t.kind === 349 /* JSDocReturnTag */)) { return; } for (const tag of tags) { - infos.push({ name: tag.tagName.text, text: getCommentDisplayParts(tag, checker) }); + infos.push({ + name: tag.tagName.text, + text: getCommentDisplayParts(tag, checker) + }); if (isJSDocPropertyLikeTag(tag) && tag.isNameFirst && tag.typeExpression && isJSDocTypeLiteral(tag.typeExpression.type)) { - forEach(tag.typeExpression.type.jsDocPropertyTags, (propTag) => { - infos.push({ name: propTag.tagName.text, text: getCommentDisplayParts(propTag, checker) }); + forEach(tag.typeExpression.type.jsDocPropertyTags, propTag => { + infos.push({ + name: propTag.tagName.text, + text: getCommentDisplayParts(propTag, checker) + }); }); } } @@ -164847,13 +149163,13 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (typeof comment === "string") { return [textPart(comment)]; } - return flatMap( - comment, - (node) => node.kind === 328 /* JSDocText */ ? [textPart(node.text)] : buildLinkParts(node, checker) - ); + return flatMap(comment, node => node.kind === 328 /* JSDocText */ ? [textPart(node.text)] : buildLinkParts(node, checker)); } function getCommentDisplayParts(tag, checker) { - const { comment, kind } = tag; + const { + comment, + kind + } = tag; const namePart = getTagNameDisplayPart(kind); switch (kind) { case 356 /* JSDocThrowsTag */: @@ -164874,7 +149190,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} displayParts.push(spacePart()); } const lastTypeParameter = templateTag.typeParameters[templateTag.typeParameters.length - 1]; - forEach(templateTag.typeParameters, (tp) => { + forEach(templateTag.typeParameters, tp => { displayParts.push(namePart(tp.getText())); if (lastTypeParameter !== tp) { displayParts.push(...[punctuationPart(28 /* CommaToken */), spacePart()]); @@ -164893,7 +149209,9 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} case 355 /* JSDocPropertyTag */: case 348 /* JSDocParameterTag */: case 354 /* JSDocSeeTag */: - const { name } = tag; + const { + name + } = tag; return name ? withNode(name) : comment === void 0 ? void 0 : getDisplayPartsFromComment(comment, checker); default: return comment === void 0 ? void 0 : getDisplayPartsFromComment(comment, checker); @@ -164929,7 +149247,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } } function getJSDocTagNameCompletions() { - return jsDocTagNameCompletionEntries || (jsDocTagNameCompletionEntries = map(jsDocTagNames, (tagName) => { + return jsDocTagNameCompletionEntries || (jsDocTagNameCompletionEntries = map(jsDocTagNames, tagName => { return { name: tagName, kind: "keyword" /* keyword */, @@ -164939,7 +149257,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} })); } function getJSDocTagCompletions() { - return jsDocTagCompletionEntries || (jsDocTagCompletionEntries = map(jsDocTagNames, (tagName) => { + return jsDocTagCompletionEntries || (jsDocTagCompletionEntries = map(jsDocTagNames, tagName => { return { name: `@${tagName}`, kind: "keyword" /* keyword */, @@ -164952,6 +149270,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return { name, kind: "" /* unknown */, + // TODO: should have its own kind? kindModifiers: "", displayParts: [textPart(name)], @@ -164967,16 +149286,19 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} const nameThusFar = tag.name.text; const jsdoc = tag.parent; const fn = jsdoc.parent; - if (!isFunctionLike(fn)) - return []; - return mapDefined(fn.parameters, (param) => { - if (!isIdentifier(param.name)) - return void 0; + if (!isFunctionLike(fn)) return []; + return mapDefined(fn.parameters, param => { + if (!isIdentifier(param.name)) return void 0; const name = param.name.text; - if (jsdoc.tags.some((t) => t !== tag && isJSDocParameterTag(t) && isIdentifier(t.name) && t.name.escapedText === name) || nameThusFar !== void 0 && !startsWith(name, nameThusFar)) { + if (jsdoc.tags.some(t => t !== tag && isJSDocParameterTag(t) && isIdentifier(t.name) && t.name.escapedText === name) || nameThusFar !== void 0 && !startsWith(name, nameThusFar)) { return void 0; } - return { name, kind: "parameter" /* parameterElement */, kindModifiers: "", sortText: ts_Completions_exports.SortText.LocationPriority }; + return { + name, + kind: "parameter" /* parameterElement */, + kindModifiers: "", + sortText: ts_Completions_exports.SortText.LocationPriority + }; }); } function getJSDocParameterNameCompletionDetails(name) { @@ -165004,7 +149326,11 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (!commentOwnerInfo) { return void 0; } - const { commentOwner, parameters, hasReturn: hasReturn2 } = commentOwnerInfo; + const { + commentOwner, + parameters, + hasReturn: hasReturn2 + } = commentOwnerInfo; const commentOwnerJsDoc = hasJSDocNodes(commentOwner) && commentOwner.jsDoc ? commentOwner.jsDoc : void 0; const lastJsDoc = lastOrUndefined(commentOwnerJsDoc); if (commentOwner.getStart(sourceFile) < position || lastJsDoc && existingDocComment && lastJsDoc !== existingDocComment) { @@ -165020,20 +149346,30 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} const preamble = openComment + newLine + indentationStr + " * "; const endLine = tokenStart === position ? newLine + indentationStr : ""; const result = preamble + newLine + tags + indentationStr + closeComment + endLine; - return { newText: result, caretOffset: preamble.length }; + return { + newText: result, + caretOffset: preamble.length + }; } - return { newText: openComment + closeComment, caretOffset: 3 }; + return { + newText: openComment + closeComment, + caretOffset: 3 + }; } function getIndentationStringAtPosition(sourceFile, position) { - const { text } = sourceFile; + 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) { - return parameters.map(({ name, dotDotDotToken }, i) => { + return parameters.map(({ + name, + dotDotDotToken + }, i) => { const paramName = name.kind === 80 /* Identifier */ ? name.text : "param" + i; const type = isJavaScriptFile ? dotDotDotToken ? "{...any} " : "{any} " : ""; return `${indentationStr} * @param ${type}${paramName}${newLine}`; @@ -165043,7 +149379,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return `${indentationStr} * @returns${newLine}`; } function getCommentOwnerInfo(tokenAtPos, options) { - return forEachAncestor(tokenAtPos, (n) => getCommentOwnerInfoWorker(n, options)); + return forEachAncestor(tokenAtPos, n => getCommentOwnerInfoWorker(n, options)); } function getCommentOwnerInfoWorker(commentOwner, options) { switch (commentOwner.kind) { @@ -165054,7 +149390,11 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} case 173 /* MethodSignature */: case 219 /* ArrowFunction */: const host = commentOwner; - return { commentOwner, parameters: host.parameters, hasReturn: hasReturn(host, options) }; + return { + commentOwner, + parameters: host.parameters, + hasReturn: hasReturn(host, options) + }; case 303 /* PropertyAssignment */: return getCommentOwnerInfoWorker(commentOwner.initializer, options); case 263 /* ClassDeclaration */: @@ -165062,39 +149402,68 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} case 266 /* EnumDeclaration */: case 306 /* EnumMember */: case 265 /* TypeAliasDeclaration */: - return { commentOwner }; - case 171 /* PropertySignature */: { - const host2 = commentOwner; - return host2.type && isFunctionTypeNode(host2.type) ? { commentOwner, parameters: host2.type.parameters, hasReturn: hasReturn(host2.type, options) } : { commentOwner }; - } - case 243 /* VariableStatement */: { - const varStatement = commentOwner; - const varDeclarations = varStatement.declarationList.declarations; - const host2 = varDeclarations.length === 1 && varDeclarations[0].initializer ? getRightHandSideOfAssignment(varDeclarations[0].initializer) : void 0; - return host2 ? { commentOwner, parameters: host2.parameters, hasReturn: hasReturn(host2, options) } : { commentOwner }; - } + return { + commentOwner + }; + case 171 /* PropertySignature */: + { + const host2 = commentOwner; + return host2.type && isFunctionTypeNode(host2.type) ? { + commentOwner, + parameters: host2.type.parameters, + hasReturn: hasReturn(host2.type, options) + } : { + commentOwner + }; + } + case 243 /* VariableStatement */: + { + const varStatement = commentOwner; + const varDeclarations = varStatement.declarationList.declarations; + const host2 = varDeclarations.length === 1 && varDeclarations[0].initializer ? getRightHandSideOfAssignment(varDeclarations[0].initializer) : void 0; + return host2 ? { + commentOwner, + parameters: host2.parameters, + hasReturn: hasReturn(host2, options) + } : { + commentOwner + }; + } case 312 /* SourceFile */: return "quit"; case 267 /* ModuleDeclaration */: - return commentOwner.parent.kind === 267 /* ModuleDeclaration */ ? void 0 : { commentOwner }; + return commentOwner.parent.kind === 267 /* ModuleDeclaration */ ? void 0 : { + commentOwner + }; case 244 /* ExpressionStatement */: return getCommentOwnerInfoWorker(commentOwner.expression, options); - case 226 /* BinaryExpression */: { - const be = commentOwner; - if (getAssignmentDeclarationKind(be) === 0 /* None */) { - return "quit"; + case 226 /* BinaryExpression */: + { + const be = commentOwner; + if (getAssignmentDeclarationKind(be) === 0 /* None */) { + return "quit"; + } + return isFunctionLike(be.right) ? { + commentOwner, + parameters: be.right.parameters, + hasReturn: hasReturn(be.right, options) + } : { + commentOwner + }; } - return isFunctionLike(be.right) ? { commentOwner, parameters: be.right.parameters, hasReturn: hasReturn(be.right, options) } : { commentOwner }; - } case 172 /* PropertyDeclaration */: const init = commentOwner.initializer; if (init && (isFunctionExpression(init) || isArrowFunction(init))) { - return { commentOwner, parameters: init.parameters, hasReturn: hasReturn(init, options) }; + return { + commentOwner, + parameters: init.parameters, + hasReturn: hasReturn(init, options) + }; } } } function hasReturn(node, options) { - return !!(options == null ? void 0 : options.generateReturnInDocTemplate) && (isFunctionTypeNode(node) || isArrowFunction(node) && isExpression(node.body) || isFunctionLikeDeclaration(node) && node.body && isBlock(node.body) && !!forEachReturnStatement(node.body, (n) => n)); + return !!(options == null ? void 0 : options.generateReturnInDocTemplate) && (isFunctionTypeNode(node) || isArrowFunction(node) && isExpression(node.body) || isFunctionLikeDeclaration(node) && node.body && isBlock(node.body) && !!forEachReturnStatement(node.body, n => n)); } function getRightHandSideOfAssignment(rightHandSide) { while (rightHandSide.kind === 217 /* ParenthesizedExpression */) { @@ -165112,92 +149481,9 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} var init_jsDoc = __esm({ "src/services/jsDoc.ts"() { "use strict"; + init_ts4(); - jsDocTagNames = [ - "abstract", - "access", - "alias", - "argument", - "async", - "augments", - "author", - "borrows", - "callback", - "class", - "classdesc", - "constant", - "constructor", - "constructs", - "copyright", - "default", - "deprecated", - "description", - "emits", - "enum", - "event", - "example", - "exports", - "extends", - "external", - "field", - "file", - "fileoverview", - "fires", - "function", - "generator", - "global", - "hideconstructor", - "host", - "ignore", - "implements", - "inheritdoc", - "inner", - "instance", - "interface", - "kind", - "lends", - "license", - "link", - "linkcode", - "linkplain", - "listens", - "member", - "memberof", - "method", - "mixes", - "module", - "name", - "namespace", - "overload", - "override", - "package", - "param", - "private", - "prop", - "property", - "protected", - "public", - "readonly", - "requires", - "returns", - "satisfies", - "see", - "since", - "static", - "summary", - "template", - "this", - "throws", - "todo", - "tutorial", - "type", - "typedef", - "var", - "variation", - "version", - "virtual", - "yields" - ]; + jsDocTagNames = ["abstract", "access", "alias", "argument", "async", "augments", "author", "borrows", "callback", "class", "classdesc", "constant", "constructor", "constructs", "copyright", "default", "deprecated", "description", "emits", "enum", "event", "example", "exports", "extends", "external", "field", "file", "fileoverview", "fires", "function", "generator", "global", "hideconstructor", "host", "ignore", "implements", "inheritdoc", "inner", "instance", "interface", "kind", "lends", "license", "link", "linkcode", "linkplain", "listens", "member", "memberof", "method", "mixes", "module", "name", "namespace", "overload", "override", "package", "param", "private", "prop", "property", "protected", "public", "readonly", "requires", "returns", "satisfies", "see", "since", "static", "summary", "template", "this", "throws", "todo", "tutorial", "type", "typedef", "var", "variation", "version", "virtual", "yields"]; getJSDocTagNameCompletionDetails = getJSDocTagCompletionDetails; } }); @@ -165218,39 +149504,40 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} var init_ts_JsDoc = __esm({ "src/services/_namespaces/ts.JsDoc.ts"() { "use strict"; + init_jsDoc(); } }); // src/services/organizeImports.ts function organizeImports(sourceFile, formatContext, host, program, preferences, mode) { - const changeTracker = ts_textChanges_exports.ChangeTracker.fromContext({ host, formatContext, preferences }); + const changeTracker = ts_textChanges_exports.ChangeTracker.fromContext({ + host, + formatContext, + preferences + }); const shouldSort = mode === "SortAndCombine" /* SortAndCombine */ || mode === "All" /* All */; const shouldCombine = shouldSort; const shouldRemove = mode === "RemoveUnused" /* RemoveUnused */ || mode === "All" /* All */; const topLevelImportGroupDecls = groupByNewlineContiguous(sourceFile, sourceFile.statements.filter(isImportDeclaration)); const comparer = getOrganizeImportsComparerWithDetection(preferences, shouldSort ? () => detectSortingWorker(topLevelImportGroupDecls, preferences) === 2 /* CaseInsensitive */ : void 0); - const processImportsOfSameModuleSpecifier = (importGroup) => { - if (shouldRemove) - importGroup = removeUnusedImports(importGroup, sourceFile, program); - if (shouldCombine) - importGroup = coalesceImportsWorker(importGroup, comparer, sourceFile); - if (shouldSort) - importGroup = stableSort(importGroup, (s1, s2) => compareImportsOrRequireStatements(s1, s2, comparer)); + const processImportsOfSameModuleSpecifier = importGroup => { + if (shouldRemove) importGroup = removeUnusedImports(importGroup, sourceFile, program); + if (shouldCombine) importGroup = coalesceImportsWorker(importGroup, comparer, sourceFile); + if (shouldSort) importGroup = stableSort(importGroup, (s1, s2) => compareImportsOrRequireStatements(s1, s2, comparer)); return importGroup; }; - topLevelImportGroupDecls.forEach((importGroupDecl) => organizeImportsWorker(importGroupDecl, processImportsOfSameModuleSpecifier)); + topLevelImportGroupDecls.forEach(importGroupDecl => organizeImportsWorker(importGroupDecl, processImportsOfSameModuleSpecifier)); if (mode !== "RemoveUnused" /* RemoveUnused */) { - getTopLevelExportGroups(sourceFile).forEach((exportGroupDecl) => organizeImportsWorker(exportGroupDecl, (group2) => coalesceExportsWorker(group2, comparer))); + getTopLevelExportGroups(sourceFile).forEach(exportGroupDecl => organizeImportsWorker(exportGroupDecl, group2 => coalesceExportsWorker(group2, comparer))); } 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, processImportsOfSameModuleSpecifier)); + ambientModuleImportGroupDecls.forEach(importGroupDecl => organizeImportsWorker(importGroupDecl, processImportsOfSameModuleSpecifier)); if (mode !== "RemoveUnused" /* RemoveUnused */) { const ambientModuleExportDecls = ambientModule.body.statements.filter(isExportDeclaration); - organizeImportsWorker(ambientModuleExportDecls, (group2) => coalesceExportsWorker(group2, comparer)); + organizeImportsWorker(ambientModuleExportDecls, group2 => coalesceExportsWorker(group2, comparer)); } } return changeTracker.getChanges(); @@ -165259,20 +149546,15 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return; } setEmitFlags(oldImportDecls[0], 1024 /* NoLeadingComments */); - const oldImportGroups = shouldCombine ? group(oldImportDecls, (importDecl) => getExternalModuleName2(importDecl.moduleSpecifier)) : [oldImportDecls]; + const oldImportGroups = shouldCombine ? group(oldImportDecls, importDecl => getExternalModuleName2(importDecl.moduleSpecifier)) : [oldImportDecls]; const sortedImportGroups = shouldSort ? stableSort(oldImportGroups, (group1, group2) => compareModuleSpecifiersWorker(group1[0].moduleSpecifier, group2[0].moduleSpecifier, comparer)) : oldImportGroups; - const newImportDecls = flatMap(sortedImportGroups, (importGroup) => getExternalModuleName2(importGroup[0].moduleSpecifier) || importGroup[0].moduleSpecifier === void 0 ? coalesce(importGroup) : importGroup); + const newImportDecls = flatMap(sortedImportGroups, importGroup => getExternalModuleName2(importGroup[0].moduleSpecifier) || importGroup[0].moduleSpecifier === void 0 ? coalesce(importGroup) : importGroup); if (newImportDecls.length === 0) { - changeTracker.deleteNodes( - sourceFile, - oldImportDecls, - { - leadingTriviaOption: ts_textChanges_exports.LeadingTriviaOption.Exclude, - trailingTriviaOption: ts_textChanges_exports.TrailingTriviaOption.Include - }, - /*hasTrailingComment*/ - true - ); + changeTracker.deleteNodes(sourceFile, oldImportDecls, { + leadingTriviaOption: ts_textChanges_exports.LeadingTriviaOption.Exclude, + trailingTriviaOption: ts_textChanges_exports.TrailingTriviaOption.Include + }, /*hasTrailingComment*/ + true); } else { const replaceOptions = { leadingTriviaOption: ts_textChanges_exports.LeadingTriviaOption.Exclude, @@ -165289,12 +149571,8 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } } function groupByNewlineContiguous(sourceFile, decls) { - const scanner2 = createScanner( - sourceFile.languageVersion, - /*skipTrivia*/ - false, - sourceFile.languageVariant - ); + const scanner2 = createScanner(sourceFile.languageVersion, /*skipTrivia*/ + false, sourceFile.languageVariant); const group2 = []; let groupIndex = 0; for (const decl of decls) { @@ -165332,12 +149610,18 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} const jsxElementsPresent = !!(sourceFile.transformFlags & 2 /* ContainsJsx */); const usedImports = []; for (const importDecl of oldImports) { - const { importClause, moduleSpecifier } = importDecl; + const { + importClause, + moduleSpecifier + } = importDecl; if (!importClause) { usedImports.push(importDecl); continue; } - let { name, namedBindings } = importClause; + let { + name, + namedBindings + } = importClause; if (name && !isDeclarationUsed(name)) { name = void 0; } @@ -165347,7 +149631,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} namedBindings = void 0; } } else { - const newElements = namedBindings.elements.filter((e) => isDeclarationUsed(e.name)); + const newElements = namedBindings.elements.filter(e => isDeclarationUsed(e.name)); if (newElements.length < namedBindings.elements.length) { namedBindings = newElements.length ? factory.updateNamedImports(namedBindings, newElements) : void 0; } @@ -165357,14 +149641,9 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} usedImports.push(updateImportDeclarationAndClause(importDecl, name, namedBindings)); } else if (hasModuleDeclarationMatchingSpecifier(sourceFile, moduleSpecifier)) { if (sourceFile.isDeclarationFile) { - usedImports.push(factory.createImportDeclaration( - importDecl.modifiers, - /*importClause*/ - void 0, - moduleSpecifier, - /*attributes*/ - void 0 - )); + usedImports.push(factory.createImportDeclaration(importDecl.modifiers, /*importClause*/ + void 0, moduleSpecifier, /*attributes*/ + void 0)); } else { usedImports.push(importDecl); } @@ -165377,7 +149656,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } function hasModuleDeclarationMatchingSpecifier(sourceFile, moduleSpecifier) { const moduleSpecifierText = isStringLiteral(moduleSpecifier) && moduleSpecifier.text; - return isString(moduleSpecifierText) && some(sourceFile.moduleAugmentations, (moduleName) => isStringLiteral(moduleName) && moduleName.text === moduleSpecifierText); + return isString(moduleSpecifierText) && some(sourceFile.moduleAugmentations, moduleName => isStringLiteral(moduleName) && moduleName.text === moduleSpecifierText); } function getExternalModuleName2(specifier) { return specifier !== void 0 && isStringLiteralLike(specifier) ? specifier.text : void 0; @@ -165390,35 +149669,35 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (importGroup.length === 0) { return importGroup; } - const { importWithoutClause, typeOnlyImports, regularImports } = getCategorizedImports(importGroup); + const { + importWithoutClause, + typeOnlyImports, + regularImports + } = getCategorizedImports(importGroup); const coalescedImports = []; if (importWithoutClause) { coalescedImports.push(importWithoutClause); } for (const group2 of [regularImports, typeOnlyImports]) { const isTypeOnly = group2 === typeOnlyImports; - const { defaultImports, namespaceImports, namedImports } = group2; + const { + defaultImports, + namespaceImports, + namedImports + } = group2; if (!isTypeOnly && defaultImports.length === 1 && namespaceImports.length === 1 && namedImports.length === 0) { const defaultImport = defaultImports[0]; - coalescedImports.push( - updateImportDeclarationAndClause(defaultImport, defaultImport.importClause.name, namespaceImports[0].importClause.namedBindings) - ); + coalescedImports.push(updateImportDeclarationAndClause(defaultImport, defaultImport.importClause.name, namespaceImports[0].importClause.namedBindings)); continue; } const sortedNamespaceImports = stableSort(namespaceImports, (i1, i2) => comparer(i1.importClause.namedBindings.name.text, i2.importClause.namedBindings.name.text)); for (const namespaceImport of sortedNamespaceImports) { - coalescedImports.push( - updateImportDeclarationAndClause( - namespaceImport, - /*name*/ - void 0, - namespaceImport.importClause.namedBindings - ) - ); + coalescedImports.push(updateImportDeclarationAndClause(namespaceImport, /*name*/ + void 0, namespaceImport.importClause.namedBindings)); } const firstDefaultImport = firstOrUndefined(defaultImports); const firstNamedImport = firstOrUndefined(namedImports); - const importDecl = firstDefaultImport ?? firstNamedImport; + const importDecl = firstDefaultImport !== null && firstDefaultImport !== void 0 ? firstDefaultImport : firstNamedImport; if (!importDecl) { continue; } @@ -165428,61 +149707,50 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} newDefaultImport = defaultImports[0].importClause.name; } else { for (const defaultImport of defaultImports) { - newImportSpecifiers.push( - factory.createImportSpecifier( - /*isTypeOnly*/ - false, - factory.createIdentifier("default"), - defaultImport.importClause.name - ) - ); + newImportSpecifiers.push(factory.createImportSpecifier( /*isTypeOnly*/ + false, factory.createIdentifier("default"), defaultImport.importClause.name)); } } newImportSpecifiers.push(...getNewImportSpecifiers(namedImports)); - const sortedImportSpecifiers = factory.createNodeArray( - sortSpecifiers(newImportSpecifiers, comparer), - firstNamedImport == null ? void 0 : firstNamedImport.importClause.namedBindings.elements.hasTrailingComma - ); + const sortedImportSpecifiers = factory.createNodeArray(sortSpecifiers(newImportSpecifiers, comparer), firstNamedImport == null ? void 0 : firstNamedImport.importClause.namedBindings.elements.hasTrailingComma); const newNamedImports = sortedImportSpecifiers.length === 0 ? newDefaultImport ? void 0 : factory.createNamedImports(emptyArray) : firstNamedImport ? factory.updateNamedImports(firstNamedImport.importClause.namedBindings, sortedImportSpecifiers) : factory.createNamedImports(sortedImportSpecifiers); if (sourceFile && newNamedImports && (firstNamedImport == null ? void 0 : firstNamedImport.importClause.namedBindings) && !rangeIsOnSingleLine(firstNamedImport.importClause.namedBindings, sourceFile)) { setEmitFlags(newNamedImports, 2 /* MultiLine */); } + if (isTypeOnly && newDefaultImport && newNamedImports) { - coalescedImports.push( - updateImportDeclarationAndClause( - importDecl, - newDefaultImport, - /*namedBindings*/ - void 0 - ) - ); - coalescedImports.push( - updateImportDeclarationAndClause( - firstNamedImport ?? importDecl, - /*name*/ - void 0, - newNamedImports - ) - ); + coalescedImports.push(updateImportDeclarationAndClause(importDecl, newDefaultImport, /*namedBindings*/ + void 0)); + coalescedImports.push(updateImportDeclarationAndClause(firstNamedImport !== null && firstNamedImport !== void 0 ? firstNamedImport : importDecl, /*name*/ + void 0, newNamedImports)); } else { - coalescedImports.push( - updateImportDeclarationAndClause(importDecl, newDefaultImport, newNamedImports) - ); + coalescedImports.push(updateImportDeclarationAndClause(importDecl, newDefaultImport, newNamedImports)); } } return coalescedImports; } function getCategorizedImports(importGroup) { let importWithoutClause; - const typeOnlyImports = { defaultImports: [], namespaceImports: [], namedImports: [] }; - const regularImports = { defaultImports: [], namespaceImports: [], namedImports: [] }; + const typeOnlyImports = { + defaultImports: [], + namespaceImports: [], + namedImports: [] + }; + const regularImports = { + defaultImports: [], + namespaceImports: [], + namedImports: [] + }; for (const importDeclaration of importGroup) { if (importDeclaration.importClause === void 0) { importWithoutClause = importWithoutClause || importDeclaration; continue; } const group2 = importDeclaration.importClause.isTypeOnly ? typeOnlyImports : regularImports; - const { name, namedBindings } = importDeclaration.importClause; + const { + name, + namedBindings + } = importDeclaration.importClause; if (name) { group2.defaultImports.push(importDeclaration); } @@ -165508,7 +149776,11 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (exportGroup.length === 0) { return exportGroup; } - const { exportWithoutClause, namedExports, typeOnlyExports } = getCategorizedExports(exportGroup); + const { + exportWithoutClause, + namedExports, + typeOnlyExports + } = getCategorizedExports(exportGroup); const coalescedExports = []; if (exportWithoutClause) { coalescedExports.push(exportWithoutClause); @@ -165518,19 +149790,10 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} continue; } const newExportSpecifiers = []; - newExportSpecifiers.push(...flatMap(exportGroup2, (i) => i.exportClause && isNamedExports(i.exportClause) ? i.exportClause.elements : emptyArray)); + newExportSpecifiers.push(...flatMap(exportGroup2, i => i.exportClause && isNamedExports(i.exportClause) ? i.exportClause.elements : emptyArray)); const sortedExportSpecifiers = sortSpecifiers(newExportSpecifiers, comparer); const exportDecl = exportGroup2[0]; - coalescedExports.push( - factory.updateExportDeclaration( - exportDecl, - exportDecl.modifiers, - exportDecl.isTypeOnly, - exportDecl.exportClause && (isNamedExports(exportDecl.exportClause) ? factory.updateNamedExports(exportDecl.exportClause, sortedExportSpecifiers) : factory.updateNamespaceExport(exportDecl.exportClause, exportDecl.exportClause.name)), - exportDecl.moduleSpecifier, - exportDecl.attributes - ) - ); + coalescedExports.push(factory.updateExportDeclaration(exportDecl, exportDecl.modifiers, exportDecl.isTypeOnly, exportDecl.exportClause && (isNamedExports(exportDecl.exportClause) ? factory.updateNamedExports(exportDecl.exportClause, sortedExportSpecifiers) : factory.updateNamespaceExport(exportDecl.exportClause, exportDecl.exportClause.name)), exportDecl.moduleSpecifier, exportDecl.attributes)); } return coalescedExports; function getCategorizedExports(exportGroup2) { @@ -165554,14 +149817,9 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } } function updateImportDeclarationAndClause(importDeclaration, name, namedBindings) { - return factory.updateImportDeclaration( - importDeclaration, - importDeclaration.modifiers, - factory.updateImportClause(importDeclaration.importClause, importDeclaration.importClause.isTypeOnly, name, namedBindings), - // TODO: GH#18217 - importDeclaration.moduleSpecifier, - importDeclaration.attributes - ); + return factory.updateImportDeclaration(importDeclaration, importDeclaration.modifiers, factory.updateImportClause(importDeclaration.importClause, importDeclaration.importClause.isTypeOnly, name, namedBindings), + // TODO: GH#18217 + importDeclaration.moduleSpecifier, importDeclaration.attributes); } function sortSpecifiers(specifiers, comparer) { return stableSort(specifiers, (s1, s2) => compareImportOrExportSpecifiers(s1, s2, comparer)); @@ -165590,35 +149848,22 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } } function detectSorting(sourceFile, preferences) { - return detectSortingWorker( - groupByNewlineContiguous(sourceFile, sourceFile.statements.filter(isImportDeclaration)), - preferences - ); + return detectSortingWorker(groupByNewlineContiguous(sourceFile, sourceFile.statements.filter(isImportDeclaration)), preferences); } function detectSortingWorker(importGroups, preferences) { - const collateCaseSensitive = getOrganizeImportsComparer( - preferences, - /*ignoreCase*/ - false - ); - const collateCaseInsensitive = getOrganizeImportsComparer( - preferences, - /*ignoreCase*/ - true - ); + const collateCaseSensitive = getOrganizeImportsComparer(preferences, /*ignoreCase*/ + false); + const collateCaseInsensitive = getOrganizeImportsComparer(preferences, /*ignoreCase*/ + true); let sortState = 3 /* Both */; let seenUnsortedGroup = false; for (const importGroup of importGroups) { if (importGroup.length > 1) { - const moduleSpecifierSort = detectSortCaseSensitivity( - importGroup, - (i) => { - var _a; - return ((_a = tryCast(i.moduleSpecifier, isStringLiteral)) == null ? void 0 : _a.text) ?? ""; - }, - collateCaseSensitive, - collateCaseInsensitive - ); + const moduleSpecifierSort = detectSortCaseSensitivity(importGroup, i => { + var _ref47; + var _a; + return (_ref47 = (_a = tryCast(i.moduleSpecifier, isStringLiteral)) == null ? void 0 : _a.text) !== null && _ref47 !== void 0 ? _ref47 : ""; + }, collateCaseSensitive, collateCaseInsensitive); if (moduleSpecifierSort) { sortState &= moduleSpecifierSort; seenUnsortedGroup = true; @@ -165627,13 +149872,10 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return sortState; } } - const declarationWithNamedImports = find( - importGroup, - (i) => { - var _a, _b; - return ((_b = tryCast((_a = i.importClause) == null ? void 0 : _a.namedBindings, isNamedImports)) == null ? void 0 : _b.elements.length) > 1; - } - ); + const declarationWithNamedImports = find(importGroup, i => { + var _a, _b; + return ((_b = tryCast((_a = i.importClause) == null ? void 0 : _a.namedBindings, isNamedImports)) == null ? void 0 : _b.elements.length) > 1; + }); if (declarationWithNamedImports) { const namedImportSort = detectImportSpecifierSorting(declarationWithNamedImports.importClause.namedBindings.elements, preferences); if (namedImportSort) { @@ -165651,22 +149893,11 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return seenUnsortedGroup ? 0 /* None */ : sortState; } function detectImportDeclarationSorting(imports, preferences) { - const collateCaseSensitive = getOrganizeImportsComparer( - preferences, - /*ignoreCase*/ - false - ); - const collateCaseInsensitive = getOrganizeImportsComparer( - preferences, - /*ignoreCase*/ - true - ); - return detectSortCaseSensitivity( - imports, - (s) => getExternalModuleName2(getModuleSpecifierExpression(s)) || "", - collateCaseSensitive, - collateCaseInsensitive - ); + const collateCaseSensitive = getOrganizeImportsComparer(preferences, /*ignoreCase*/ + false); + const collateCaseInsensitive = getOrganizeImportsComparer(preferences, /*ignoreCase*/ + true); + return detectSortCaseSensitivity(imports, s => getExternalModuleName2(getModuleSpecifierExpression(s)) || "", collateCaseSensitive, collateCaseInsensitive); } function getImportDeclarationInsertionIndex(sortedImports, newImport, comparer) { const index = binarySearch(sortedImports, newImport, identity, (a, b) => compareImportsOrRequireStatements(a, b, comparer)); @@ -165686,14 +149917,10 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} 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; @@ -165702,13 +149929,8 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } } function getNewImportSpecifiers(namedImports) { - return flatMap(namedImports, (namedImport) => map(tryGetNamedBindingElements(namedImport), (importSpecifier) => importSpecifier.name && importSpecifier.propertyName && importSpecifier.name.escapedText === importSpecifier.propertyName.escapedText ? factory.updateImportSpecifier( - importSpecifier, - importSpecifier.isTypeOnly, - /*propertyName*/ - void 0, - importSpecifier.name - ) : importSpecifier)); + return flatMap(namedImports, namedImport => map(tryGetNamedBindingElements(namedImport), importSpecifier => importSpecifier.name && importSpecifier.propertyName && importSpecifier.name.escapedText === importSpecifier.propertyName.escapedText ? factory.updateImportSpecifier(importSpecifier, importSpecifier.isTypeOnly, /*propertyName*/ + void 0, importSpecifier.name) : importSpecifier)); } function tryGetNamedBindingElements(namedImport) { var _a; @@ -165718,10 +149940,11 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return ignoreCase ? compareStringsCaseInsensitiveEslintCompatible : compareStringsCaseSensitive; } function getOrganizeImportsUnicodeStringComparer(ignoreCase, preferences) { + var _preferences$organize, _preferences$organize2, _preferences$organize3; const resolvedLocale = getOrganizeImportsLocale(preferences); - const caseFirst = preferences.organizeImportsCaseFirst ?? false; - const numeric = preferences.organizeImportsNumericCollation ?? false; - const accents = preferences.organizeImportsAccentCollation ?? true; + const caseFirst = (_preferences$organize = preferences.organizeImportsCaseFirst) !== null && _preferences$organize !== void 0 ? _preferences$organize : false; + const numeric = (_preferences$organize2 = preferences.organizeImportsNumericCollation) !== null && _preferences$organize2 !== void 0 ? _preferences$organize2 : false; + const accents = (_preferences$organize3 = preferences.organizeImportsAccentCollation) !== null && _preferences$organize3 !== void 0 ? _preferences$organize3 : true; const sensitivity = ignoreCase ? accents ? "accent" : "base" : accents ? "variant" : "case"; const collator = new Intl.Collator(resolvedLocale, { usage: "sort", @@ -165733,20 +149956,20 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } 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; } function getOrganizeImportsComparer(preferences, ignoreCase) { - const collation = preferences.organizeImportsCollation ?? "ordinal"; + var _preferences$organize4; + const collation = (_preferences$organize4 = preferences.organizeImportsCollation) !== null && _preferences$organize4 !== void 0 ? _preferences$organize4 : "ordinal"; return collation === "unicode" ? getOrganizeImportsUnicodeStringComparer(ignoreCase, preferences) : getOrganizeImportsOrdinalStringComparer(ignoreCase); } function getOrganizeImportsComparerWithDetection(preferences, detectIgnoreCase) { - const ignoreCase = typeof preferences.organizeImportsIgnoreCase === "boolean" ? preferences.organizeImportsIgnoreCase : (detectIgnoreCase == null ? void 0 : detectIgnoreCase()) ?? false; + var _ref48; + const ignoreCase = typeof preferences.organizeImportsIgnoreCase === "boolean" ? preferences.organizeImportsIgnoreCase : (_ref48 = detectIgnoreCase == null ? void 0 : detectIgnoreCase()) !== null && _ref48 !== void 0 ? _ref48 : false; return getOrganizeImportsComparer(preferences, ignoreCase); } function getTopLevelExportGroups(sourceFile) { @@ -165774,30 +149997,30 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} i++; } } - return flatMap(topLevelExportGroups, (exportGroupDecls) => groupByNewlineContiguous(sourceFile, exportGroupDecls)); + return flatMap(topLevelExportGroups, exportGroupDecls => groupByNewlineContiguous(sourceFile, exportGroupDecls)); } var ImportSpecifierSortingCache, detectImportSpecifierSorting; var init_organizeImports = __esm({ "src/services/organizeImports.ts"() { "use strict"; + init_ts4(); ImportSpecifierSortingCache = class { has([specifiers, preferences]) { - if (this._lastPreferences !== preferences || !this._cache) - return false; + if (this._lastPreferences !== preferences || !this._cache) return false; return this._cache.has(specifiers); } get([specifiers, preferences]) { - if (this._lastPreferences !== preferences || !this._cache) - return void 0; + if (this._lastPreferences !== preferences || !this._cache) return void 0; return this._cache.get(specifiers); } set([specifiers, preferences], value) { + var _this$_cache; if (this._lastPreferences !== preferences) { this._lastPreferences = preferences; this._cache = void 0; } - this._cache ?? (this._cache = /* @__PURE__ */ new WeakMap()); + (_this$_cache = this._cache) !== null && _this$_cache !== void 0 ? _this$_cache : this._cache = /* @__PURE__ */new WeakMap(); this._cache.set(specifiers, value); } }; @@ -165805,17 +150028,12 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (!arrayIsSorted(specifiers, (s1, s2) => compareBooleans(s1.isTypeOnly, s2.isTypeOnly))) { return 0 /* None */; } - const collateCaseSensitive = getOrganizeImportsComparer( - preferences, - /*ignoreCase*/ - false - ); - const collateCaseInsensitive = getOrganizeImportsComparer( - preferences, - /*ignoreCase*/ - true - ); - return detectSortCaseSensitivity(specifiers, (specifier) => specifier.name.text, collateCaseSensitive, collateCaseInsensitive); + + const collateCaseSensitive = getOrganizeImportsComparer(preferences, /*ignoreCase*/ + false); + const collateCaseInsensitive = getOrganizeImportsComparer(preferences, /*ignoreCase*/ + true); + return detectSortCaseSensitivity(specifiers, specifier => specifier.name.text, collateCaseSensitive, collateCaseInsensitive); }, new ImportSpecifierSortingCache()); } }); @@ -165839,6 +150057,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} var init_ts_OrganizeImports = __esm({ "src/services/_namespaces/ts.OrganizeImports.ts"() { "use strict"; + init_organizeImports(); } }); @@ -165860,8 +150079,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} visitNode3(statements[current]); current++; } - if (current === n) - break; + if (current === n) break; const firstImport = current; while (current < n && isAnyImportSyntax(statements[current])) { visitNode3(statements[current]); @@ -165872,10 +150090,10 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} out.push(createOutliningSpanFromBounds(findChildOfKind(statements[firstImport], 102 /* ImportKeyword */, sourceFile).getStart(sourceFile), statements[lastImport].getEnd(), "imports" /* Imports */)); } } + 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); @@ -165890,8 +150108,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} 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++; @@ -165923,14 +150140,8 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } if (!result[1]) { const span = createTextSpanFromBounds(sourceFile.text.indexOf("//", currentLineStart), lineEnd); - regions.push(createOutliningSpan( - span, - "region" /* Region */, - span, - /*autoCollapse*/ - false, - result[2] || "#region" - )); + regions.push(createOutliningSpan(span, "region" /* Region */, span, /*autoCollapse*/ + false, result[2] || "#region")); } else { const region = regions.pop(); if (region) { @@ -165951,13 +150162,16 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } 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; const sourceText = sourceFile.getFullText(); - for (const { kind, pos: pos2, end } of comments) { + for (const { + kind, + pos: pos2, + end + } of comments) { cancellationToken.throwIfCancellationRequested(); switch (kind) { case 2 /* SingleLineCommentTrivia */: @@ -165989,9 +150203,9 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } } } + 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) { @@ -166019,12 +150233,12 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} 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 */); } + case 268 /* ModuleBlock */: return spanForNode(n.parent); case 263 /* ClassDeclaration */: @@ -166036,14 +150250,10 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} case 206 /* ObjectBindingPattern */: return spanForNode(n); case 189 /* TupleType */: - return spanForNode( - n, - /*autoCollapse*/ - false, - /*useFullStart*/ - !isTupleTypeNode(n.parent), - 23 /* OpenBracketToken */ - ); + return spanForNode(n, /*autoCollapse*/ + false, /*useFullStart*/ + !isTupleTypeNode(n.parent), 23 /* OpenBracketToken */); + case 296 /* CaseClause */: case 297 /* DefaultClause */: return spanForNodeArray(n.statements); @@ -166062,14 +150272,10 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} case 15 /* NoSubstitutionTemplateLiteral */: return spanForTemplateLiteral(n); case 207 /* ArrayBindingPattern */: - return spanForNode( - n, - /*autoCollapse*/ - false, - /*useFullStart*/ - !isBindingElement(n.parent), - 23 /* OpenBracketToken */ - ); + return spanForNode(n, /*autoCollapse*/ + false, /*useFullStart*/ + !isBindingElement(n.parent), 23 /* OpenBracketToken */); + case 219 /* ArrowFunction */: return spanForArrowFunction(n); case 213 /* CallExpression */: @@ -166090,16 +150296,9 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (!openToken || !closeToken || positionsAreOnSameLine(openToken.pos, closeToken.pos, sourceFile)) { return void 0; } - return spanBetweenTokens( - openToken, - closeToken, - node, - sourceFile, - /*autoCollapse*/ - false, - /*useFullStart*/ - false - ); + return spanBetweenTokens(openToken, closeToken, node, sourceFile, /*autoCollapse*/ + false, /*useFullStart*/ + false); } function spanForCallExpression(node) { if (!node.arguments.length) { @@ -166110,16 +150309,9 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (!openToken || !closeToken || positionsAreOnSameLine(openToken.pos, closeToken.pos, sourceFile)) { return void 0; } - return spanBetweenTokens( - openToken, - closeToken, - node, - sourceFile, - /*autoCollapse*/ - false, - /*useFullStart*/ - true - ); + return spanBetweenTokens(openToken, closeToken, node, sourceFile, /*autoCollapse*/ + false, /*useFullStart*/ + true); } function spanForArrowFunction(node) { if (isBlock(node.body) || isParenthesizedExpression(node.body) || positionsAreOnSameLine(node.body.getFullStart(), node.body.getEnd(), sourceFile)) { @@ -166132,26 +150324,14 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} const textSpan = createTextSpanFromBounds(node.openingElement.getStart(sourceFile), node.closingElement.getEnd()); const tagName = node.openingElement.tagName.getText(sourceFile); const bannerText = "<" + tagName + ">..."; - return createOutliningSpan( - textSpan, - "code" /* Code */, - textSpan, - /*autoCollapse*/ - false, - bannerText - ); + return createOutliningSpan(textSpan, "code" /* Code */, textSpan, /*autoCollapse*/ + false, bannerText); } function spanForJSXFragment(node) { const textSpan = createTextSpanFromBounds(node.openingFragment.getStart(sourceFile), node.closingFragment.getEnd()); const bannerText = "<>..."; - return createOutliningSpan( - textSpan, - "code" /* Code */, - textSpan, - /*autoCollapse*/ - false, - bannerText - ); + return createOutliningSpan(textSpan, "code" /* Code */, textSpan, /*autoCollapse*/ + false, bannerText); } function spanForJSXAttributes(node) { if (node.properties.length === 0) { @@ -166159,21 +150339,18 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } return createOutliningSpanFromBounds(node.getStart(sourceFile), node.getEnd(), "code" /* Code */); } + function spanForTemplateLiteral(node) { if (node.kind === 15 /* NoSubstitutionTemplateLiteral */ && node.text.length === 0) { return void 0; } return createOutliningSpanFromBounds(node.getStart(sourceFile), node.getEnd(), "code" /* Code */); } + function spanForObjectOrArrayLiteral(node, open = 19 /* OpenBraceToken */) { - return spanForNode( - node, - /*autoCollapse*/ - false, - /*useFullStart*/ - !isArrayLiteralExpression(node.parent) && !isCallExpression(node.parent), - open - ); + return spanForNode(node, /*autoCollapse*/ + false, /*useFullStart*/ + !isArrayLiteralExpression(node.parent) && !isCallExpression(node.parent), open); } function spanForNode(hintSpanNode, autoCollapse = false, useFullStart = true, open = 19 /* OpenBraceToken */, close = open === 19 /* OpenBraceToken */ ? 20 /* CloseBraceToken */ : 24 /* CloseBracketToken */) { const openToken = findChildOfKind(n, open, sourceFile); @@ -166184,8 +150361,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} 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)); } @@ -166193,21 +150369,22 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} function functionSpan(node, body, sourceFile) { const openToken = tryGetFunctionOpenToken(node, body, sourceFile); const closeToken = findChildOfKind(body, 20 /* CloseBraceToken */, sourceFile); - return openToken && closeToken && spanBetweenTokens( - openToken, - closeToken, - node, - sourceFile, - /*autoCollapse*/ - node.kind !== 219 /* ArrowFunction */ - ); + return openToken && closeToken && spanBetweenTokens(openToken, closeToken, node, sourceFile, /*autoCollapse*/ + node.kind !== 219 /* ArrowFunction */); } + function spanBetweenTokens(openToken, closeToken, hintSpanNode, sourceFile, autoCollapse = false, useFullStart = true) { const textSpan = createTextSpanFromBounds(useFullStart ? openToken.getFullStart() : openToken.getStart(sourceFile), closeToken.getEnd()); return createOutliningSpan(textSpan, "code" /* Code */, createTextSpanFromNode(hintSpanNode, sourceFile), autoCollapse); } function createOutliningSpan(textSpan, kind, hintSpan = textSpan, autoCollapse = false, bannerText = "...") { - return { textSpan, kind, hintSpan, bannerText, autoCollapse }; + return { + textSpan, + kind, + hintSpan, + bannerText, + autoCollapse + }; } function tryGetFunctionOpenToken(node, body, sourceFile) { if (isNodeArrayMultiLine(node.parameters, sourceFile)) { @@ -166222,6 +150399,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} var init_outliningElementsCollector = __esm({ "src/services/outliningElementsCollector.ts"() { "use strict"; + init_ts4(); regionDelimiterRegExp = /^#(end)?region(?:\s+(.*))?(?:\r)?$/; } @@ -166235,6 +150413,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} var init_ts_OutliningElementsCollector = __esm({ "src/services/_namespaces/ts.OutliningElementsCollector.ts"() { "use strict"; + init_outliningElementsCollector(); } }); @@ -166255,7 +150434,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (!symbol) { if (isStringLiteralLike(node)) { const type = getContextualTypeFromParentOrAncestorTypeNode(node, typeChecker); - if (type && (type.flags & 128 /* StringLiteral */ || type.flags & 1048576 /* Union */ && every(type.types, (type2) => !!(type2.flags & 128 /* StringLiteral */)))) { + if (type && (type.flags & 128 /* StringLiteral */ || type.flags & 1048576 /* Union */ && every(type.types, type2 => !!(type2.flags & 128 /* StringLiteral */)))) { return getRenameInfoSuccess(node.text, node.text, "string" /* string */, "", node, sourceFile); } } else if (isLabelName(node)) { @@ -166264,10 +150443,11 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } return void 0; } - const { declarations } = symbol; - if (!declarations || declarations.length === 0) - return; - if (declarations.some((declaration) => isDefinedInLibraryFile(program, declaration))) { + const { + declarations + } = symbol; + if (!declarations || declarations.length === 0) return; + if (declarations.some(declaration => isDefinedInLibraryFile(program, declaration))) { return getRenameInfoError(Diagnostics.You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library); } if (isIdentifier(node) && node.escapedText === "default" && symbol.parent && symbol.parent.flags & 1536 /* Module */) { @@ -166290,20 +150470,23 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} const sourceFile = declaration.getSourceFile(); return program.isSourceFileDefaultLibrary(sourceFile) && fileExtensionIs(sourceFile.fileName, ".d.ts" /* Dts */); } + function wouldRenameInOtherNodeModules(originalFile, symbol, checker, preferences) { if (!preferences.providePrefixAndSuffixTextForRename && symbol.flags & 2097152 /* Alias */) { - const importSpecifier = symbol.declarations && find(symbol.declarations, (decl) => isImportSpecifier(decl)); + const importSpecifier = symbol.declarations && find(symbol.declarations, decl => isImportSpecifier(decl)); if (importSpecifier && !importSpecifier.propertyName) { symbol = checker.getAliasedSymbol(symbol); } } - const { declarations } = symbol; + const { + declarations + } = symbol; if (!declarations) { return void 0; } const originalPackage = getPackagePathComponents(originalFile.path); if (originalPackage === void 0) { - if (some(declarations, (declaration) => isInsideNodeModules(declaration.getSourceFile().path))) { + if (some(declarations, declaration => isInsideNodeModules(declaration.getSourceFile().path))) { return Diagnostics.You_cannot_rename_elements_that_are_defined_in_a_node_modules_folder; } else { return void 0; @@ -166335,8 +150518,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} 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 name = withoutIndex === void 0 ? moduleSourceFile.fileName : withoutIndex; const kind = withoutIndex === void 0 ? "module" /* moduleElement */ : "directory" /* directory */; @@ -166364,7 +150546,10 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} }; } function getRenameInfoError(diagnostic) { - return { canRename: false, localizedErrorMessage: getLocaleSpecificMessage(diagnostic) }; + return { + canRename: false, + localizedErrorMessage: getLocaleSpecificMessage(diagnostic) + }; } function createTriggerSpanForNode(node, sourceFile) { let start = node.getStart(sourceFile); @@ -166392,6 +150577,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} var init_rename = __esm({ "src/services/rename.ts"() { "use strict"; + init_ts4(); } }); @@ -166405,6 +150591,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} var init_ts_Rename = __esm({ "src/services/_namespaces/ts.Rename.ts"() { "use strict"; + init_rename(); } }); @@ -166422,54 +150609,74 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } 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(); if (!candidateInfo) { return isSourceFileJS(sourceFile) ? createJSSignatureHelpItems(argumentInfo, program, cancellationToken) : void 0; } - return typeChecker.runWithCancellationToken(cancellationToken, (typeChecker2) => candidateInfo.kind === 0 /* Candidate */ ? createSignatureHelpItems(candidateInfo.candidates, candidateInfo.resolvedSignature, argumentInfo, sourceFile, typeChecker2) : createTypeHelpItems(candidateInfo.symbol, argumentInfo, sourceFile, typeChecker2)); + return typeChecker.runWithCancellationToken(cancellationToken, typeChecker2 => candidateInfo.kind === 0 /* Candidate */ ? createSignatureHelpItems(candidateInfo.candidates, candidateInfo.resolvedSignature, argumentInfo, sourceFile, typeChecker2) : createTypeHelpItems(candidateInfo.symbol, argumentInfo, sourceFile, typeChecker2)); } - function getCandidateOrTypeInfo({ invocation, argumentCount }, checker, sourceFile, startingToken, onlyUseSyntacticOwners) { + function getCandidateOrTypeInfo({ + invocation, + argumentCount + }, checker, sourceFile, startingToken, onlyUseSyntacticOwners) { switch (invocation.kind) { - case 0 /* Call */: { - if (onlyUseSyntacticOwners && !isSyntacticOwner(startingToken, invocation.node, sourceFile)) { - return void 0; + case 0 /* Call */: + { + if (onlyUseSyntacticOwners && !isSyntacticOwner(startingToken, invocation.node, sourceFile)) { + return void 0; + } + const candidates = []; + const resolvedSignature = checker.getResolvedSignatureForSignatureHelp(invocation.node, candidates, argumentCount); + return candidates.length === 0 ? void 0 : { + kind: 0 /* Candidate */, + candidates, + resolvedSignature + }; } - const candidates = []; - const resolvedSignature = checker.getResolvedSignatureForSignatureHelp(invocation.node, candidates, argumentCount); - return candidates.length === 0 ? void 0 : { kind: 0 /* Candidate */, candidates, resolvedSignature }; - } - case 1 /* TypeArgs */: { - const { called } = invocation; - if (onlyUseSyntacticOwners && !containsPrecedingToken(startingToken, sourceFile, isIdentifier(called) ? called.parent : called)) { - return void 0; + case 1 /* TypeArgs */: + { + const { + called + } = invocation; + if (onlyUseSyntacticOwners && !containsPrecedingToken(startingToken, sourceFile, isIdentifier(called) ? called.parent : called)) { + return void 0; + } + const candidates = getPossibleGenericSignatures(called, argumentCount, checker); + if (candidates.length !== 0) return { + kind: 0 /* Candidate */, + candidates, + resolvedSignature: first(candidates) + }; + const symbol = checker.getSymbolAtLocation(called); + return symbol && { + kind: 1 /* Type */, + symbol + }; } - const candidates = getPossibleGenericSignatures(called, argumentCount, checker); - if (candidates.length !== 0) - return { kind: 0 /* Candidate */, candidates, resolvedSignature: first(candidates) }; - const symbol = checker.getSymbolAtLocation(called); - return symbol && { kind: 1 /* Type */, symbol }; - } case 2 /* Contextual */: - return { kind: 0 /* Candidate */, candidates: [invocation.signature], resolvedSignature: invocation.signature }; + return { + kind: 0 /* Candidate */, + candidates: [invocation.signature], + resolvedSignature: invocation.signature + }; default: return Debug.assertNever(invocation); } } 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 */: return contains(invocationChildren, startingToken); - case 28 /* CommaToken */: { - const containingList = findContainingList(startingToken); - return !!containingList && contains(invocationChildren, containingList); - } + case 28 /* CommaToken */: + { + const containingList = findContainingList(startingToken); + return !!containingList && contains(invocationChildren, containingList); + } case 30 /* LessThanToken */: return containsPrecedingToken(startingToken, sourceFile, node.expression); default: @@ -166477,27 +150684,16 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } } 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(); - return name === void 0 ? void 0 : firstDefined(program.getSourceFiles(), (sourceFile) => firstDefined(sourceFile.getNamedDeclarations().get(name), (declaration) => { + return name === void 0 ? void 0 : firstDefined(program.getSourceFiles(), sourceFile => firstDefined(sourceFile.getNamedDeclarations().get(name), declaration => { const type = declaration.symbol && typeChecker.getTypeOfSymbolAtLocation(declaration.symbol, declaration); const callSignatures = type && type.getCallSignatures(); if (callSignatures && callSignatures.length) { - return typeChecker.runWithCancellationToken( - cancellationToken, - (typeChecker2) => createSignatureHelpItems( - callSignatures, - callSignatures[0], - argumentInfo, - sourceFile, - typeChecker2, - /*useFullPrefix*/ - true - ) - ); + return typeChecker.runWithCancellationToken(cancellationToken, typeChecker2 => createSignatureHelpItems(callSignatures, callSignatures[0], argumentInfo, sourceFile, typeChecker2, /*useFullPrefix*/ + true)); } })); } @@ -166505,13 +150701,8 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} const pos = startingToken.getFullStart(); let currentParent = startingToken.parent; while (currentParent) { - const precedingToken = findPrecedingToken( - pos, - sourceFile, - currentParent, - /*excludeJsdoc*/ - true - ); + const precedingToken = findPrecedingToken(pos, sourceFile, currentParent, /*excludeJsdoc*/ + true); if (precedingToken) { return rangeContainsRange(container, precedingToken); } @@ -166521,50 +150712,75 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } function getArgumentInfoForCompletions(node, position, sourceFile) { const info = getImmediatelyContainingArgumentInfo(node, position, sourceFile); - return !info || info.isTypeParameterList || info.invocation.kind !== 0 /* Call */ ? void 0 : { invocation: info.invocation.node, argumentCount: info.argumentCount, argumentIndex: info.argumentIndex }; + return !info || info.isTypeParameterList || info.invocation.kind !== 0 /* Call */ ? void 0 : { + invocation: info.invocation.node, + argumentCount: info.argumentCount, + argumentIndex: info.argumentIndex + }; } function getArgumentOrParameterListInfo(node, position, sourceFile) { const info = getArgumentOrParameterListAndIndex(node, sourceFile); - if (!info) - return void 0; - const { list, argumentIndex } = info; - const argumentCount = getArgumentCount( + if (!info) return void 0; + const { list, - /*ignoreTrailingComma*/ - isInString(sourceFile, position, node) - ); + argumentIndex + } = info; + const argumentCount = getArgumentCount(list, /*ignoreTrailingComma*/ + isInString(sourceFile, position, node)); if (argumentIndex !== 0) { Debug.assertLessThan(argumentIndex, argumentCount); } const argumentsSpan = getApplicableSpanForArguments(list, sourceFile); - return { list, argumentIndex, argumentCount, argumentsSpan }; + return { + list, + argumentIndex, + argumentCount, + argumentsSpan + }; } function getArgumentOrParameterListAndIndex(node, sourceFile) { if (node.kind === 30 /* LessThanToken */ || node.kind === 21 /* OpenParenToken */) { - return { list: getChildListThatStartsWithOpenerToken(node.parent, node, sourceFile), argumentIndex: 0 }; + return { + list: getChildListThatStartsWithOpenerToken(node.parent, node, sourceFile), + argumentIndex: 0 + }; } else { const list = findContainingList(node); - return list && { list, argumentIndex: getArgumentIndex(list, node) }; + return list && { + list, + argumentIndex: getArgumentIndex(list, node) + }; } } function getImmediatelyContainingArgumentInfo(node, position, sourceFile) { - const { parent: parent2 } = node; + const { + parent: parent2 + } = node; if (isCallOrNewExpression(parent2)) { const invocation = parent2; const info = getArgumentOrParameterListInfo(node, position, sourceFile); - if (!info) - return void 0; - const { list, argumentIndex, argumentCount, argumentsSpan } = info; + 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 }; + return { + isTypeParameterList, + invocation: { + kind: 0 /* Call */, + node: invocation + }, + argumentsSpan, + argumentIndex, + argumentCount + }; } else if (isNoSubstitutionTemplateLiteral(node) && isTaggedTemplateExpression(parent2)) { if (isInsideTemplateLiteral(node, position, sourceFile)) { - return getArgumentListInfoForTemplate( - parent2, - /*argumentIndex*/ - 0, - sourceFile - ); + return getArgumentListInfoForTemplate(parent2, /*argumentIndex*/ + 0, sourceFile); } return void 0; } else if (isTemplateHead(node) && parent2.parent.kind === 215 /* TaggedTemplateExpression */) { @@ -166584,15 +150800,14 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return getArgumentListInfoForTemplate(tagExpression, argumentIndex, sourceFile); } else if (isJsxOpeningLikeElement(parent2)) { const attributeSpanStart = parent2.attributes.pos; - const attributeSpanEnd = skipTrivia( - sourceFile.text, - parent2.attributes.end, - /*stopAfterLineBreak*/ - false - ); + const attributeSpanEnd = skipTrivia(sourceFile.text, parent2.attributes.end, /*stopAfterLineBreak*/ + false); return { isTypeParameterList: false, - invocation: { kind: 0 /* Call */, node: parent2 }, + invocation: { + kind: 0 /* Call */, + node: parent2 + }, argumentsSpan: createTextSpan(attributeSpanStart, attributeSpanEnd - attributeSpanStart), argumentIndex: 0, argumentCount: 1 @@ -166600,10 +150815,22 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } else { const typeArgInfo = getPossibleTypeArgumentsInfo(node, sourceFile); if (typeArgInfo) { - const { called, nTypeArguments } = typeArgInfo; - const invocation = { kind: 1 /* TypeArgs */, called }; + const { + called, + nTypeArguments + } = typeArgInfo; + const invocation = { + kind: 1 /* TypeArgs */, + called + }; const argumentsSpan = createTextSpanFromBounds(called.getStart(sourceFile), node.end); - return { isTypeParameterList: true, invocation, argumentsSpan, argumentIndex: nTypeArguments, argumentCount: nTypeArguments + 1 }; + return { + isTypeParameterList: true, + invocation, + argumentsSpan, + argumentIndex: nTypeArguments, + argumentCount: nTypeArguments + 1 + }; } return void 0; } @@ -166619,21 +150846,33 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } 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; - const { contextualType, argumentIndex, argumentCount, argumentsSpan } = info; + 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; - const invocation = { kind: 2 /* Contextual */, signature, node: startingToken, symbol: chooseBetterSymbol(symbol) }; - return { isTypeParameterList: false, invocation, argumentsSpan, argumentIndex, argumentCount }; + 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 + }; } function getAdjustedNode(node) { switch (node.kind) { @@ -166641,35 +150880,51 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} case 28 /* CommaToken */: return node; default: - return findAncestor(node.parent, (n) => isParameter(n) ? true : isBindingElement(n) || isObjectBindingPattern(n) || isArrayBindingPattern(n) ? false : "quit"); + return findAncestor(node.parent, n => isParameter(n) ? true : isBindingElement(n) || isObjectBindingPattern(n) || isArrayBindingPattern(n) ? false : "quit"); } } function getContextualSignatureLocationInfo(node, sourceFile, position, checker) { - const { parent: parent2 } = node; + const { + parent: parent2 + } = node; switch (parent2.kind) { case 217 /* ParenthesizedExpression */: case 174 /* MethodDeclaration */: case 218 /* FunctionExpression */: case 219 /* ArrowFunction */: const info = getArgumentOrParameterListInfo(node, position, sourceFile); - if (!info) - return void 0; - const { argumentIndex, argumentCount, argumentsSpan } = info; + 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 }; - case 226 /* BinaryExpression */: { - const highestBinary = getHighestBinary(parent2); - const contextualType2 = checker.getContextualType(highestBinary); - const argumentIndex2 = node.kind === 21 /* OpenParenToken */ ? 0 : countBinaryExpressionParameters(parent2) - 1; - const argumentCount2 = countBinaryExpressionParameters(highestBinary); - return contextualType2 && { contextualType: contextualType2, argumentIndex: argumentIndex2, argumentCount: argumentCount2, argumentsSpan: createTextSpanFromNode(parent2) }; - } + return contextualType && { + contextualType, + argumentIndex, + argumentCount, + argumentsSpan + }; + case 226 /* BinaryExpression */: + { + const highestBinary = getHighestBinary(parent2); + const contextualType2 = checker.getContextualType(highestBinary); + const argumentIndex2 = node.kind === 21 /* OpenParenToken */ ? 0 : countBinaryExpressionParameters(parent2) - 1; + const argumentCount2 = countBinaryExpressionParameters(highestBinary); + return contextualType2 && { + contextualType: contextualType2, + argumentIndex: argumentIndex2, + argumentCount: argumentCount2, + argumentsSpan: createTextSpanFromNode(parent2) + }; + } default: return void 0; } } function chooseBetterSymbol(s) { - return s.name === "__type" /* Type */ ? firstDefined(s.declarations, (d) => { + return s.name === "__type" /* Type */ ? firstDefined(s.declarations, d => { var _a; return isFunctionTypeNode(d) ? (_a = tryCast(d.parent, canHaveSymbol)) == null ? void 0 : _a.symbol : void 0; }) || s : s; @@ -166688,7 +150943,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } function getArgumentCount(argumentsList, ignoreTrailingComma) { const listChildren = argumentsList.getChildren(); - let argumentCount = countWhere(listChildren, (arg) => arg.kind !== 28 /* CommaToken */); + let argumentCount = countWhere(listChildren, arg => arg.kind !== 28 /* CommaToken */); if (!ignoreTrailingComma && listChildren.length > 0 && last(listChildren).kind === 28 /* CommaToken */) { argumentCount++; } @@ -166711,7 +150966,10 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } return { isTypeParameterList: false, - invocation: { kind: 0 /* Call */, node: tagExpression }, + invocation: { + kind: 0 /* Call */, + node: tagExpression + }, argumentsSpan: getApplicableSpanForTaggedTemplate(tagExpression, sourceFile), argumentIndex, argumentCount @@ -166719,12 +150977,8 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } function getApplicableSpanForArguments(argumentsList, sourceFile) { const applicableSpanStart = argumentsList.getFullStart(); - const applicableSpanEnd = skipTrivia( - sourceFile.text, - argumentsList.getEnd(), - /*stopAfterLineBreak*/ - false - ); + const applicableSpanEnd = skipTrivia(sourceFile.text, argumentsList.getEnd(), /*stopAfterLineBreak*/ + false); return createTextSpan(applicableSpanStart, applicableSpanEnd - applicableSpanStart); } function getApplicableSpanForTaggedTemplate(taggedTemplate, sourceFile) { @@ -166734,12 +150988,8 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (template.kind === 228 /* TemplateExpression */) { const lastSpan = last(template.templateSpans); if (lastSpan.literal.getFullWidth() === 0) { - applicableSpanEnd = skipTrivia( - sourceFile.text, - applicableSpanEnd, - /*stopAfterLineBreak*/ - false - ); + applicableSpanEnd = skipTrivia(sourceFile.text, applicableSpanEnd, /*stopAfterLineBreak*/ + false); } } return createTextSpan(applicableSpanStart, applicableSpanEnd - applicableSpanStart); @@ -166766,18 +151016,19 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} function getEnclosingDeclarationFromInvocation(invocation) { return invocation.kind === 0 /* Call */ ? invocation.node : invocation.kind === 1 /* TypeArgs */ ? invocation.called : invocation.node; } - function createSignatureHelpItems(candidates, resolvedSignature, { isTypeParameterList, argumentCount, argumentsSpan: applicableSpan, invocation, argumentIndex }, sourceFile, typeChecker, useFullPrefix) { + function createSignatureHelpItems(candidates, resolvedSignature, { + isTypeParameterList, + argumentCount, + argumentsSpan: applicableSpan, + invocation, + argumentIndex + }, sourceFile, typeChecker, useFullPrefix) { var _a; const enclosingDeclaration = getEnclosingDeclarationFromInvocation(invocation); const callTargetSymbol = invocation.kind === 2 /* Contextual */ ? invocation.symbol : typeChecker.getSymbolAtLocation(getExpressionFromInvocation(invocation)) || useFullPrefix && ((_a = resolvedSignature.declaration) == null ? void 0 : _a.symbol); - const callTargetDisplayParts = callTargetSymbol ? symbolToDisplayParts( - typeChecker, - callTargetSymbol, - useFullPrefix ? sourceFile : void 0, - /*meaning*/ - void 0 - ) : emptyArray; - const items = map(candidates, (candidateSignature) => getSignatureHelpItem(candidateSignature, callTargetDisplayParts, isTypeParameterList, typeChecker, enclosingDeclaration, sourceFile)); + const callTargetDisplayParts = callTargetSymbol ? symbolToDisplayParts(typeChecker, callTargetSymbol, useFullPrefix ? sourceFile : void 0, /*meaning*/ + void 0) : emptyArray; + const items = map(candidates, candidateSignature => getSignatureHelpItem(candidateSignature, callTargetDisplayParts, isTypeParameterList, typeChecker, enclosingDeclaration, sourceFile)); if (argumentIndex !== 0) { Debug.assertLessThan(argumentIndex, argumentCount); } @@ -166801,10 +151052,16 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} itemsSeen += item.length; } Debug.assert(selectedItemIndex !== -1); - const help = { items: flatMapToMutable(items, identity), applicableSpan, selectedItemIndex, argumentIndex, argumentCount }; + const help = { + items: flatMapToMutable(items, identity), + applicableSpan, + selectedItemIndex, + argumentIndex, + argumentCount + }; const selected = help.items[selectedItemIndex]; if (selected.isVariadic) { - const firstRest = findIndex(selected.parameters, (p) => !!p.isRest); + const firstRest = findIndex(selected.parameters, p => !!p.isRest); if (-1 < firstRest && firstRest < selected.parameters.length - 1) { help.argumentIndex = selected.parameters.length; } else { @@ -166813,109 +151070,150 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } return help; } - function createTypeHelpItems(symbol, { argumentCount, argumentsSpan: applicableSpan, invocation, argumentIndex }, sourceFile, checker) { + 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 }; + return { + items, + applicableSpan, + selectedItemIndex: 0, + argumentIndex, + argumentCount + }; } function getTypeHelpItem(symbol, typeParameters, checker, enclosingDeclaration, sourceFile) { const typeSymbolDisplay = symbolToDisplayParts(checker, symbol); const printer = createPrinterWithRemoveComments(); - const parameters = typeParameters.map((t) => createSignatureHelpParameterForTypeParameter(t, checker, enclosingDeclaration, sourceFile, printer)); + const parameters = typeParameters.map(t => createSignatureHelpParameterForTypeParameter(t, checker, enclosingDeclaration, sourceFile, printer)); const documentation = symbol.getDocumentationComment(checker); const tags = symbol.getJsDocTags(checker); const prefixDisplayParts = [...typeSymbolDisplay, punctuationPart(30 /* LessThanToken */)]; - return { isVariadic: false, prefixDisplayParts, suffixDisplayParts: [punctuationPart(32 /* GreaterThanToken */)], separatorDisplayParts, parameters, documentation, tags }; + return { + isVariadic: false, + prefixDisplayParts, + suffixDisplayParts: [punctuationPart(32 /* GreaterThanToken */)], + separatorDisplayParts, + parameters, + documentation, + tags + }; } function getSignatureHelpItem(candidateSignature, callTargetDisplayParts, isTypeParameterList, checker, enclosingDeclaration, sourceFile) { const infos = (isTypeParameterList ? itemInfoForTypeParameters : itemInfoForParameters)(candidateSignature, checker, enclosingDeclaration, sourceFile); - return map(infos, ({ isVariadic, parameters, prefix, suffix }) => { + return map(infos, ({ + isVariadic, + parameters, + prefix, + suffix + }) => { const prefixDisplayParts = [...callTargetDisplayParts, ...prefix]; const suffixDisplayParts = [...suffix, ...returnTypeToDisplayParts(candidateSignature, enclosingDeclaration, checker)]; const documentation = candidateSignature.getDocumentationComment(checker); const tags = candidateSignature.getJsDocTags(); - return { isVariadic, prefixDisplayParts, suffixDisplayParts, separatorDisplayParts, parameters, documentation, tags }; + return { + isVariadic, + prefixDisplayParts, + suffixDisplayParts, + separatorDisplayParts, + parameters, + documentation, + tags + }; }); } function returnTypeToDisplayParts(candidateSignature, enclosingDeclaration, checker) { - return mapToDisplayParts((writer) => { + return mapToDisplayParts(writer => { writer.writePunctuation(":"); writer.writeSpace(" "); const predicate = checker.getTypePredicateOfSignature(candidateSignature); if (predicate) { - checker.writeTypePredicate( - predicate, - enclosingDeclaration, - /*flags*/ - void 0, - writer - ); + checker.writeTypePredicate(predicate, enclosingDeclaration, /*flags*/ + void 0, writer); } else { - checker.writeType( - checker.getReturnTypeOfSignature(candidateSignature), - enclosingDeclaration, - /*flags*/ - void 0, - writer - ); + checker.writeType(checker.getReturnTypeOfSignature(candidateSignature), enclosingDeclaration, /*flags*/ + void 0, writer); } }); } function itemInfoForTypeParameters(candidateSignature, checker, enclosingDeclaration, sourceFile) { const typeParameters = (candidateSignature.target || candidateSignature).typeParameters; const printer = createPrinterWithRemoveComments(); - const parameters = (typeParameters || emptyArray).map((t) => createSignatureHelpParameterForTypeParameter(t, checker, enclosingDeclaration, sourceFile, printer)); + const parameters = (typeParameters || emptyArray).map(t => createSignatureHelpParameterForTypeParameter(t, checker, enclosingDeclaration, sourceFile, printer)); const thisParameter = candidateSignature.thisParameter ? [checker.symbolToParameterDeclaration(candidateSignature.thisParameter, enclosingDeclaration, signatureHelpNodeBuilderFlags)] : []; - return checker.getExpandedParameters(candidateSignature).map((paramList) => { - const params = factory.createNodeArray([...thisParameter, ...map(paramList, (param) => checker.symbolToParameterDeclaration(param, enclosingDeclaration, signatureHelpNodeBuilderFlags))]); - const parameterParts = mapToDisplayParts((writer) => { + return checker.getExpandedParameters(candidateSignature).map(paramList => { + const params = factory.createNodeArray([...thisParameter, ...map(paramList, param => checker.symbolToParameterDeclaration(param, enclosingDeclaration, signatureHelpNodeBuilderFlags))]); + const parameterParts = mapToDisplayParts(writer => { printer.writeList(2576 /* CallExpressionArguments */, params, sourceFile, writer); }); - return { isVariadic: false, parameters, prefix: [punctuationPart(30 /* LessThanToken */)], suffix: [punctuationPart(32 /* GreaterThanToken */), ...parameterParts] }; + return { + isVariadic: false, + parameters, + prefix: [punctuationPart(30 /* LessThanToken */)], + suffix: [punctuationPart(32 /* GreaterThanToken */), ...parameterParts] + }; }); } function itemInfoForParameters(candidateSignature, checker, enclosingDeclaration, sourceFile) { const printer = createPrinterWithRemoveComments(); - const typeParameterParts = mapToDisplayParts((writer) => { + const typeParameterParts = mapToDisplayParts(writer => { if (candidateSignature.typeParameters && candidateSignature.typeParameters.length) { - const args = factory.createNodeArray(candidateSignature.typeParameters.map((p) => checker.typeParameterToDeclaration(p, enclosingDeclaration, signatureHelpNodeBuilderFlags))); + const args = factory.createNodeArray(candidateSignature.typeParameters.map(p => checker.typeParameterToDeclaration(p, enclosingDeclaration, signatureHelpNodeBuilderFlags))); printer.writeList(53776 /* TypeParameters */, args, sourceFile, writer); } }); const lists = checker.getExpandedParameters(candidateSignature); - const isVariadic = !checker.hasEffectiveRestParameter(candidateSignature) ? (_) => false : lists.length === 1 ? (_) => true : (pList) => { + const isVariadic = !checker.hasEffectiveRestParameter(candidateSignature) ? _ => false : lists.length === 1 ? _ => true : pList => { var _a; return !!(pList.length && ((_a = tryCast(pList[pList.length - 1], isTransientSymbol)) == null ? void 0 : _a.links.checkFlags) & 32768 /* RestParameter */); }; - return lists.map((parameterList) => ({ + + return lists.map(parameterList => ({ isVariadic: isVariadic(parameterList), - parameters: parameterList.map((p) => createSignatureHelpParameterForParameter(p, checker, enclosingDeclaration, sourceFile, printer)), + parameters: parameterList.map(p => createSignatureHelpParameterForParameter(p, checker, enclosingDeclaration, sourceFile, printer)), prefix: [...typeParameterParts, punctuationPart(21 /* OpenParenToken */)], suffix: [punctuationPart(22 /* CloseParenToken */)] })); } + function createSignatureHelpParameterForParameter(parameter, checker, enclosingDeclaration, sourceFile, printer) { - const displayParts = mapToDisplayParts((writer) => { + const displayParts = mapToDisplayParts(writer => { const param = checker.symbolToParameterDeclaration(parameter, enclosingDeclaration, signatureHelpNodeBuilderFlags); printer.writeNode(4 /* Unspecified */, param, sourceFile, writer); }); const isOptional = checker.isOptionalParameter(parameter.valueDeclaration); const isRest = isTransientSymbol(parameter) && !!(parameter.links.checkFlags & 32768 /* RestParameter */); - return { name: parameter.name, documentation: parameter.getDocumentationComment(checker), displayParts, isOptional, isRest }; + return { + name: parameter.name, + documentation: parameter.getDocumentationComment(checker), + displayParts, + isOptional, + isRest + }; } function createSignatureHelpParameterForTypeParameter(typeParameter, checker, enclosingDeclaration, sourceFile, printer) { - const displayParts = mapToDisplayParts((writer) => { + const displayParts = mapToDisplayParts(writer => { const param = checker.typeParameterToDeclaration(typeParameter, enclosingDeclaration, signatureHelpNodeBuilderFlags); printer.writeNode(4 /* Unspecified */, param, sourceFile, writer); }); - return { name: typeParameter.symbol.name, documentation: typeParameter.symbol.getDocumentationComment(checker), displayParts, isOptional: false, isRest: false }; + return { + name: typeParameter.symbol.name, + documentation: typeParameter.symbol.getDocumentationComment(checker), + displayParts, + isOptional: false, + isRest: false + }; } var signatureHelpNodeBuilderFlags, separatorDisplayParts; var init_signatureHelp = __esm({ "src/services/signatureHelp.ts"() { "use strict"; + init_ts4(); signatureHelpNodeBuilderFlags = 8192 /* OmitParameterModifiers */ | 70221824 /* IgnoreErrors */ | 16384 /* UseAliasDefinedOutsideCurrentScope */; separatorDisplayParts = [punctuationPart(28 /* CommaToken */), spacePart()]; @@ -166931,6 +151229,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} var init_ts_SignatureHelp = __esm({ "src/services/_namespaces/ts.SignatureHelp.ts"() { "use strict"; + init_signatureHelp(); } }); @@ -166942,72 +151241,73 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} textSpan: createTextSpanFromBounds(sourceFile.getFullStart(), sourceFile.getEnd()) }; let parentNode = sourceFile; - outer: - while (true) { - const children = getSelectionChildren(parentNode); - if (!children.length) - break; - for (let i = 0; i < children.length; i++) { - const prevNode = children[i - 1]; - const node = children[i]; - const nextNode = children[i + 1]; - if (getTokenPosOfNode( - node, - sourceFile, - /*includeJsDoc*/ - true - ) > pos) { - break outer; + outer: while (true) { + const children = getSelectionChildren(parentNode); + if (!children.length) break; + for (let i = 0; i < children.length; i++) { + const prevNode = children[i - 1]; + const node = children[i]; + const nextNode = children[i + 1]; + if (getTokenPosOfNode(node, sourceFile, /*includeJsDoc*/ + true) > pos) { + break outer; + } + const comment = singleOrUndefined(getTrailingCommentRanges(sourceFile.text, node.end)); + if (comment && comment.kind === 2 /* SingleLineCommentTrivia */) { + pushSelectionCommentRange(comment.pos, comment.end); + } + if (positionShouldSnapToNode(sourceFile, pos, node)) { + if (isFunctionBody(node) && isFunctionLikeDeclaration(parentNode) && !positionsAreOnSameLine(node.getStart(sourceFile), node.getEnd(), sourceFile)) { + pushSelectionRange(node.getStart(sourceFile), node.getEnd()); } - const comment = singleOrUndefined(getTrailingCommentRanges(sourceFile.text, node.end)); - if (comment && comment.kind === 2 /* SingleLineCommentTrivia */) { - pushSelectionCommentRange(comment.pos, comment.end); - } - if (positionShouldSnapToNode(sourceFile, pos, node)) { - if (isFunctionBody(node) && isFunctionLikeDeclaration(parentNode) && !positionsAreOnSameLine(node.getStart(sourceFile), node.getEnd(), sourceFile)) { - pushSelectionRange(node.getStart(sourceFile), node.getEnd()); - } - if (isBlock(node) || isTemplateSpan(node) || isTemplateHead(node) || isTemplateTail(node) || prevNode && isTemplateHead(prevNode) || isVariableDeclarationList(node) && isVariableStatement(parentNode) || isSyntaxList(node) && isVariableDeclarationList(parentNode) || isVariableDeclaration(node) && isSyntaxList(parentNode) && children.length === 1 || isJSDocTypeExpression(node) || isJSDocSignature(node) || isJSDocTypeLiteral(node)) { - parentNode = node; - break; - } - if (isTemplateSpan(parentNode) && nextNode && isTemplateMiddleOrTemplateTail(nextNode)) { - const start2 = node.getFullStart() - "${".length; - const end2 = nextNode.getStart() + "}".length; - pushSelectionRange(start2, end2); - } - const isBetweenMultiLineBookends = isSyntaxList(node) && isListOpener(prevNode) && isListCloser(nextNode) && !positionsAreOnSameLine(prevNode.getStart(), nextNode.getStart(), sourceFile); - let start = isBetweenMultiLineBookends ? prevNode.getEnd() : node.getStart(); - const end = isBetweenMultiLineBookends ? nextNode.getStart() : getEndPos(sourceFile, node); - if (hasJSDocNodes(node) && ((_a = node.jsDoc) == null ? void 0 : _a.length)) { - pushSelectionRange(first(node.jsDoc).getStart(), end); - } - if (isSyntaxList(node)) { - const firstChild = node.getChildren()[0]; - if (firstChild && hasJSDocNodes(firstChild) && ((_b = firstChild.jsDoc) == null ? void 0 : _b.length) && firstChild.getStart() !== node.pos) { - start = Math.min(start, first(firstChild.jsDoc).getStart()); - } - } - pushSelectionRange(start, end); - if (isStringLiteral(node) || isTemplateLiteral(node)) { - pushSelectionRange(start + 1, end - 1); - } + if (isBlock(node) || isTemplateSpan(node) || isTemplateHead(node) || isTemplateTail(node) || prevNode && isTemplateHead(prevNode) || isVariableDeclarationList(node) && isVariableStatement(parentNode) || isSyntaxList(node) && isVariableDeclarationList(parentNode) || isVariableDeclaration(node) && isSyntaxList(parentNode) && children.length === 1 || isJSDocTypeExpression(node) || isJSDocSignature(node) || isJSDocTypeLiteral(node)) { parentNode = node; break; } - if (i === children.length - 1) { - break outer; + if (isTemplateSpan(parentNode) && nextNode && isTemplateMiddleOrTemplateTail(nextNode)) { + const start2 = node.getFullStart() - "${".length; + const end2 = nextNode.getStart() + "}".length; + pushSelectionRange(start2, end2); } + const isBetweenMultiLineBookends = isSyntaxList(node) && isListOpener(prevNode) && isListCloser(nextNode) && !positionsAreOnSameLine(prevNode.getStart(), nextNode.getStart(), sourceFile); + let start = isBetweenMultiLineBookends ? prevNode.getEnd() : node.getStart(); + const end = isBetweenMultiLineBookends ? nextNode.getStart() : getEndPos(sourceFile, node); + if (hasJSDocNodes(node) && ((_a = node.jsDoc) == null ? void 0 : _a.length)) { + pushSelectionRange(first(node.jsDoc).getStart(), end); + } + if (isSyntaxList(node)) { + const firstChild = node.getChildren()[0]; + if (firstChild && hasJSDocNodes(firstChild) && ((_b = firstChild.jsDoc) == null ? void 0 : _b.length) && firstChild.getStart() !== node.pos) { + start = Math.min(start, first(firstChild.jsDoc).getStart()); + } + } + pushSelectionRange(start, end); + if (isStringLiteral(node) || isTemplateLiteral(node)) { + pushSelectionRange(start + 1, end - 1); + } + parentNode = node; + break; + } + if (i === children.length - 1) { + break outer; } } + } return selectionRange; function pushSelectionRange(start, end) { if (start !== end) { const textSpan = createTextSpanFromBounds(start, end); - if (!selectionRange || // Skip ranges that are identical to the parent - !textSpansEqual(textSpan, selectionRange.textSpan) && // Skip ranges that don't contain the original position + if (!selectionRange || + // Skip ranges that are identical to the parent + !textSpansEqual(textSpan, selectionRange.textSpan) && + // Skip ranges that don't contain the original position textSpanIntersectsWithPosition(textSpan, pos)) { - selectionRange = { textSpan, ...selectionRange && { parent: selectionRange } }; + selectionRange = { + textSpan, + ...(selectionRange && { + parent: selectionRange + }) + }; } } } @@ -167041,30 +151341,39 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} const closeBraceToken = Debug.checkDefined(children.pop()); Debug.assertEqual(openBraceToken.kind, 19 /* OpenBraceToken */); Debug.assertEqual(closeBraceToken.kind, 20 /* CloseBraceToken */); - const groupedWithPlusMinusTokens = groupChildren(children, (child) => child === node.readonlyToken || child.kind === 148 /* ReadonlyKeyword */ || child === node.questionToken || child.kind === 58 /* QuestionToken */); - const groupedWithBrackets = groupChildren(groupedWithPlusMinusTokens, ({ kind }) => kind === 23 /* OpenBracketToken */ || kind === 168 /* TypeParameter */ || kind === 24 /* CloseBracketToken */); - return [ - openBraceToken, - // Pivot on `:` - createSyntaxList2(splitChildren(groupedWithBrackets, ({ kind }) => kind === 59 /* ColonToken */)), - closeBraceToken - ]; + const groupedWithPlusMinusTokens = groupChildren(children, child => child === node.readonlyToken || child.kind === 148 /* ReadonlyKeyword */ || child === node.questionToken || child.kind === 58 /* QuestionToken */); + const groupedWithBrackets = groupChildren(groupedWithPlusMinusTokens, ({ + kind + }) => kind === 23 /* OpenBracketToken */ || kind === 168 /* TypeParameter */ || kind === 24 /* CloseBracketToken */); + return [openBraceToken, + // Pivot on `:` + createSyntaxList2(splitChildren(groupedWithBrackets, ({ + kind + }) => kind === 59 /* ColonToken */)), closeBraceToken]; } if (isPropertySignature(node)) { - const children = groupChildren(node.getChildren(), (child) => child === node.name || contains(node.modifiers, child)); + const children = groupChildren(node.getChildren(), child => child === node.name || contains(node.modifiers, child)); const firstJSDocChild = ((_a = children[0]) == null ? void 0 : _a.kind) === 327 /* JSDoc */ ? children[0] : void 0; const withJSDocSeparated = firstJSDocChild ? children.slice(1) : children; - const splittedChildren = splitChildren(withJSDocSeparated, ({ kind }) => kind === 59 /* ColonToken */); + const splittedChildren = splitChildren(withJSDocSeparated, ({ + kind + }) => kind === 59 /* ColonToken */); return firstJSDocChild ? [firstJSDocChild, createSyntaxList2(splittedChildren)] : splittedChildren; } if (isParameter(node)) { - const groupedDotDotDotAndName = groupChildren(node.getChildren(), (child) => child === node.dotDotDotToken || child === node.name); - const groupedWithQuestionToken = groupChildren(groupedDotDotDotAndName, (child) => child === groupedDotDotDotAndName[0] || child === node.questionToken); - return splitChildren(groupedWithQuestionToken, ({ kind }) => kind === 64 /* EqualsToken */); + const groupedDotDotDotAndName = groupChildren(node.getChildren(), child => child === node.dotDotDotToken || child === node.name); + const groupedWithQuestionToken = groupChildren(groupedDotDotDotAndName, child => child === groupedDotDotDotAndName[0] || child === node.questionToken); + return splitChildren(groupedWithQuestionToken, ({ + kind + }) => kind === 64 /* EqualsToken */); } + if (isBindingElement(node)) { - return splitChildren(node.getChildren(), ({ kind }) => kind === 64 /* EqualsToken */); + return splitChildren(node.getChildren(), ({ + kind + }) => kind === 64 /* EqualsToken */); } + return node.getChildren(); } function groupChildren(children, groupOn) { @@ -167100,11 +151409,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} const lastToken = last(children); const separateLastToken = separateTrailingSemicolon && lastToken.kind === 27 /* SemicolonToken */; const rightChildren = children.slice(splitTokenIndex + 1, separateLastToken ? children.length - 1 : void 0); - const result = compact([ - leftChildren.length ? createSyntaxList2(leftChildren) : void 0, - splitToken, - rightChildren.length ? createSyntaxList2(rightChildren) : void 0 - ]); + const result = compact([leftChildren.length ? createSyntaxList2(leftChildren) : void 0, splitToken, rightChildren.length ? createSyntaxList2(rightChildren) : void 0]); return separateLastToken ? result.concat(lastToken) : result; } function createSyntaxList2(children) { @@ -167115,10 +151420,12 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} const kind = token && token.kind; return kind === 19 /* OpenBraceToken */ || kind === 23 /* OpenBracketToken */ || kind === 21 /* OpenParenToken */ || kind === 286 /* JsxOpeningElement */; } + function isListCloser(token) { const kind = token && token.kind; return kind === 20 /* CloseBraceToken */ || kind === 24 /* CloseBracketToken */ || kind === 22 /* CloseParenToken */ || kind === 287 /* JsxClosingElement */; } + function getEndPos(sourceFile, node) { switch (node.kind) { case 348 /* JSDocParameterTag */: @@ -167135,6 +151442,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} var init_smartSelection = __esm({ "src/services/smartSelection.ts"() { "use strict"; + init_ts4(); isImport2 = or(isImportDeclaration, isImportEqualsDeclaration); } @@ -167148,6 +151456,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} var init_ts_SmartSelectionRange = __esm({ "src/services/_namespaces/ts.SmartSelectionRange.ts"() { "use strict"; + init_smartSelection(); } }); @@ -167162,20 +151471,14 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} 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) { @@ -167183,15 +151486,19 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (roots.length === 1 && first(roots).flags & 8192 /* Method */ && typeChecker.getTypeOfSymbolAtLocation(symbol, location).getNonNullableType().getCallSignatures().length !== 0) { return "method" /* memberFunctionElement */; } + if (typeChecker.isUndefinedSymbol(symbol)) { return "var" /* variableElement */; } + if (typeChecker.isArgumentsSymbol(symbol)) { return "local var" /* localVariableElement */; } + if (location.kind === 110 /* ThisKeyword */ && isExpression(location) || isThisInTypeQuery(location)) { return "parameter" /* parameterElement */; } + const flags = getCombinedLocalAndExportSymbolFlags(symbol); if (flags & 3 /* Variable */) { if (isFirstDeclarationOfSymbolParameter(symbol)) { @@ -167205,45 +151512,46 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } else if (forEach(symbol.declarations, isLet)) { return "let" /* letElement */; } + 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) => { + const unionPropertyKind = forEach(typeChecker.getRootSymbols(symbol), rootSymbol => { const rootSymbolFlags = rootSymbol.getFlags(); if (rootSymbolFlags & (98308 /* PropertyOrAccessor */ | 3 /* Variable */)) { return "property" /* memberVariableElement */; } }); + if (!unionPropertyKind) { const typeOfUnionProperty = typeChecker.getTypeOfSymbolAtLocation(symbol, location); if (typeOfUnionProperty.getCallSignatures().length) { return "method" /* memberFunctionElement */; } + return "property" /* memberVariableElement */; } + return unionPropertyKind; } return "property" /* memberVariableElement */; } + return "" /* unknown */; } + function getNormalizedSymbolModifiers(symbol) { if (symbol.declarations && symbol.declarations.length) { const [declaration, ...declarations] = symbol.declarations; - const excludeFlags = length(declarations) && isDeprecatedDeclaration(declaration) && some(declarations, (d) => !isDeprecatedDeclaration(d)) ? 65536 /* Deprecated */ : 0 /* None */; + const excludeFlags = length(declarations) && isDeprecatedDeclaration(declaration) && some(declarations, d => !isDeprecatedDeclaration(d)) ? 65536 /* Deprecated */ : 0 /* None */; const modifiers = getNodeModifiers(declaration, excludeFlags); if (modifiers) { return modifiers.split(","); @@ -167255,11 +151563,12 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (!symbol) { return "" /* none */; } + const modifiers = new Set(getNormalizedSymbolModifiers(symbol)); if (symbol.flags & 2097152 /* Alias */) { const resolvedSymbol = typeChecker.getAliasedSymbol(symbol); if (resolvedSymbol !== symbol) { - forEach(getNormalizedSymbolModifiers(resolvedSymbol), (modifier) => { + forEach(getNormalizedSymbolModifiers(resolvedSymbol), modifier => { modifiers.add(modifier); }); } @@ -167267,8 +151576,10 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (symbol.flags & 16777216 /* Optional */) { modifiers.add("optional" /* optionalModifier */); } + return modifiers.size > 0 ? arrayFrom(modifiers.values()).join(",") : "" /* none */; } + function getSymbolDisplayPartsDocumentationAndSymbolKindWorker(typeChecker, symbol, sourceFile, enclosingDeclaration, location, type, semanticMeaning, alias) { var _a; const displayParts = []; @@ -167282,11 +151593,17 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} let tagsFromAlias; let hasMultipleSignatures = false; if (location.kind === 110 /* ThisKeyword */ && !isThisExpression) { - return { displayParts: [keywordPart(110 /* ThisKeyword */)], documentation: [], symbolKind: "primitive type" /* primitiveType */, tags: void 0 }; + return { + displayParts: [keywordPart(110 /* ThisKeyword */)], + documentation: [], + symbolKind: "primitive type" /* primitiveType */, + tags: void 0 + }; } if (symbolKind !== "" /* unknown */ || symbolFlags & 32 /* Class */ || symbolFlags & 2097152 /* Alias */) { + var _type; if (symbolKind === "getter" /* memberGetAccessorElement */ || symbolKind === "setter" /* memberSetAccessorElement */) { - const declaration = find(symbol.declarations, (declaration2) => declaration2.name === location); + const declaration = find(symbol.declarations, declaration2 => declaration2.name === location); if (declaration) { switch (declaration.kind) { case 177 /* GetAccessor */: @@ -167305,8 +151622,9 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} symbolKind = "property" /* memberVariableElement */; } } + let signature; - type ?? (type = isThisExpression ? typeChecker.getTypeAtLocation(location) : typeChecker.getTypeOfSymbolAtLocation(symbol, location)); + (_type = type) !== null && _type !== void 0 ? _type : type = isThisExpression ? typeChecker.getTypeAtLocation(location) : typeChecker.getTypeOfSymbolAtLocation(symbol, location); if (location.parent && location.parent.kind === 211 /* PropertyAccessExpression */) { const right = location.parent.name; if (right === location || right && right.getFullWidth() === 0) { @@ -167359,14 +151677,9 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} displayParts.push(punctuationPart(59 /* ColonToken */)); displayParts.push(spacePart()); if (!(getObjectFlags(type) & 16 /* Anonymous */) && type.symbol) { - addRange(displayParts, symbolToDisplayParts( - typeChecker, - type.symbol, - enclosingDeclaration, - /*meaning*/ - void 0, - 4 /* AllowAnyNodeKind */ | 1 /* WriteTypeParametersOrArguments */ - )); + addRange(displayParts, symbolToDisplayParts(typeChecker, type.symbol, enclosingDeclaration, /*meaning*/ + void 0, 4 /* AllowAnyNodeKind */ | 1 /* WriteTypeParametersOrArguments */)); + displayParts.push(lineBreakPart()); } if (useConstructSignatures) { @@ -167385,10 +151698,11 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} hasAddedSymbolInfo = true; hasMultipleSignatures = allSignatures.length > 1; } - } else if (isNameOfFunctionDeclaration(location) && !(symbolFlags & 98304 /* Accessor */) || // name of function declaration + } else if (isNameOfFunctionDeclaration(location) && !(symbolFlags & 98304 /* Accessor */) || + // name of function declaration location.kind === 137 /* ConstructorKeyword */ && location.parent.kind === 176 /* Constructor */) { const functionDeclaration = location.parent; - const locationIsSymbolDeclaration = symbol.declarations && find(symbol.declarations, (declaration) => declaration === (location.kind === 137 /* ConstructorKeyword */ ? functionDeclaration.parent : functionDeclaration)); + const locationIsSymbolDeclaration = symbol.declarations && find(symbol.declarations, declaration => declaration === (location.kind === 137 /* ConstructorKeyword */ ? functionDeclaration.parent : functionDeclaration)); if (locationIsSymbolDeclaration) { const allSignatures = functionDeclaration.kind === 176 /* Constructor */ ? type.getNonNullableType().getConstructSignatures() : type.getNonNullableType().getCallSignatures(); if (!typeChecker.isImplementationOfOverload(functionDeclaration)) { @@ -167400,10 +151714,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} symbolKind = "constructor" /* constructorImplementationElement */; addPrefixForAnyFunctionOrVar(type.symbol, symbolKind); } else { - addPrefixForAnyFunctionOrVar( - functionDeclaration.kind === 179 /* CallSignature */ && !(type.symbol.flags & 2048 /* TypeLiteral */ || type.symbol.flags & 4096 /* ObjectLiteral */) ? type.symbol : symbol, - symbolKind - ); + addPrefixForAnyFunctionOrVar(functionDeclaration.kind === 179 /* CallSignature */ && !(type.symbol.flags & 2048 /* TypeLiteral */ || type.symbol.flags & 4096 /* ObjectLiteral */) ? type.symbol : symbol, symbolKind); } if (signature) { addSignatureDisplayParts(signature, allSignatures); @@ -167420,6 +151731,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } else { displayParts.push(keywordPart(86 /* ClassKeyword */)); } + displayParts.push(spacePart()); addFullSymbolName(symbol); writeTypeParametersOfSymbol(symbol, sourceFile); @@ -167442,9 +151754,10 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} displayParts.push(spacePart()); addRange(displayParts, typeToDisplayParts(typeChecker, location.parent && isConstTypeReference(location.parent) ? typeChecker.getTypeAtLocation(location.parent) : typeChecker.getDeclaredTypeOfSymbol(symbol), enclosingDeclaration, 8388608 /* InTypeAlias */)); } + if (symbolFlags & 384 /* Enum */) { prefixNextMeaning(); - if (some(symbol.declarations, (d) => isEnumDeclaration(d) && isEnumConst(d))) { + if (some(symbol.declarations, d => isEnumDeclaration(d) && isEnumConst(d))) { displayParts.push(keywordPart(87 /* ConstKeyword */)); displayParts.push(spacePart()); } @@ -167473,8 +151786,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} 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)) { @@ -167511,6 +151823,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } } } + if (symbol.flags & 2097152 /* Alias */) { prefixNextMeaning(); if (!hasAddedSymbolInfo || documentation.length === 0 && tags.length === 0) { @@ -167521,16 +151834,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (declarationName && !hasAddedSymbolInfo) { const isExternalModuleDeclaration = isModuleWithStringLiteralName(resolvedNode) && hasSyntacticModifier(resolvedNode, 128 /* Ambient */); const shouldUseAliasName = symbol.name !== "default" && !isExternalModuleDeclaration; - const resolvedInfo = getSymbolDisplayPartsDocumentationAndSymbolKindWorker( - typeChecker, - resolvedSymbol, - getSourceFileOfNode(resolvedNode), - resolvedNode, - declarationName, - type, - semanticMeaning, - shouldUseAliasName ? symbol : resolvedSymbol - ); + const resolvedInfo = getSymbolDisplayPartsDocumentationAndSymbolKindWorker(typeChecker, resolvedSymbol, getSourceFileOfNode(resolvedNode), resolvedNode, declarationName, type, semanticMeaning, shouldUseAliasName ? symbol : resolvedSymbol); displayParts.push(...resolvedInfo.displayParts); displayParts.push(lineBreakPart()); documentationFromAlias = resolvedInfo.documentation; @@ -167560,9 +151864,10 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} displayParts.push(keywordPart(102 /* ImportKeyword */)); } } + displayParts.push(spacePart()); addFullSymbolName(symbol); - forEach(symbol.declarations, (declaration) => { + forEach(symbol.declarations, declaration => { if (declaration.kind === 271 /* ImportEqualsDeclaration */) { const importEqualsDeclaration = declaration; if (isExternalModuleImportEqualsDeclaration(importEqualsDeclaration)) { @@ -167599,7 +151904,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} displayParts.push(punctuationPart(59 /* ColonToken */)); displayParts.push(spacePart()); if (type.symbol && type.symbol.flags & 262144 /* TypeParameter */ && symbolKind !== "index" /* indexSignatureElement */) { - const typeParameterParts = mapToDisplayParts((writer) => { + const typeParameterParts = mapToDisplayParts(writer => { const param = typeChecker.typeParameterToDeclaration(type, enclosingDeclaration, symbolDisplayNodeBuilderFlags); getPrinter().writeNode(4 /* Unspecified */, param, getSourceFileOfNode(getParseTreeNode(enclosingDeclaration)), writer); }); @@ -167631,7 +151936,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} documentation = symbol.getContextualDocumentationComment(enclosingDeclaration, typeChecker); } if (documentation.length === 0 && symbolFlags & 4 /* Property */) { - if (symbol.parent && symbol.declarations && forEach(symbol.parent.declarations, (declaration) => declaration.kind === 312 /* SourceFile */)) { + if (symbol.parent && symbol.declarations && forEach(symbol.parent.declarations, declaration => declaration.kind === 312 /* SourceFile */)) { for (const declaration of symbol.declarations) { if (!declaration.parent || declaration.parent.kind !== 226 /* BinaryExpression */) { continue; @@ -167655,7 +151960,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (isIdentifier(name) && isObjectBindingPattern(parent2)) { const propertyName = getTextOfIdentifierOrLiteral(name); const objectType = typeChecker.getTypeAtLocation(parent2); - documentation = firstDefined(objectType.isUnion() ? objectType.types : [objectType], (t) => { + documentation = firstDefined(objectType.isUnion() ? objectType.types : [objectType], t => { const prop = t.getProperty(propertyName); return prop ? prop.getDocumentationComment(typeChecker) : void 0; }) || emptyArray; @@ -167670,7 +151975,12 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (tags.length === 0 && tagsFromAlias) { tags = tagsFromAlias; } - return { displayParts, documentation, symbolKind, tags: tags.length === 0 ? void 0 : tags }; + return { + displayParts, + documentation, + symbolKind, + tags: tags.length === 0 ? void 0 : tags + }; function getPrinter() { return createPrinterWithRemoveComments(); } @@ -167715,25 +152025,21 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} }); fullSymbolDisplayParts.push(punctuationPart(24 /* CloseBracketToken */)); } else { - fullSymbolDisplayParts = symbolToDisplayParts( - typeChecker, - symbolToDisplay, - enclosingDeclaration2 || sourceFile, - /*meaning*/ - void 0, - 1 /* WriteTypeParametersOrArguments */ | 2 /* UseOnlyExternalAliasing */ | 4 /* AllowAnyNodeKind */ - ); + fullSymbolDisplayParts = symbolToDisplayParts(typeChecker, symbolToDisplay, enclosingDeclaration2 || sourceFile, /*meaning*/ + void 0, 1 /* WriteTypeParametersOrArguments */ | 2 /* UseOnlyExternalAliasing */ | 4 /* AllowAnyNodeKind */); } + addRange(displayParts, fullSymbolDisplayParts); if (symbol.flags & 16777216 /* Optional */) { displayParts.push(punctuationPart(58 /* QuestionToken */)); } } + function addPrefixForAnyFunctionOrVar(symbol2, symbolKind2) { prefixNextMeaning(); if (symbolKind2) { pushSymbolKind(symbolKind2); - if (symbol2 && !some(symbol2.declarations, (d) => isArrowFunction(d) || (isFunctionExpression(d) || isClassExpression(d)) && !d.name)) { + if (symbol2 && !some(symbol2.declarations, d => isArrowFunction(d) || (isFunctionExpression(d) || isClassExpression(d)) && !d.name)) { displayParts.push(spacePart()); addFullSymbolName(symbol2); } @@ -167768,15 +152074,16 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} displayParts.push(textPart(allSignatures.length === 2 ? "overload" : "overloads")); displayParts.push(punctuationPart(22 /* CloseParenToken */)); } + documentation = signature.getDocumentationComment(typeChecker); tags = signature.getJsDocTags(); if (allSignatures.length > 1 && documentation.length === 0 && tags.length === 0) { documentation = allSignatures[0].getDocumentationComment(typeChecker); - tags = allSignatures[0].getJsDocTags().filter((tag) => tag.name !== "deprecated"); + tags = allSignatures[0].getJsDocTags().filter(tag => tag.name !== "deprecated"); } } function writeTypeParametersOfSymbol(symbol2, enclosingDeclaration2) { - const typeParameterParts = mapToDisplayParts((writer) => { + const typeParameterParts = mapToDisplayParts(writer => { const params = typeChecker.symbolToTypeParameterDeclarations(symbol2, enclosingDeclaration2, symbolDisplayNodeBuilderFlags); getPrinter().writeList(53776 /* TypeParameters */, params, getSourceFileOfNode(getParseTreeNode(enclosingDeclaration2)), writer); }); @@ -167784,23 +152091,14 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } } function getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, enclosingDeclaration, location, semanticMeaning = getMeaningFromLocation(location), alias) { - return getSymbolDisplayPartsDocumentationAndSymbolKindWorker( - typeChecker, - symbol, - sourceFile, - enclosingDeclaration, - location, - /*type*/ - void 0, - semanticMeaning, - alias - ); + return getSymbolDisplayPartsDocumentationAndSymbolKindWorker(typeChecker, symbol, sourceFile, enclosingDeclaration, location, /*type*/ + void 0, semanticMeaning, alias); } function isLocalVariableOrFunction(symbol) { if (symbol.parent) { return false; } - return forEach(symbol.declarations, (declaration) => { + return forEach(symbol.declarations, declaration => { if (declaration.kind === 218 /* FunctionExpression */) { return true; } @@ -167819,6 +152117,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} var init_symbolDisplay = __esm({ "src/services/symbolDisplay.ts"() { "use strict"; + init_ts4(); symbolDisplayNodeBuilderFlags = 8192 /* OmitParameterModifiers */ | 70221824 /* IgnoreErrors */ | 16384 /* UseAliasDefinedOutsideCurrentScope */; } @@ -167834,6 +152133,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} var init_ts_SymbolDisplay = __esm({ "src/services/_namespaces/ts.SymbolDisplay.ts"() { "use strict"; + init_symbolDisplay(); } }); @@ -167858,14 +152158,9 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} n.__end = end; } function skipWhitespacesAndLineBreaks(text, start) { - return skipTrivia( - text, - start, - /*stopAfterLineBreak*/ - false, - /*stopAtComments*/ - true - ); + return skipTrivia(text, start, /*stopAfterLineBreak*/ + false, /*stopAtComments*/ + true); } function hasCommentsBeforeLineBreak(text, start) { let i = start; @@ -167877,14 +152172,20 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } return ch === 47 /* slash */; } + return false; } function getAdjustedRange(sourceFile, startNode2, endNode2, options) { - return { pos: getAdjustedStartPosition(sourceFile, startNode2, options), end: getAdjustedEndPosition(sourceFile, endNode2, options) }; + return { + pos: getAdjustedStartPosition(sourceFile, startNode2, options), + end: getAdjustedEndPosition(sourceFile, endNode2, options) + }; } function getAdjustedStartPosition(sourceFile, node, options, hasTrailingComment = false) { var _a, _b; - const { leadingTriviaOption } = options; + const { + leadingTriviaOption + } = options; if (leadingTriviaOption === 0 /* Exclude */) { return node.getStart(sourceFile); } @@ -167912,14 +152213,9 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (hasTrailingComment) { const comment = ((_a = getLeadingCommentRanges(sourceFile.text, fullStart)) == null ? void 0 : _a[0]) || ((_b = getTrailingCommentRanges(sourceFile.text, fullStart)) == null ? void 0 : _b[0]); if (comment) { - return skipTrivia( - sourceFile.text, - comment.end, - /*stopAfterLineBreak*/ - true, - /*stopAtComments*/ - true - ); + return skipTrivia(sourceFile.text, comment.end, /*stopAfterLineBreak*/ + true, /*stopAtComments*/ + true); } } const nextLineStart = fullStart > 0 ? 1 : 0; @@ -167928,8 +152224,12 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return getStartPositionOfLine(getLineOfLocalPosition(sourceFile, adjustedStartPosition), sourceFile); } function getEndPositionOfMultilineTrailingComment(sourceFile, node, options) { - const { end } = node; - const { trailingTriviaOption } = options; + const { + end + } = node; + const { + trailingTriviaOption + } = options; if (trailingTriviaOption === 2 /* Include */) { const comments = getTrailingCommentRanges(sourceFile.text, end); if (comments) { @@ -167940,14 +152240,9 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } const commentEndLine = getLineOfLocalPosition(sourceFile, comment.end); if (commentEndLine > nodeEndLine) { - return skipTrivia( - sourceFile.text, - comment.end, - /*stopAfterLineBreak*/ - true, - /*stopAtComments*/ - true - ); + return skipTrivia(sourceFile.text, comment.end, /*stopAfterLineBreak*/ + true, /*stopAtComments*/ + true); } } } @@ -167956,8 +152251,12 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } function getAdjustedEndPosition(sourceFile, node, options) { var _a; - const { end } = node; - const { trailingTriviaOption } = options; + const { + end + } = node; + const { + trailingTriviaOption + } = options; if (trailingTriviaOption === 0 /* Exclude */) { return end; } @@ -167973,17 +152272,14 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (multilineEndPosition) { return multilineEndPosition; } - const newEnd = skipTrivia( - sourceFile.text, - end, - /*stopAfterLineBreak*/ - true - ); + const newEnd = skipTrivia(sourceFile.text, end, /*stopAfterLineBreak*/ + true); return newEnd !== end && (trailingTriviaOption === 2 /* Include */ || isLineBreak(sourceFile.text.charCodeAt(newEnd - 1))) ? newEnd : end; } function isSeparator(node, candidate) { return !!candidate && !!node.parent && (candidate.kind === 28 /* CommaToken */ || candidate.kind === 27 /* SemicolonToken */ && node.parent.kind === 210 /* ObjectLiteralExpression */); } + function isThisTypeAnnotatable(containingFunction) { return isFunctionExpression(containingFunction) || isFunctionDeclaration(containingFunction); } @@ -168000,45 +152296,28 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return void 0; } switch (oldTag.kind) { - case 348 /* JSDocParameterTag */: { - const oldParam = oldTag; - const newParam = newTag; - return isIdentifier(oldParam.name) && isIdentifier(newParam.name) && oldParam.name.escapedText === newParam.name.escapedText ? factory.createJSDocParameterTag( - /*tagName*/ - void 0, - newParam.name, - /*isBracketed*/ - false, - newParam.typeExpression, - newParam.isNameFirst, - oldParam.comment - ) : void 0; - } + case 348 /* JSDocParameterTag */: + { + const oldParam = oldTag; + const newParam = newTag; + return isIdentifier(oldParam.name) && isIdentifier(newParam.name) && oldParam.name.escapedText === newParam.name.escapedText ? factory.createJSDocParameterTag( /*tagName*/ + void 0, newParam.name, /*isBracketed*/ + false, newParam.typeExpression, newParam.isNameFirst, oldParam.comment) : void 0; + } case 349 /* JSDocReturnTag */: - return factory.createJSDocReturnTag( - /*tagName*/ - void 0, - newTag.typeExpression, - oldTag.comment - ); + return factory.createJSDocReturnTag( /*tagName*/ + void 0, newTag.typeExpression, oldTag.comment); case 351 /* JSDocTypeTag */: - return factory.createJSDocTypeTag( - /*tagName*/ - void 0, - newTag.typeExpression, - oldTag.comment - ); + return factory.createJSDocTypeTag( /*tagName*/ + void 0, newTag.typeExpression, oldTag.comment); } } function startPositionToDeleteNodeInList(sourceFile, node) { - return skipTrivia( - sourceFile.text, - getAdjustedStartPosition(sourceFile, node, { leadingTriviaOption: 1 /* IncludeAll */ }), - /*stopAfterLineBreak*/ - false, - /*stopAtComments*/ - true - ); + return skipTrivia(sourceFile.text, getAdjustedStartPosition(sourceFile, node, { + leadingTriviaOption: 1 /* IncludeAll */ + }), /*stopAfterLineBreak*/ + false, /*stopAtComments*/ + true); } function endPositionToDeleteNodeInList(sourceFile, node, prevNode, nextNode) { const end = startPositionToDeleteNodeInList(sourceFile, nextNode); @@ -168049,14 +152328,9 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (isSeparator(node, token)) { const prevToken = findPrecedingToken(node.getStart(sourceFile), sourceFile); if (isSeparator(prevNode, prevToken)) { - const pos = skipTrivia( - sourceFile.text, - token.getEnd(), - /*stopAfterLineBreak*/ - true, - /*stopAtComments*/ - true - ); + const pos = skipTrivia(sourceFile.text, token.getEnd(), /*stopAfterLineBreak*/ + true, /*stopAtComments*/ + true); if (positionsAreOnSameLine(prevToken.getStart(sourceFile), token.getStart(sourceFile), sourceFile)) { return isLineBreak(sourceFile.text.charCodeAt(pos - 1)) ? pos - 1 : pos; } @@ -168077,7 +152351,10 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } function applyChanges(text, changes) { for (let i = changes.length - 1; i >= 0; i--) { - const { span, newText } = changes[i]; + const { + span, + newText + } = changes[i]; text = `${text.substring(0, span.start)}${newText}${text.substring(textSpanEnd(span))}`; } return text; @@ -168104,32 +152381,32 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} function createWriter(newLine) { let lastNonTriviaPosition = 0; const writer = createTextWriter(newLine); - const onBeforeEmitNode = (node) => { + const onBeforeEmitNode = node => { if (node) { setPos(node, lastNonTriviaPosition); } }; - const onAfterEmitNode = (node) => { + const onAfterEmitNode = node => { if (node) { setEnd(node, lastNonTriviaPosition); } }; - const onBeforeEmitNodeArray = (nodes) => { + const onBeforeEmitNodeArray = nodes => { if (nodes) { setPos(nodes, lastNonTriviaPosition); } }; - const onAfterEmitNodeArray = (nodes) => { + const onAfterEmitNodeArray = nodes => { if (nodes) { setEnd(nodes, lastNonTriviaPosition); } }; - const onBeforeEmitToken = (node) => { + const onBeforeEmitToken = node => { if (node) { setPos(node, lastNonTriviaPosition); } }; - const onAfterEmitToken = (node) => { + const onAfterEmitToken = node => { if (node) { setEnd(node, lastNonTriviaPosition); } @@ -168146,86 +152423,56 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } function write(s) { writer.write(s); - setLastNonTriviaPosition( - s, - /*force*/ - false - ); + setLastNonTriviaPosition(s, /*force*/ + false); } function writeComment(s) { writer.writeComment(s); } function writeKeyword(s) { writer.writeKeyword(s); - setLastNonTriviaPosition( - s, - /*force*/ - false - ); + setLastNonTriviaPosition(s, /*force*/ + false); } function writeOperator(s) { writer.writeOperator(s); - setLastNonTriviaPosition( - s, - /*force*/ - false - ); + setLastNonTriviaPosition(s, /*force*/ + false); } function writePunctuation(s) { writer.writePunctuation(s); - setLastNonTriviaPosition( - s, - /*force*/ - false - ); + setLastNonTriviaPosition(s, /*force*/ + false); } function writeTrailingSemicolon(s) { writer.writeTrailingSemicolon(s); - setLastNonTriviaPosition( - s, - /*force*/ - false - ); + setLastNonTriviaPosition(s, /*force*/ + false); } function writeParameter(s) { writer.writeParameter(s); - setLastNonTriviaPosition( - s, - /*force*/ - false - ); + setLastNonTriviaPosition(s, /*force*/ + false); } function writeProperty(s) { writer.writeProperty(s); - setLastNonTriviaPosition( - s, - /*force*/ - false - ); + setLastNonTriviaPosition(s, /*force*/ + false); } function writeSpace(s) { writer.writeSpace(s); - setLastNonTriviaPosition( - s, - /*force*/ - false - ); + setLastNonTriviaPosition(s, /*force*/ + false); } function writeStringLiteral(s) { writer.writeStringLiteral(s); - setLastNonTriviaPosition( - s, - /*force*/ - false - ); + setLastNonTriviaPosition(s, /*force*/ + false); } function writeSymbol(s, sym) { writer.writeSymbol(s, sym); - setLastNonTriviaPosition( - s, - /*force*/ - false - ); + setLastNonTriviaPosition(s, /*force*/ + false); } function writeLine(force) { writer.writeLine(force); @@ -168241,19 +152488,13 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } function rawWrite(s) { writer.rawWrite(s); - setLastNonTriviaPosition( - s, - /*force*/ - false - ); + setLastNonTriviaPosition(s, /*force*/ + false); } function writeLiteral(s) { writer.writeLiteral(s); - setLastNonTriviaPosition( - s, - /*force*/ - true - ); + setLastNonTriviaPosition(s, /*force*/ + true); } function getTextPos() { return writer.getTextPos(); @@ -168330,36 +152571,40 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} advancePastLineBreak(); } const ranges = getLeadingCommentRanges(text, position); - if (!ranges) - return position; + if (!ranges) return position; let lastComment; let firstNodeLine; for (const range of ranges) { if (range.kind === 3 /* MultiLineCommentTrivia */) { if (isPinnedComment(text, range.pos)) { - lastComment = { range, pinnedOrTripleSlash: true }; + lastComment = { + range, + pinnedOrTripleSlash: true + }; continue; } } else if (isRecognizedTripleSlashComment(text, range.pos, range.end)) { - lastComment = { range, pinnedOrTripleSlash: true }; + lastComment = { + range, + pinnedOrTripleSlash: true + }; 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 }; + lastComment = { + range, + pinnedOrTripleSlash: false + }; } if (lastComment) { position = lastComment.range.end; @@ -168384,10 +152629,15 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} function needSemicolonBetween(a, b) { return (isPropertySignature(a) || isPropertyDeclaration(a)) && isClassOrTypeElement(b) && b.name.kind === 167 /* ComputedPropertyName */ || isStatementButNotDeclaration(a) && isStatementButNotDeclaration(b); } - function deleteNode(changes, sourceFile, node, options = { leadingTriviaOption: 1 /* IncludeAll */ }) { + function deleteNode(changes, sourceFile, node, options = { + leadingTriviaOption: 1 /* IncludeAll */ + }) { const startPosition = getAdjustedStartPosition(sourceFile, node, options); const endPosition = getAdjustedEndPosition(sourceFile, node, options); - changes.deleteRange(sourceFile, { pos: startPosition, end: endPosition }); + changes.deleteRange(sourceFile, { + pos: startPosition, + end: endPosition + }); } function deleteNodeInList(changes, deletedNodesInLists, sourceFile, node) { const containingList = Debug.checkDefined(ts_formatting_exports.SmartIndenter.getContainingList(node, sourceFile)); @@ -168408,15 +152658,16 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} var init_textChanges = __esm({ "src/services/textChanges.ts"() { "use strict"; + init_ts4(); - LeadingTriviaOption = /* @__PURE__ */ ((LeadingTriviaOption2) => { + LeadingTriviaOption = /* @__PURE__ */(LeadingTriviaOption2 => { LeadingTriviaOption2[LeadingTriviaOption2["Exclude"] = 0] = "Exclude"; LeadingTriviaOption2[LeadingTriviaOption2["IncludeAll"] = 1] = "IncludeAll"; LeadingTriviaOption2[LeadingTriviaOption2["JSDoc"] = 2] = "JSDoc"; LeadingTriviaOption2[LeadingTriviaOption2["StartLine"] = 3] = "StartLine"; return LeadingTriviaOption2; })(LeadingTriviaOption || {}); - TrailingTriviaOption = /* @__PURE__ */ ((TrailingTriviaOption2) => { + TrailingTriviaOption = /* @__PURE__ */(TrailingTriviaOption2 => { TrailingTriviaOption2[TrailingTriviaOption2["Exclude"] = 0] = "Exclude"; TrailingTriviaOption2[TrailingTriviaOption2["ExcludeWhitespace"] = 1] = "ExcludeWhitespace"; TrailingTriviaOption2[TrailingTriviaOption2["Include"] = 2] = "Include"; @@ -168426,13 +152677,14 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} leadingTriviaOption: 0 /* Exclude */, trailingTriviaOption: 0 /* Exclude */ }; + ChangeTracker = class _ChangeTracker { /** Public for tests only. Other callers should use `ChangeTracker.with`. */ constructor(newLineCharacter, formatContext) { this.newLineCharacter = newLineCharacter; this.formatContext = formatContext; this.changes = []; - this.classesWithNodesInsertedAtStart = /* @__PURE__ */ new Map(); + this.classesWithNodesInsertedAtStart = /* @__PURE__ */new Map(); // Set implemented as Map this.deletedNodes = []; } @@ -168456,43 +152708,72 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } } deleteRange(sourceFile, range) { - this.changes.push({ kind: 0 /* Remove */, sourceFile, range }); + this.changes.push({ + kind: 0 /* Remove */, + sourceFile, + range + }); } delete(sourceFile, node) { - this.deletedNodes.push({ sourceFile, node }); + this.deletedNodes.push({ + sourceFile, + node + }); } /** Stop! Consider using `delete` instead, which has logic for deleting nodes from delimited lists. */ - deleteNode(sourceFile, node, options = { leadingTriviaOption: 1 /* IncludeAll */ }) { + deleteNode(sourceFile, node, options = { + leadingTriviaOption: 1 /* IncludeAll */ + }) { this.deleteRange(sourceFile, getAdjustedRange(sourceFile, node, node, options)); } - deleteNodes(sourceFile, nodes, options = { leadingTriviaOption: 1 /* IncludeAll */ }, hasTrailingComment) { + deleteNodes(sourceFile, nodes, options = { + leadingTriviaOption: 1 /* IncludeAll */ + }, hasTrailingComment) { for (const node of nodes) { const pos = getAdjustedStartPosition(sourceFile, node, options, hasTrailingComment); const end = getAdjustedEndPosition(sourceFile, node, options); - this.deleteRange(sourceFile, { pos, end }); + this.deleteRange(sourceFile, { + pos, + end + }); hasTrailingComment = !!getEndPositionOfMultilineTrailingComment(sourceFile, node, options); } } deleteModifier(sourceFile, modifier) { - this.deleteRange(sourceFile, { pos: modifier.getStart(sourceFile), end: skipTrivia( - sourceFile.text, - modifier.end, - /*stopAfterLineBreak*/ - true - ) }); + this.deleteRange(sourceFile, { + pos: modifier.getStart(sourceFile), + end: skipTrivia(sourceFile.text, modifier.end, /*stopAfterLineBreak*/ + true) + }); } - deleteNodeRange(sourceFile, startNode2, endNode2, options = { leadingTriviaOption: 1 /* IncludeAll */ }) { + deleteNodeRange(sourceFile, startNode2, endNode2, options = { + leadingTriviaOption: 1 /* IncludeAll */ + }) { const startPosition = getAdjustedStartPosition(sourceFile, startNode2, options); const endPosition = getAdjustedEndPosition(sourceFile, endNode2, options); - this.deleteRange(sourceFile, { pos: startPosition, end: endPosition }); + this.deleteRange(sourceFile, { + pos: startPosition, + end: endPosition + }); } - deleteNodeRangeExcludingEnd(sourceFile, startNode2, afterEndNode, options = { leadingTriviaOption: 1 /* IncludeAll */ }) { + deleteNodeRangeExcludingEnd(sourceFile, startNode2, afterEndNode, options = { + leadingTriviaOption: 1 /* IncludeAll */ + }) { const startPosition = getAdjustedStartPosition(sourceFile, startNode2, options); const endPosition = afterEndNode === void 0 ? sourceFile.text.length : getAdjustedStartPosition(sourceFile, afterEndNode, options); - this.deleteRange(sourceFile, { pos: startPosition, end: endPosition }); + this.deleteRange(sourceFile, { + pos: startPosition, + end: endPosition + }); } replaceRange(sourceFile, range, newNode, options = {}) { - this.changes.push({ kind: 1 /* ReplaceWithSingleNode */, sourceFile, range, options, node: newNode }); + this.changes.push({ + kind: 1 /* ReplaceWithSingleNode */, + sourceFile, + range, + options, + node: newNode + }); } replaceNode(sourceFile, oldNode, newNode, options = useNonAdjustedPositions) { this.replaceRange(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, options), newNode, options); @@ -168501,7 +152782,13 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} this.replaceRange(sourceFile, getAdjustedRange(sourceFile, startNode2, endNode2, options), newNode, options); } replaceRangeWithNodes(sourceFile, range, newNodes, options = {}) { - this.changes.push({ kind: 2 /* ReplaceWithMultipleNodes */, sourceFile, range, options, nodes: newNodes }); + this.changes.push({ + kind: 2 /* ReplaceWithMultipleNodes */, + sourceFile, + range, + options, + nodes: newNodes + }); } replaceNodeWithNodes(sourceFile, oldNode, newNodes, options = useNonAdjustedPositions) { this.replaceRangeWithNodes(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, options), newNodes, options); @@ -168521,7 +152808,9 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } replacePropertyAssignment(sourceFile, oldNode, newNode) { const suffix = this.nextCommaToken(sourceFile, oldNode) ? "" : "," + this.newLineCharacter; - this.replaceNode(sourceFile, oldNode, newNode, { suffix }); + this.replaceNode(sourceFile, oldNode, newNode, { + suffix + }); } insertNodeAt(sourceFile, pos, newNode, options = {}) { this.replaceRange(sourceFile, createRange(pos), newNode, options); @@ -168562,7 +152851,10 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} if (!this.newFileChanges) { this.newFileChanges = createMultiMap(); } - this.newFileChanges.add(fileName, { oldFile, statements }); + this.newFileChanges.add(fileName, { + oldFile, + statements + }); } insertFirstParameter(sourceFile, parameters, newParam) { const p0 = firstOrUndefined(parameters); @@ -168582,7 +152874,9 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} this.insertNodeAt(sourceFile, pos, factory.createToken(modifier), options); } insertModifierBefore(sourceFile, modifier, before) { - return this.insertModifierAt(sourceFile, before.getStart(sourceFile), modifier, { suffix: " " }); + return this.insertModifierAt(sourceFile, before.getStart(sourceFile), modifier, { + suffix: " " + }); } insertCommentBeforeLine(sourceFile, lineNumber, position, commentText) { const lineStartPosition = getStartPositionOfLine(lineNumber, sourceFile); @@ -168599,21 +152893,19 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} for (const jsdoc of node.jsDoc) { this.deleteRange(sourceFile, { pos: getLineStartPositionForPosition(jsdoc.getStart(sourceFile), sourceFile), - end: getAdjustedEndPosition( - sourceFile, - jsdoc, - /*options*/ - {} - ) + end: getAdjustedEndPosition(sourceFile, jsdoc, /*options*/ + {}) }); } } const startPosition = getPrecedingNonSpaceCharacterPosition(sourceFile.text, fnStart - 1); const indent3 = sourceFile.text.slice(startPosition, fnStart); - this.insertNodeAt(sourceFile, fnStart, tag, { suffix: this.newLineCharacter + indent3 }); + this.insertNodeAt(sourceFile, fnStart, tag, { + suffix: this.newLineCharacter + indent3 + }); } createJSDocText(sourceFile, node) { - const comments = flatMap(node.jsDoc, (jsDoc2) => isString(jsDoc2.comment) ? factory.createJSDocText(jsDoc2.comment) : jsDoc2.comment); + const comments = flatMap(node.jsDoc, jsDoc2 => isString(jsDoc2.comment) ? factory.createJSDocText(jsDoc2.comment) : jsDoc2.comment); const jsDoc = singleOrUndefined(node.jsDoc); return jsDoc && positionsAreOnSameLine(jsDoc.pos, jsDoc.end, sourceFile) && length(comments) === 0 ? void 0 : factory.createNodeArray(intersperse(comments, factory.createJSDocText("\n"))); } @@ -168621,22 +152913,24 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} this.insertJsdocCommentBefore(sourceFile, updateJSDocHost(node), factory.createJSDocComment(this.createJSDocText(sourceFile, node), factory.createNodeArray(tags))); } addJSDocTags(sourceFile, parent2, newTags) { - const oldTags = flatMapToMutable(parent2.jsDoc, (j) => j.tags); - const unmergedNewTags = newTags.filter( - (newTag) => !oldTags.some((tag, i) => { - const merged = tryMergeJsdocTags(tag, newTag); - if (merged) - oldTags[i] = merged; - return !!merged; - }) - ); + const oldTags = flatMapToMutable(parent2.jsDoc, j => j.tags); + const unmergedNewTags = newTags.filter(newTag => !oldTags.some((tag, i) => { + const merged = tryMergeJsdocTags(tag, newTag); + if (merged) oldTags[i] = merged; + return !!merged; + })); this.replaceJSDocComment(sourceFile, parent2, [...oldTags, ...unmergedNewTags]); } filterJSDocTags(sourceFile, parent2, predicate) { - this.replaceJSDocComment(sourceFile, parent2, filter(flatMapToMutable(parent2.jsDoc, (j) => j.tags), predicate)); + this.replaceJSDocComment(sourceFile, parent2, filter(flatMapToMutable(parent2.jsDoc, j => j.tags), predicate)); } replaceRangeWithText(sourceFile, range, text) { - this.changes.push({ kind: 3 /* Text */, sourceFile, range, text }); + this.changes.push({ + kind: 3 /* Text */, + sourceFile, + range, + text + }); } insertText(sourceFile, pos, text) { this.replaceRangeWithText(sourceFile, createRange(pos), text); @@ -168647,36 +152941,55 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} 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 { - endNode2 = (node.kind === 260 /* VariableDeclaration */ ? node.exclamationToken : node.questionToken) ?? node.name; + var _ref49; + endNode2 = (_ref49 = node.kind === 260 /* VariableDeclaration */ ? node.exclamationToken : node.questionToken) !== null && _ref49 !== void 0 ? _ref49 : node.name; } - this.insertNodeAt(sourceFile, endNode2.end, type, { prefix: ": " }); + this.insertNodeAt(sourceFile, endNode2.end, type, { + prefix: ": " + }); return true; } tryInsertThisTypeAnnotation(sourceFile, node, type) { const start = findChildOfKind(node, 21 /* OpenParenToken */, sourceFile).getStart(sourceFile) + 1; const suffix = node.parameters.length ? ", " : ""; - this.insertNodeAt(sourceFile, start, type, { prefix: "this: ", suffix }); + this.insertNodeAt(sourceFile, start, type, { + prefix: "this: ", + suffix + }); } insertTypeParameters(sourceFile, node, typeParameters) { const start = (findChildOfKind(node, 21 /* OpenParenToken */, sourceFile) || first(node.parameters)).getStart(sourceFile); - this.insertNodesAt(sourceFile, start, typeParameters, { prefix: "<", suffix: ">", joiner: ", " }); + this.insertNodesAt(sourceFile, start, typeParameters, { + prefix: "<", + suffix: ">", + joiner: ", " + }); } getOptionsForInsertNodeBefore(before, inserted, blankLineBetween) { if (isStatement(before) || isClassElement(before)) { - return { suffix: blankLineBetween ? this.newLineCharacter + this.newLineCharacter : this.newLineCharacter }; + return { + suffix: blankLineBetween ? this.newLineCharacter + this.newLineCharacter : this.newLineCharacter + }; } else if (isVariableDeclaration(before)) { - return { suffix: ", " }; + return { + suffix: ", " + }; } else if (isParameter(before)) { - return isParameter(inserted) ? { suffix: ", " } : {}; + return isParameter(inserted) ? { + suffix: ", " + } : {}; } else if (isStringLiteral(before) && isImportDeclaration(before.parent) || isNamedImports(before)) { - return { suffix: ", " }; + return { + suffix: ", " + }; } else if (isImportSpecifier(before)) { - return { suffix: "," + (blankLineBetween ? this.newLineCharacter : " ") }; + return { + suffix: "," + (blankLineBetween ? this.newLineCharacter : " ") + }; } return Debug.failBadSyntaxKind(before); } @@ -168689,7 +153002,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } } insertNodeAtConstructorStartAfterSuperCall(sourceFile, ctr, newStatement) { - const superCallStatement = find(ctr.body.statements, (stmt) => isExpressionStatement(stmt) && isSuperCall(stmt.expression)); + const superCallStatement = find(ctr.body.statements, stmt => isExpressionStatement(stmt) && isSuperCall(stmt.expression)); if (!superCallStatement || !ctr.body.multiLine) { this.replaceConstructorBody(sourceFile, ctr, [...ctr.body.statements, newStatement]); } else { @@ -168705,11 +153018,8 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } } replaceConstructorBody(sourceFile, ctr, statements) { - this.replaceNode(sourceFile, ctr.body, factory.createBlock( - statements, - /*multiLine*/ - true - )); + this.replaceNode(sourceFile, ctr.body, factory.createBlock(statements, /*multiLine*/ + true)); } insertNodeAtEndOfScope(sourceFile, scope, newNode) { const pos = getAdjustedStartPosition(sourceFile, scope.getLastToken(), {}); @@ -168725,7 +153035,8 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} this.insertNodeAtStartWorker(sourceFile, obj, newElement); } insertNodeAtStartWorker(sourceFile, node, newElement) { - const indentation = this.guessIndentationFromExistingMembers(sourceFile, node) ?? this.computeIndentationForNewMember(sourceFile, node); + var _this$guessIndentatio; + const indentation = (_this$guessIndentatio = this.guessIndentationFromExistingMembers(sourceFile, node)) !== null && _this$guessIndentatio !== void 0 ? _this$guessIndentatio : this.computeIndentationForNewMember(sourceFile, node); this.insertNodeAt(sourceFile, getMembersOrProperties(node).pos, newElement, this.getInsertNodeAtStartInsertOptions(sourceFile, node, indentation)); } /** @@ -168751,13 +153062,17 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} return indentation; } computeIndentationForNewMember(sourceFile, node) { + var _this$formatContext$o; const nodeStart = node.getStart(sourceFile); - return ts_formatting_exports.SmartIndenter.findFirstNonWhitespaceColumn(getLineStartPositionForPosition(nodeStart, sourceFile), nodeStart, sourceFile, this.formatContext.options) + (this.formatContext.options.indentSize ?? 4); + return ts_formatting_exports.SmartIndenter.findFirstNonWhitespaceColumn(getLineStartPositionForPosition(nodeStart, sourceFile), nodeStart, sourceFile, this.formatContext.options) + ((_this$formatContext$o = this.formatContext.options.indentSize) !== null && _this$formatContext$o !== void 0 ? _this$formatContext$o : 4); } getInsertNodeAtStartInsertOptions(sourceFile, node, indentation) { const members = getMembersOrProperties(node); const isEmpty = members.length === 0; - const isFirstInsertion = addToSeen(this.classesWithNodesInsertedAtStart, getNodeId(node), { node, sourceFile }); + const isFirstInsertion = addToSeen(this.classesWithNodesInsertedAtStart, getNodeId(node), { + node, + sourceFile + }); const insertTrailingComma = isObjectLiteralExpression(node) && (!isJsonSourceFile(sourceFile) || !isEmpty); const insertLeadingComma = isObjectLiteralExpression(node) && isJsonSourceFile(sourceFile) && isEmpty && !isFirstInsertion; return { @@ -168775,7 +153090,9 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} this.insertNodeAt(sourceFile, endPosition, newNode, this.getInsertNodeAfterOptions(sourceFile, after)); } insertNodeAtEndOfList(sourceFile, list, newNode) { - this.insertNodeAt(sourceFile, list.end, newNode, { prefix: ", " }); + this.insertNodeAt(sourceFile, list.end, newNode, { + prefix: ", " + }); } insertNodesAfter(sourceFile, after, newNodes) { const endPosition = this.insertNodeAfterWorker(sourceFile, after, first(newNodes)); @@ -168787,6 +153104,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} this.replaceRange(sourceFile, createRange(after.end), factory.createToken(27 /* SemicolonToken */)); } } + const endPosition = getAdjustedEndPosition(sourceFile, after, {}); return endPosition; } @@ -168802,20 +153120,31 @@ ${options.prefix}` : "\n" : options.prefix switch (node.kind) { case 263 /* ClassDeclaration */: case 267 /* ModuleDeclaration */: - return { prefix: this.newLineCharacter, suffix: this.newLineCharacter }; + return { + prefix: this.newLineCharacter, + suffix: this.newLineCharacter + }; case 260 /* VariableDeclaration */: case 11 /* StringLiteral */: case 80 /* Identifier */: - return { prefix: ", " }; + return { + prefix: ", " + }; case 303 /* PropertyAssignment */: - return { suffix: "," + this.newLineCharacter }; + return { + suffix: "," + this.newLineCharacter + }; case 95 /* ExportKeyword */: - return { prefix: " " }; + return { + prefix: " " + }; case 169 /* Parameter */: return {}; default: Debug.assert(isStatement(node) || isClassOrTypeElement(node)); - return { suffix: this.newLineCharacter }; + return { + suffix: this.newLineCharacter + }; } } insertName(sourceFile, node, name) { @@ -168824,19 +153153,29 @@ ${options.prefix}` : "\n" : options.prefix const arrow = findChildOfKind(node, 39 /* EqualsGreaterThanToken */, sourceFile); const lparen = findChildOfKind(node, 21 /* OpenParenToken */, sourceFile); if (lparen) { - this.insertNodesAt(sourceFile, lparen.getStart(sourceFile), [factory.createToken(100 /* FunctionKeyword */), factory.createIdentifier(name)], { joiner: " " }); + this.insertNodesAt(sourceFile, lparen.getStart(sourceFile), [factory.createToken(100 /* FunctionKeyword */), factory.createIdentifier(name)], { + joiner: " " + }); deleteNode(this, sourceFile, arrow); } else { this.insertText(sourceFile, first(node.parameters).getStart(sourceFile), `function ${name}(`); this.replaceRange(sourceFile, arrow, factory.createToken(22 /* CloseParenToken */)); } + if (node.body.kind !== 241 /* Block */) { - this.insertNodesAt(sourceFile, node.body.getStart(sourceFile), [factory.createToken(19 /* OpenBraceToken */), factory.createToken(107 /* ReturnKeyword */)], { joiner: " ", suffix: " " }); - this.insertNodesAt(sourceFile, node.body.end, [factory.createToken(27 /* SemicolonToken */), factory.createToken(20 /* CloseBraceToken */)], { joiner: " " }); + this.insertNodesAt(sourceFile, node.body.getStart(sourceFile), [factory.createToken(19 /* OpenBraceToken */), factory.createToken(107 /* ReturnKeyword */)], { + joiner: " ", + suffix: " " + }); + this.insertNodesAt(sourceFile, node.body.end, [factory.createToken(27 /* SemicolonToken */), factory.createToken(20 /* CloseBraceToken */)], { + joiner: " " + }); } } else { const pos = findChildOfKind(node, node.kind === 218 /* FunctionExpression */ ? 100 /* FunctionKeyword */ : 86 /* ClassKeyword */, sourceFile).end; - this.insertNodeAt(sourceFile, pos, factory.createIdentifier(name), { prefix: " " }); + this.insertNodeAt(sourceFile, pos, factory.createIdentifier(name), { + prefix: " " + }); } } insertExportModifier(sourceFile, node) { @@ -168847,12 +153186,7 @@ ${options.prefix}` : "\n" : options.prefix if (prevSpecifier) { this.insertNodeInListAfter(sourceFile, prevSpecifier, importSpecifier); } else { - this.insertNodeBefore( - sourceFile, - namedImports.elements[0], - importSpecifier, - !positionsAreOnSameLine(namedImports.elements[0].getStart(), namedImports.parent.parent.getStart(), sourceFile) - ); + this.insertNodeBefore(sourceFile, namedImports.elements[0], importSpecifier, !positionsAreOnSameLine(namedImports.elements[0].getStart(), namedImports.parent.parent.getStart(), sourceFile)); } } /** @@ -168876,7 +153210,9 @@ ${options.prefix}` : "\n" : options.prefix const nextNode = containingList[index + 1]; const startPos = skipWhitespacesAndLineBreaks(sourceFile.text, nextNode.getFullStart()); const suffix = `${tokenToString(nextToken.kind)}${sourceFile.text.substring(nextToken.end, startPos)}`; - this.insertNodesAt(sourceFile, startPos, [newNode], { suffix }); + this.insertNodesAt(sourceFile, startPos, [newNode], { + suffix + }); } } else { const afterStart = after.getStart(sourceFile); @@ -168897,20 +153233,20 @@ ${options.prefix}` : "\n" : options.prefix if (multilineList) { this.replaceRange(sourceFile, createRange(end), factory.createToken(separator)); const indentation = ts_formatting_exports.SmartIndenter.findFirstNonWhitespaceColumn(afterStartLinePosition, afterStart, sourceFile, this.formatContext.options); - let insertPos = skipTrivia( - sourceFile.text, - end, - /*stopAfterLineBreak*/ - true, - /*stopAtComments*/ - false - ); + let insertPos = skipTrivia(sourceFile.text, end, /*stopAfterLineBreak*/ + true, /*stopAtComments*/ + false); while (insertPos !== end && isLineBreak(sourceFile.text.charCodeAt(insertPos - 1))) { insertPos--; } - this.replaceRange(sourceFile, createRange(insertPos), newNode, { indentation, prefix: this.newLineCharacter }); + this.replaceRange(sourceFile, createRange(insertPos), newNode, { + indentation, + prefix: this.newLineCharacter + }); } else { - this.replaceRange(sourceFile, createRange(end), newNode, { prefix: `${tokenToString(separator)} ` }); + this.replaceRange(sourceFile, createRange(end), newNode, { + prefix: `${tokenToString(separator)} ` + }); } } } @@ -168918,7 +153254,10 @@ ${options.prefix}` : "\n" : options.prefix this.replaceRange(sourceFile, rangeOfNode(expression), factory.createParenthesizedExpression(expression)); } finishClassesWithNodesInsertedAtStart() { - this.classesWithNodesInsertedAtStart.forEach(({ node, sourceFile }) => { + this.classesWithNodesInsertedAtStart.forEach(({ + node, + sourceFile + }) => { const [openBraceEnd, closeBraceEnd] = getClassOrObjectBraceEnds(node, sourceFile); if (openBraceEnd !== void 0 && closeBraceEnd !== void 0) { const isEmpty = getMembersOrProperties(node).length === 0; @@ -168933,9 +153272,12 @@ ${options.prefix}` : "\n" : options.prefix }); } finishDeleteDeclarations() { - const deletedNodesInLists = /* @__PURE__ */ new Set(); - for (const { sourceFile, node } of this.deletedNodes) { - if (!this.deletedNodes.some((d) => d.sourceFile === sourceFile && rangeContainsRangeExclusive(d.node, node))) { + const deletedNodesInLists = /* @__PURE__ */new Set(); + for (const { + sourceFile, + node + } of this.deletedNodes) { + if (!this.deletedNodes.some(d => d.sourceFile === sourceFile && rangeContainsRangeExclusive(d.node, node))) { if (isArray(node)) { this.deleteRange(sourceFile, rangeOfTypeParameters(sourceFile, node)); } else { @@ -168943,14 +153285,16 @@ ${options.prefix}` : "\n" : options.prefix } } } - deletedNodesInLists.forEach((node) => { + deletedNodesInLists.forEach(node => { const sourceFile = node.getSourceFile(); const list = ts_formatting_exports.SmartIndenter.getContainingList(node, sourceFile); - if (node !== last(list)) - return; - const lastNonDeletedIndex = findLastIndex(list, (n) => !deletedNodesInLists.has(n), list.length - 2); + 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]) }); + this.deleteRange(sourceFile, { + pos: list[lastNonDeletedIndex].end, + end: startPositionToDeleteNodeInList(sourceFile, list[lastNonDeletedIndex + 1]) + }); } }); } @@ -168975,42 +153319,47 @@ ${options.prefix}` : "\n" : options.prefix this.insertStatementsInNewFile(fileName, statements, oldFile); } }; - ((changesToText2) => { + (changesToText2 => { function getTextChangesFromChanges(changes, newLineCharacter, formatContext, validate) { - return mapDefined(group(changes, (c) => c.sourceFile.path), (changesInFile) => { + return mapDefined(group(changes, c => c.sourceFile.path), changesInFile => { const sourceFile = changesInFile[0].sourceFile; const normalized = stableSort(changesInFile, (a, b) => a.range.pos - b.range.pos || a.range.end - b.range.end); for (let i = 0; i < normalized.length - 1; i++) { Debug.assert(normalized[i].range.end <= normalized[i + 1].range.pos, "Changes overlap", () => `${JSON.stringify(normalized[i].range)} and ${JSON.stringify(normalized[i + 1].range)}`); } - const textChanges2 = mapDefined(normalized, (c) => { + const textChanges2 = mapDefined(normalized, c => { + var _getSourceFileOfNode2, _getSourceFileOfNode3; const span = createTextSpanFromRange(c.range); - const targetSourceFile = c.kind === 1 /* ReplaceWithSingleNode */ ? getSourceFileOfNode(getOriginalNode(c.node)) ?? c.sourceFile : c.kind === 2 /* ReplaceWithMultipleNodes */ ? getSourceFileOfNode(getOriginalNode(c.nodes[0])) ?? c.sourceFile : c.sourceFile; + const targetSourceFile = c.kind === 1 /* ReplaceWithSingleNode */ ? (_getSourceFileOfNode2 = getSourceFileOfNode(getOriginalNode(c.node))) !== null && _getSourceFileOfNode2 !== void 0 ? _getSourceFileOfNode2 : c.sourceFile : c.kind === 2 /* ReplaceWithMultipleNodes */ ? (_getSourceFileOfNode3 = getSourceFileOfNode(getOriginalNode(c.nodes[0]))) !== null && _getSourceFileOfNode3 !== void 0 ? _getSourceFileOfNode3 : c.sourceFile : c.sourceFile; const newText = computeNewText(c, targetSourceFile, sourceFile, newLineCharacter, formatContext, validate); if (span.length === newText.length && stringContainsAt(targetSourceFile.text, newText, span.start)) { return void 0; } return createTextChange(span, newText); }); - return textChanges2.length > 0 ? { fileName: sourceFile.fileName, textChanges: textChanges2 } : void 0; + return textChanges2.length > 0 ? { + fileName: sourceFile.fileName, + textChanges: textChanges2 + } : void 0; }); } changesToText2.getTextChangesFromChanges = getTextChangesFromChanges; function newFileChanges(fileName, insertions, newLineCharacter, formatContext) { const text = newFileChangesWorker(getScriptKindFromFileName(fileName), insertions, newLineCharacter, formatContext); - return { fileName, textChanges: [createTextChange(createTextSpan(0, 0), text)], isNewFile: true }; + return { + fileName, + textChanges: [createTextChange(createTextSpan(0, 0), text)], + isNewFile: true + }; } changesToText2.newFileChanges = newFileChanges; function newFileChangesWorker(scriptKind, insertions, newLineCharacter, formatContext) { - const nonFormattedText = flatMap(insertions, (insertion) => insertion.statements.map((s) => s === 4 /* NewLineTrivia */ ? "" : getNonformattedText(s, insertion.oldFile, newLineCharacter).text)).join(newLineCharacter); - const sourceFile = createSourceFile( - "any file name", - nonFormattedText, - { languageVersion: 99 /* ESNext */, jsDocParsingMode: 1 /* ParseNone */ }, - /*setParentNodes*/ - true, - scriptKind - ); + const nonFormattedText = flatMap(insertions, insertion => insertion.statements.map(s => s === 4 /* NewLineTrivia */ ? "" : getNonformattedText(s, insertion.oldFile, newLineCharacter).text)).join(newLineCharacter); + const sourceFile = createSourceFile("any file name", nonFormattedText, { + languageVersion: 99 /* ESNext */, + jsDocParsingMode: 1 /* ParseNone */ + }, /*setParentNodes*/ + true, scriptKind); const changes = ts_formatting_exports.formatDocument(sourceFile, formatContext); return applyChanges(nonFormattedText, changes) + newLineCharacter; } @@ -169023,16 +153372,27 @@ ${options.prefix}` : "\n" : options.prefix if (change.kind === 3 /* Text */) { return change.text; } - const { options = {}, range: { pos } } = change; - const format = (n) => getFormattedTextOfNode(n, targetSourceFile, sourceFile, pos, options, newLineCharacter, formatContext, validate); - const text = change.kind === 2 /* ReplaceWithMultipleNodes */ ? change.nodes.map((n) => removeSuffix(format(n), newLineCharacter)).join(((_a = change.options) == null ? void 0 : _a.joiner) || newLineCharacter) : format(change.node); + const { + options = {}, + range: { + pos + } + } = change; + const format = n => getFormattedTextOfNode(n, targetSourceFile, sourceFile, pos, options, newLineCharacter, formatContext, validate); + const text = change.kind === 2 /* ReplaceWithMultipleNodes */ ? change.nodes.map(n => removeSuffix(format(n), newLineCharacter)).join(((_a = change.options) == null ? void 0 : _a.joiner) || newLineCharacter) : format(change.node); const noIndent = options.indentation !== void 0 || getLineStartPositionForPosition(pos, targetSourceFile) === pos ? text : text.replace(/^\s+/, ""); return (options.prefix || "") + noIndent + (!options.suffix || endsWith(noIndent, options.suffix) ? "" : options.suffix); } - function getFormattedTextOfNode(nodeIn, targetSourceFile, sourceFile, pos, { indentation, prefix, delta }, newLineCharacter, formatContext, validate) { - const { node, text } = getNonformattedText(nodeIn, targetSourceFile, newLineCharacter); - if (validate) - validate(node, text); + function getFormattedTextOfNode(nodeIn, targetSourceFile, sourceFile, pos, { + indentation, + prefix, + delta + }, newLineCharacter, formatContext, validate) { + const { + node, + text + } = getNonformattedText(nodeIn, targetSourceFile, newLineCharacter); + 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) { @@ -169044,7 +153404,10 @@ ${options.prefix}` : "\n" : options.prefix return getLineAndCharacterOfPosition(this, pos2); } }; - const changes = ts_formatting_exports.formatNodeGivenIndentation(node, file, targetSourceFile.languageVariant, initialIndentation, delta, { ...formatContext, options: formatOptions }); + const changes = ts_formatting_exports.formatNodeGivenIndentation(node, file, targetSourceFile.languageVariant, initialIndentation, delta, { + ...formatContext, + options: formatOptions + }); return applyChanges(text, changes); } function getNonformattedText(node, sourceFile, newLineCharacter) { @@ -169056,35 +153419,37 @@ ${options.prefix}` : "\n" : options.prefix preserveSourceNewlines: true, terminateUnterminatedLiterals: true }, writer).writeNode(4 /* Unspecified */, node, sourceFile, writer); - return { text: writer.getText(), node: assignPositionsToNode(node) }; + return { + text: writer.getText(), + node: assignPositionsToNode(node) + }; } changesToText2.getNonformattedText = getNonformattedText; })(changesToText || (changesToText = {})); textChangesTransformationContext = { ...nullTransformationContext, - factory: createNodeFactory( - nullTransformationContext.factory.flags | 1 /* NoParenthesizerRules */, - nullTransformationContext.factory.baseFactory - ) + factory: createNodeFactory(nullTransformationContext.factory.flags | 1 /* NoParenthesizerRules */, nullTransformationContext.factory.baseFactory) }; - ((_deleteDeclaration) => { + (_deleteDeclaration => { function deleteDeclaration2(changes, deletedNodesInLists, sourceFile, node) { switch (node.kind) { - case 169 /* Parameter */: { - const oldFunction = node.parent; - if (isArrowFunction(oldFunction) && oldFunction.parameters.length === 1 && !findChildOfKind(oldFunction, 21 /* OpenParenToken */, sourceFile)) { - changes.replaceNodeWithText(sourceFile, node, "()"); - } else { - deleteNodeInList(changes, deletedNodesInLists, sourceFile, node); + case 169 /* Parameter */: + { + const oldFunction = node.parent; + if (isArrowFunction(oldFunction) && oldFunction.parameters.length === 1 && !findChildOfKind(oldFunction, 21 /* OpenParenToken */, sourceFile)) { + changes.replaceNodeWithText(sourceFile, node, "()"); + } else { + deleteNodeInList(changes, deletedNodesInLists, sourceFile, node); + } + break; } - break; - } case 272 /* ImportDeclaration */: case 271 /* ImportEqualsDeclaration */: const isFirstImport = sourceFile.imports.length && node === first(sourceFile.imports).parent || node === find(sourceFile.statements, isAnyImportSyntax); deleteNode(changes, sourceFile, node, { leadingTriviaOption: isFirstImport ? 0 /* Exclude */ : hasJSDocNodes(node) ? 2 /* JSDoc */ : 3 /* StartLine */ }); + break; case 208 /* BindingElement */: const pattern = node.parent; @@ -169113,14 +153478,20 @@ ${options.prefix}` : "\n" : options.prefix deleteImportBinding(changes, sourceFile, node); break; case 27 /* SemicolonToken */: - deleteNode(changes, sourceFile, node, { trailingTriviaOption: 0 /* Exclude */ }); + deleteNode(changes, sourceFile, node, { + trailingTriviaOption: 0 /* Exclude */ + }); break; case 100 /* FunctionKeyword */: - deleteNode(changes, sourceFile, node, { leadingTriviaOption: 0 /* Exclude */ }); + deleteNode(changes, sourceFile, node, { + leadingTriviaOption: 0 /* Exclude */ + }); break; case 263 /* ClassDeclaration */: case 262 /* FunctionDeclaration */: - deleteNode(changes, sourceFile, node, { leadingTriviaOption: hasJSDocNodes(node) ? 2 /* JSDoc */ : 3 /* StartLine */ }); + deleteNode(changes, sourceFile, node, { + leadingTriviaOption: hasJSDocNodes(node) ? 2 /* JSDoc */ : 3 /* StartLine */ + }); break; default: if (!node.parent) { @@ -169142,15 +153513,13 @@ ${options.prefix}` : "\n" : options.prefix const start = importClause.name.getStart(sourceFile); const nextToken = getTokenAtPosition(sourceFile, importClause.name.end); if (nextToken && nextToken.kind === 28 /* CommaToken */) { - const end = skipTrivia( - sourceFile.text, - nextToken.end, - /*stopAfterLineBreak*/ - false, - /*stopAtComments*/ - true - ); - changes.deleteRange(sourceFile, { pos: start, end }); + const end = skipTrivia(sourceFile.text, nextToken.end, /*stopAfterLineBreak*/ + false, /*stopAtComments*/ + true); + changes.deleteRange(sourceFile, { + pos: start, + end + }); } else { deleteNode(changes, sourceFile, importClause.name); } @@ -169159,14 +153528,19 @@ ${options.prefix}` : "\n" : options.prefix function deleteImportBinding(changes, sourceFile, node) { if (node.parent.name) { const previousToken = Debug.checkDefined(getTokenAtPosition(sourceFile, node.pos - 1)); - changes.deleteRange(sourceFile, { pos: previousToken.getStart(sourceFile), end: node.end }); + changes.deleteRange(sourceFile, { + pos: previousToken.getStart(sourceFile), + end: node.end + }); } else { const importDecl = getAncestor(node, 272 /* ImportDeclaration */); deleteNode(changes, sourceFile, importDecl); } } function deleteVariableDeclaration(changes, deletedNodesInLists, sourceFile, node) { - const { parent: parent2 } = node; + const { + parent: parent2 + } = node; if (parent2.kind === 299 /* CatchClause */) { changes.deleteNodeRange(sourceFile, findChildOfKind(parent2, 21 /* OpenParenToken */, sourceFile), findChildOfKind(parent2, 22 /* CloseParenToken */, sourceFile)); return; @@ -169185,7 +153559,9 @@ ${options.prefix}` : "\n" : options.prefix deleteNode(changes, sourceFile, parent2); break; case 243 /* VariableStatement */: - deleteNode(changes, sourceFile, gp, { leadingTriviaOption: hasJSDocNodes(gp) ? 2 /* JSDoc */ : 3 /* StartLine */ }); + deleteNode(changes, sourceFile, gp, { + leadingTriviaOption: hasJSDocNodes(gp) ? 2 /* JSDoc */ : 3 /* StartLine */ + }); break; default: Debug.assertNever(gp); @@ -169211,6 +153587,7 @@ ${options.prefix}` : "\n" : options.prefix var init_ts_textChanges = __esm({ "src/services/_namespaces/ts.textChanges.ts"() { "use strict"; + init_textChanges(); } }); @@ -169220,8 +153597,9 @@ ${options.prefix}` : "\n" : options.prefix var init_formattingContext = __esm({ "src/services/formatting/formattingContext.ts"() { "use strict"; + init_ts4(); - FormattingRequestKind = /* @__PURE__ */ ((FormattingRequestKind2) => { + FormattingRequestKind = /* @__PURE__ */(FormattingRequestKind2 => { FormattingRequestKind2[FormattingRequestKind2["FormatDocument"] = 0] = "FormatDocument"; FormattingRequestKind2[FormattingRequestKind2["FormatSelection"] = 1] = "FormatSelection"; FormattingRequestKind2[FormattingRequestKind2["FormatOnEnter"] = 2] = "FormatOnEnter"; @@ -169320,8 +153698,14 @@ ${options.prefix}` : "\n" : options.prefix lastTrailingTriviaWasNewLine: () => wasNewLine, skipToEndOf, skipToStartOf, - getTokenFullStart: () => (lastTokenInfo == null ? void 0 : lastTokenInfo.token.pos) ?? scanner2.getTokenStart(), - getStartPos: () => (lastTokenInfo == null ? void 0 : lastTokenInfo.token.pos) ?? scanner2.getTokenStart() + getTokenFullStart: () => { + var _ref50; + return (_ref50 = lastTokenInfo == null ? void 0 : lastTokenInfo.token.pos) !== null && _ref50 !== void 0 ? _ref50 : scanner2.getTokenStart(); + }, + getStartPos: () => { + var _ref51; + return (_ref51 = lastTokenInfo == null ? void 0 : lastTokenInfo.token.pos) !== null && _ref51 !== void 0 ? _ref51 : scanner2.getTokenStart(); + } }); lastTokenInfo = void 0; scanner2.setText(void 0); @@ -169374,23 +153758,28 @@ ${options.prefix}` : "\n" : options.prefix return isKeyword(node.kind) || node.kind === 80 /* Identifier */; } } + return false; } function shouldRescanJsxText(node) { return isJsxText(node) || isJsxElement(node) && (lastTokenInfo == null ? void 0 : lastTokenInfo.token.kind) === 12 /* JsxText */; } + function shouldRescanSlashToken(container) { return container.kind === 14 /* RegularExpressionLiteral */; } + function shouldRescanTemplateToken(container) { return container.kind === 17 /* TemplateMiddle */ || container.kind === 18 /* TemplateTail */; } + function shouldRescanJsxAttributeValue(node) { return node.parent && isJsxAttribute(node.parent) && node.parent.initializer === node; } function startsWithSlashToken(t) { return t === 44 /* SlashToken */ || t === 69 /* SlashEqualsToken */; } + function readTokenInfo(n) { Debug.assert(isOnToken()); const expectedScanAction = shouldRescanGreaterThanToken(n) ? 1 /* RescanGreaterThanToken */ : shouldRescanSlashToken(n) ? 2 /* RescanSlashToken */ : shouldRescanTemplateToken(n) ? 3 /* RescanTemplateToken */ : shouldRescanJsxIdentifier(n) ? 4 /* RescanJsxIdentifier */ : shouldRescanJsxText(n) ? 5 /* RescanJsxText */ : shouldRescanJsxAttributeValue(n) ? 6 /* RescanJsxAttributeValue */ : 0 /* Scan */; @@ -169403,11 +153792,7 @@ ${options.prefix}` : "\n" : options.prefix scanner2.scan(); } let currentToken = getNextToken(n, expectedScanAction); - const token = createTextRangeWithKind( - scanner2.getTokenFullStart(), - scanner2.getTokenEnd(), - currentToken - ); + const token = createTextRangeWithKind(scanner2.getTokenFullStart(), scanner2.getTokenEnd(), currentToken); if (trailingTrivia) { trailingTrivia = void 0; } @@ -169416,11 +153801,7 @@ ${options.prefix}` : "\n" : options.prefix if (!isTrivia(currentToken)) { break; } - const trivia = createTextRangeWithKind( - scanner2.getTokenFullStart(), - scanner2.getTokenEnd(), - currentToken - ); + const trivia = createTextRangeWithKind(scanner2.getTokenFullStart(), scanner2.getTokenEnd(), currentToken); if (!trailingTrivia) { trailingTrivia = []; } @@ -169430,7 +153811,11 @@ ${options.prefix}` : "\n" : options.prefix break; } } - lastTokenInfo = { leadingTrivia, trailingTrivia, token }; + lastTokenInfo = { + leadingTrivia, + trailingTrivia, + token + }; return fixTokenKind(lastTokenInfo, n); } function getNextToken(n, expectedScanAction) { @@ -169456,10 +153841,8 @@ ${options.prefix}` : "\n" : options.prefix case 3 /* RescanTemplateToken */: if (token === 20 /* CloseBraceToken */) { lastScanAction = 3 /* RescanTemplateToken */; - return scanner2.reScanTemplateToken( - /*isTaggedTemplate*/ - false - ); + return scanner2.reScanTemplateToken( /*isTaggedTemplate*/ + false); } break; case 4 /* RescanJsxIdentifier */: @@ -169467,10 +153850,8 @@ ${options.prefix}` : "\n" : options.prefix return scanner2.scanJsxIdentifier(); case 5 /* RescanJsxText */: lastScanAction = 5 /* RescanJsxText */; - return scanner2.reScanJsxToken( - /*allowMultilineJsxText*/ - false - ); + return scanner2.reScanJsxToken( /*allowMultilineJsxText*/ + false); case 6 /* RescanJsxAttributeValue */: lastScanAction = 6 /* RescanJsxAttributeValue */; return scanner2.reScanJsxAttributeValue(); @@ -169485,6 +153866,7 @@ ${options.prefix}` : "\n" : options.prefix Debug.assert(isOnEOF()); return createTextRangeWithKind(scanner2.getTokenFullStart(), scanner2.getTokenEnd(), 1 /* EndOfFileToken */); } + function isOnToken() { const current = lastTokenInfo ? lastTokenInfo.token.kind : scanner2.getToken(); return current !== 1 /* EndOfFileToken */ && !isTrivia(current); @@ -169493,6 +153875,7 @@ ${options.prefix}` : "\n" : options.prefix const current = lastTokenInfo ? lastTokenInfo.token.kind : scanner2.getToken(); return current === 1 /* EndOfFileToken */; } + function fixTokenKind(tokenInfo, container) { if (isToken(container) && tokenInfo.token.kind !== container.kind) { tokenInfo.token.kind = container.kind; @@ -169522,20 +153905,14 @@ ${options.prefix}` : "\n" : options.prefix var init_formattingScanner = __esm({ "src/services/formatting/formattingScanner.ts"() { "use strict"; + init_ts4(); init_ts_formatting(); - standardScanner = createScanner( - 99 /* Latest */, - /*skipTrivia*/ - false, - 0 /* Standard */ - ); - jsxScanner = createScanner( - 99 /* Latest */, - /*skipTrivia*/ - false, - 1 /* JSX */ - ); + standardScanner = createScanner(99 /* Latest */, /*skipTrivia*/ + false, 0 /* Standard */); + + jsxScanner = createScanner(99 /* Latest */, /*skipTrivia*/ + false, 1 /* JSX */); } }); @@ -169544,9 +153921,10 @@ ${options.prefix}` : "\n" : options.prefix var init_rule = __esm({ "src/services/formatting/rule.ts"() { "use strict"; + init_ts4(); anyContext = emptyArray; - RuleAction = /* @__PURE__ */ ((RuleAction2) => { + RuleAction = /* @__PURE__ */(RuleAction2 => { RuleAction2[RuleAction2["None"] = 0] = "None"; RuleAction2[RuleAction2["StopProcessingSpaceActions"] = 1] = "StopProcessingSpaceActions"; RuleAction2[RuleAction2["StopProcessingTokenActions"] = 2] = "StopProcessingTokenActions"; @@ -169560,7 +153938,7 @@ ${options.prefix}` : "\n" : options.prefix RuleAction2[RuleAction2["ModifyTokenAction"] = 96] = "ModifyTokenAction"; return RuleAction2; })(RuleAction || {}); - RuleFlags = /* @__PURE__ */ ((RuleFlags2) => { + RuleFlags = /* @__PURE__ */(RuleFlags2 => { RuleFlags2[RuleFlags2["None"] = 0] = "None"; RuleFlags2[RuleFlags2["CanDeleteNewLines"] = 1] = "CanDeleteNewLines"; return RuleFlags2; @@ -169577,32 +153955,24 @@ ${options.prefix}` : "\n" : options.prefix } } function anyTokenExcept(...tokens) { - return { tokens: allTokens.filter((t) => !tokens.some((t2) => t2 === t)), isSpecific: false }; + return { + tokens: allTokens.filter(t => !tokens.some(t2 => t2 === t)), + isSpecific: false + }; } - const anyToken = { tokens: allTokens, isSpecific: false }; + const anyToken = { + tokens: allTokens, + isSpecific: false + }; const anyTokenIncludingMultilineComments = tokenRangeFrom([...allTokens, 3 /* MultiLineCommentTrivia */]); const anyTokenIncludingEOF = tokenRangeFrom([...allTokens, 1 /* EndOfFileToken */]); const keywords = tokenRangeFromRange(83 /* FirstKeyword */, 165 /* LastKeyword */); const binaryOperators = tokenRangeFromRange(30 /* FirstBinaryOperator */, 79 /* LastBinaryOperator */); - const binaryKeywordOperators = [ - 103 /* InKeyword */, - 104 /* InstanceOfKeyword */, - 165 /* OfKeyword */, - 130 /* AsKeyword */, - 142 /* IsKeyword */, - 152 /* SatisfiesKeyword */ - ]; + const binaryKeywordOperators = [103 /* InKeyword */, 104 /* InstanceOfKeyword */, 165 /* OfKeyword */, 130 /* AsKeyword */, 142 /* IsKeyword */, 152 /* SatisfiesKeyword */]; + const unaryPrefixOperators = [46 /* PlusPlusToken */, 47 /* MinusMinusToken */, 55 /* TildeToken */, 54 /* ExclamationToken */]; - const unaryPrefixExpressions = [ - 9 /* NumericLiteral */, - 10 /* BigIntLiteral */, - 80 /* Identifier */, - 21 /* OpenParenToken */, - 23 /* OpenBracketToken */, - 19 /* OpenBraceToken */, - 110 /* ThisKeyword */, - 105 /* NewKeyword */ - ]; + const unaryPrefixExpressions = [9 /* NumericLiteral */, 10 /* BigIntLiteral */, 80 /* Identifier */, 21 /* OpenParenToken */, 23 /* OpenBracketToken */, 19 /* OpenBraceToken */, 110 /* ThisKeyword */, 105 /* NewKeyword */]; + const unaryPreincrementExpressions = [80 /* Identifier */, 21 /* OpenParenToken */, 110 /* ThisKeyword */, 105 /* NewKeyword */]; const unaryPostincrementExpressions = [80 /* Identifier */, 22 /* CloseParenToken */, 24 /* CloseBracketToken */, 105 /* NewKeyword */]; const unaryPredecrementExpressions = [80 /* Identifier */, 21 /* OpenParenToken */, 110 /* ThisKeyword */, 105 /* NewKeyword */]; @@ -169613,281 +153983,130 @@ ${options.prefix}` : "\n" : options.prefix const typeScriptOpenBraceLeftTokenRange = tokenRangeFrom([80 /* Identifier */, 3 /* MultiLineCommentTrivia */, 86 /* ClassKeyword */, 95 /* ExportKeyword */, 102 /* ImportKeyword */]); const controlOpenBraceLeftTokenRange = tokenRangeFrom([22 /* CloseParenToken */, 3 /* MultiLineCommentTrivia */, 92 /* DoKeyword */, 113 /* TryKeyword */, 98 /* FinallyKeyword */, 93 /* ElseKeyword */]); const highPriorityCommonRules = [ - // Leave comments alone - rule("IgnoreBeforeComment", anyToken, comments, anyContext, 1 /* StopProcessingSpaceActions */), - rule("IgnoreAfterLineComment", 2 /* SingleLineCommentTrivia */, anyToken, anyContext, 1 /* StopProcessingSpaceActions */), - rule("NotSpaceBeforeColon", anyToken, 59 /* ColonToken */, [isNonJsxSameLineTokenContext, isNotBinaryOpContext, isNotTypeAnnotationContext], 16 /* DeleteSpace */), - rule("SpaceAfterColon", 59 /* ColonToken */, anyToken, [isNonJsxSameLineTokenContext, isNotBinaryOpContext, isNextTokenParentNotJsxNamespacedName], 4 /* InsertSpace */), - rule("NoSpaceBeforeQuestionMark", anyToken, 58 /* QuestionToken */, [isNonJsxSameLineTokenContext, isNotBinaryOpContext, isNotTypeAnnotationContext], 16 /* DeleteSpace */), - // insert space after '?' only when it is used in conditional operator - rule("SpaceAfterQuestionMarkInConditionalOperator", 58 /* QuestionToken */, anyToken, [isNonJsxSameLineTokenContext, isConditionalOperatorContext], 4 /* InsertSpace */), - // in other cases there should be no space between '?' and next token - rule("NoSpaceAfterQuestionMark", 58 /* QuestionToken */, anyToken, [isNonJsxSameLineTokenContext, isNonOptionalPropertyContext], 16 /* DeleteSpace */), - rule("NoSpaceBeforeDot", anyToken, [25 /* DotToken */, 29 /* QuestionDotToken */], [isNonJsxSameLineTokenContext, isNotPropertyAccessOnIntegerLiteral], 16 /* DeleteSpace */), - rule("NoSpaceAfterDot", [25 /* DotToken */, 29 /* QuestionDotToken */], anyToken, [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */), - rule("NoSpaceBetweenImportParenInImportType", 102 /* ImportKeyword */, 21 /* OpenParenToken */, [isNonJsxSameLineTokenContext, isImportTypeContext], 16 /* DeleteSpace */), - // Special handling of unary operators. - // Prefix operators generally shouldn't have a space between - // them and their target unary expression. - rule("NoSpaceAfterUnaryPrefixOperator", unaryPrefixOperators, unaryPrefixExpressions, [isNonJsxSameLineTokenContext, isNotBinaryOpContext], 16 /* DeleteSpace */), - rule("NoSpaceAfterUnaryPreincrementOperator", 46 /* PlusPlusToken */, unaryPreincrementExpressions, [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */), - rule("NoSpaceAfterUnaryPredecrementOperator", 47 /* MinusMinusToken */, unaryPredecrementExpressions, [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */), - rule("NoSpaceBeforeUnaryPostincrementOperator", unaryPostincrementExpressions, 46 /* PlusPlusToken */, [isNonJsxSameLineTokenContext, isNotStatementConditionContext], 16 /* DeleteSpace */), - rule("NoSpaceBeforeUnaryPostdecrementOperator", unaryPostdecrementExpressions, 47 /* MinusMinusToken */, [isNonJsxSameLineTokenContext, isNotStatementConditionContext], 16 /* DeleteSpace */), - // More unary operator special-casing. - // DevDiv 181814: Be careful when removing leading whitespace - // around unary operators. Examples: - // 1 - -2 --X--> 1--2 - // a + ++b --X--> a+++b - rule("SpaceAfterPostincrementWhenFollowedByAdd", 46 /* PlusPlusToken */, 40 /* PlusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 4 /* InsertSpace */), - rule("SpaceAfterAddWhenFollowedByUnaryPlus", 40 /* PlusToken */, 40 /* PlusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 4 /* InsertSpace */), - rule("SpaceAfterAddWhenFollowedByPreincrement", 40 /* PlusToken */, 46 /* PlusPlusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 4 /* InsertSpace */), - rule("SpaceAfterPostdecrementWhenFollowedBySubtract", 47 /* MinusMinusToken */, 41 /* MinusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 4 /* InsertSpace */), - rule("SpaceAfterSubtractWhenFollowedByUnaryMinus", 41 /* MinusToken */, 41 /* MinusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 4 /* InsertSpace */), - rule("SpaceAfterSubtractWhenFollowedByPredecrement", 41 /* MinusToken */, 47 /* MinusMinusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 4 /* InsertSpace */), - rule("NoSpaceAfterCloseBrace", 20 /* CloseBraceToken */, [28 /* CommaToken */, 27 /* SemicolonToken */], [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */), - // For functions and control block place } on a new line [multi-line rule] - rule("NewLineBeforeCloseBraceInBlockContext", anyTokenIncludingMultilineComments, 20 /* CloseBraceToken */, [isMultilineBlockContext], 8 /* InsertNewLine */), - // Space/new line after }. - rule("SpaceAfterCloseBrace", 20 /* CloseBraceToken */, anyTokenExcept(22 /* CloseParenToken */), [isNonJsxSameLineTokenContext, isAfterCodeBlockContext], 4 /* InsertSpace */), - // Special case for (}, else) and (}, while) since else & while tokens are not part of the tree which makes SpaceAfterCloseBrace rule not applied - // Also should not apply to }) - rule("SpaceBetweenCloseBraceAndElse", 20 /* CloseBraceToken */, 93 /* ElseKeyword */, [isNonJsxSameLineTokenContext], 4 /* InsertSpace */), - rule("SpaceBetweenCloseBraceAndWhile", 20 /* CloseBraceToken */, 117 /* WhileKeyword */, [isNonJsxSameLineTokenContext], 4 /* InsertSpace */), - rule("NoSpaceBetweenEmptyBraceBrackets", 19 /* OpenBraceToken */, 20 /* CloseBraceToken */, [isNonJsxSameLineTokenContext, isObjectContext], 16 /* DeleteSpace */), - // Add a space after control dec context if the next character is an open bracket ex: 'if (false)[a, b] = [1, 2];' -> 'if (false) [a, b] = [1, 2];' - rule("SpaceAfterConditionalClosingParen", 22 /* CloseParenToken */, 23 /* OpenBracketToken */, [isControlDeclContext], 4 /* InsertSpace */), - rule("NoSpaceBetweenFunctionKeywordAndStar", 100 /* FunctionKeyword */, 42 /* AsteriskToken */, [isFunctionDeclarationOrFunctionExpressionContext], 16 /* DeleteSpace */), - rule("SpaceAfterStarInGeneratorDeclaration", 42 /* AsteriskToken */, 80 /* Identifier */, [isFunctionDeclarationOrFunctionExpressionContext], 4 /* InsertSpace */), - rule("SpaceAfterFunctionInFuncDecl", 100 /* FunctionKeyword */, anyToken, [isFunctionDeclContext], 4 /* InsertSpace */), - // Insert new line after { and before } in multi-line contexts. - rule("NewLineAfterOpenBraceInBlockContext", 19 /* OpenBraceToken */, anyToken, [isMultilineBlockContext], 8 /* InsertNewLine */), - // For get/set members, we check for (identifier,identifier) since get/set don't have tokens and they are represented as just an identifier token. - // Though, we do extra check on the context to make sure we are dealing with get/set node. Example: - // get x() {} - // set x(val) {} - rule("SpaceAfterGetSetInMember", [139 /* GetKeyword */, 153 /* SetKeyword */], 80 /* Identifier */, [isFunctionDeclContext], 4 /* InsertSpace */), - rule("NoSpaceBetweenYieldKeywordAndStar", 127 /* YieldKeyword */, 42 /* AsteriskToken */, [isNonJsxSameLineTokenContext, isYieldOrYieldStarWithOperand], 16 /* DeleteSpace */), - rule("SpaceBetweenYieldOrYieldStarAndOperand", [127 /* YieldKeyword */, 42 /* AsteriskToken */], anyToken, [isNonJsxSameLineTokenContext, isYieldOrYieldStarWithOperand], 4 /* InsertSpace */), - rule("NoSpaceBetweenReturnAndSemicolon", 107 /* ReturnKeyword */, 27 /* SemicolonToken */, [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */), - rule("SpaceAfterCertainKeywords", [115 /* VarKeyword */, 111 /* ThrowKeyword */, 105 /* NewKeyword */, 91 /* DeleteKeyword */, 107 /* ReturnKeyword */, 114 /* TypeOfKeyword */, 135 /* AwaitKeyword */], anyToken, [isNonJsxSameLineTokenContext], 4 /* InsertSpace */), - rule("SpaceAfterLetConstInVariableDeclaration", [121 /* LetKeyword */, 87 /* ConstKeyword */], anyToken, [isNonJsxSameLineTokenContext, isStartOfVariableDeclarationList], 4 /* InsertSpace */), - rule("NoSpaceBeforeOpenParenInFuncCall", anyToken, 21 /* OpenParenToken */, [isNonJsxSameLineTokenContext, isFunctionCallOrNewContext, isPreviousTokenNotComma], 16 /* DeleteSpace */), - // Special case for binary operators (that are keywords). For these we have to add a space and shouldn't follow any user options. - rule("SpaceBeforeBinaryKeywordOperator", anyToken, binaryKeywordOperators, [isNonJsxSameLineTokenContext, isBinaryOpContext], 4 /* InsertSpace */), - rule("SpaceAfterBinaryKeywordOperator", binaryKeywordOperators, anyToken, [isNonJsxSameLineTokenContext, isBinaryOpContext], 4 /* InsertSpace */), - rule("SpaceAfterVoidOperator", 116 /* VoidKeyword */, anyToken, [isNonJsxSameLineTokenContext, isVoidOpContext], 4 /* InsertSpace */), - // Async-await - rule("SpaceBetweenAsyncAndOpenParen", 134 /* AsyncKeyword */, 21 /* OpenParenToken */, [isArrowFunctionContext, isNonJsxSameLineTokenContext], 4 /* InsertSpace */), - rule("SpaceBetweenAsyncAndFunctionKeyword", 134 /* AsyncKeyword */, [100 /* FunctionKeyword */, 80 /* Identifier */], [isNonJsxSameLineTokenContext], 4 /* InsertSpace */), - // Template string - rule("NoSpaceBetweenTagAndTemplateString", [80 /* Identifier */, 22 /* CloseParenToken */], [15 /* NoSubstitutionTemplateLiteral */, 16 /* TemplateHead */], [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */), - // JSX opening elements - rule("SpaceBeforeJsxAttribute", anyToken, 80 /* Identifier */, [isNextTokenParentJsxAttribute, isNonJsxSameLineTokenContext], 4 /* InsertSpace */), - rule("SpaceBeforeSlashInJsxOpeningElement", anyToken, 44 /* SlashToken */, [isJsxSelfClosingElementContext, isNonJsxSameLineTokenContext], 4 /* InsertSpace */), - rule("NoSpaceBeforeGreaterThanTokenInJsxOpeningElement", 44 /* SlashToken */, 32 /* GreaterThanToken */, [isJsxSelfClosingElementContext, isNonJsxSameLineTokenContext], 16 /* DeleteSpace */), - rule("NoSpaceBeforeEqualInJsxAttribute", anyToken, 64 /* EqualsToken */, [isJsxAttributeContext, isNonJsxSameLineTokenContext], 16 /* DeleteSpace */), - rule("NoSpaceAfterEqualInJsxAttribute", 64 /* EqualsToken */, anyToken, [isJsxAttributeContext, isNonJsxSameLineTokenContext], 16 /* DeleteSpace */), - rule("NoSpaceBeforeJsxNamespaceColon", 80 /* Identifier */, 59 /* ColonToken */, [isNextTokenParentJsxNamespacedName], 16 /* DeleteSpace */), - rule("NoSpaceAfterJsxNamespaceColon", 59 /* ColonToken */, 80 /* Identifier */, [isNextTokenParentJsxNamespacedName], 16 /* DeleteSpace */), - // TypeScript-specific rules - // Use of module as a function call. e.g.: import m2 = module("m2"); - rule("NoSpaceAfterModuleImport", [144 /* ModuleKeyword */, 149 /* RequireKeyword */], 21 /* OpenParenToken */, [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */), - // Add a space around certain TypeScript keywords - rule( - "SpaceAfterCertainTypeScriptKeywords", - [ - 128 /* AbstractKeyword */, - 129 /* AccessorKeyword */, - 86 /* ClassKeyword */, - 138 /* DeclareKeyword */, - 90 /* DefaultKeyword */, - 94 /* EnumKeyword */, - 95 /* ExportKeyword */, - 96 /* ExtendsKeyword */, - 139 /* GetKeyword */, - 119 /* ImplementsKeyword */, - 102 /* ImportKeyword */, - 120 /* InterfaceKeyword */, - 144 /* ModuleKeyword */, - 145 /* NamespaceKeyword */, - 123 /* PrivateKeyword */, - 125 /* PublicKeyword */, - 124 /* ProtectedKeyword */, - 148 /* ReadonlyKeyword */, - 153 /* SetKeyword */, - 126 /* StaticKeyword */, - 156 /* TypeKeyword */, - 161 /* FromKeyword */, - 143 /* KeyOfKeyword */, - 140 /* InferKeyword */ - ], - anyToken, - [isNonJsxSameLineTokenContext], - 4 /* InsertSpace */ - ), - rule( - "SpaceBeforeCertainTypeScriptKeywords", - anyToken, - [96 /* ExtendsKeyword */, 119 /* ImplementsKeyword */, 161 /* FromKeyword */], - [isNonJsxSameLineTokenContext], - 4 /* InsertSpace */ - ), - // Treat string literals in module names as identifiers, and add a space between the literal and the opening Brace braces, e.g.: module "m2" { - rule("SpaceAfterModuleName", 11 /* StringLiteral */, 19 /* OpenBraceToken */, [isModuleDeclContext], 4 /* InsertSpace */), - // Lambda expressions - rule("SpaceBeforeArrow", anyToken, 39 /* EqualsGreaterThanToken */, [isNonJsxSameLineTokenContext], 4 /* InsertSpace */), - rule("SpaceAfterArrow", 39 /* EqualsGreaterThanToken */, anyToken, [isNonJsxSameLineTokenContext], 4 /* InsertSpace */), - // Optional parameters and let args - rule("NoSpaceAfterEllipsis", 26 /* DotDotDotToken */, 80 /* Identifier */, [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */), - rule("NoSpaceAfterOptionalParameters", 58 /* QuestionToken */, [22 /* CloseParenToken */, 28 /* CommaToken */], [isNonJsxSameLineTokenContext, isNotBinaryOpContext], 16 /* DeleteSpace */), - // Remove spaces in empty interface literals. e.g.: x: {} - rule("NoSpaceBetweenEmptyInterfaceBraceBrackets", 19 /* OpenBraceToken */, 20 /* CloseBraceToken */, [isNonJsxSameLineTokenContext, isObjectTypeContext], 16 /* DeleteSpace */), - // generics and type assertions - rule("NoSpaceBeforeOpenAngularBracket", typeNames, 30 /* LessThanToken */, [isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext], 16 /* DeleteSpace */), - rule("NoSpaceBetweenCloseParenAndAngularBracket", 22 /* CloseParenToken */, 30 /* LessThanToken */, [isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext], 16 /* DeleteSpace */), - rule("NoSpaceAfterOpenAngularBracket", 30 /* LessThanToken */, anyToken, [isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext], 16 /* DeleteSpace */), - rule("NoSpaceBeforeCloseAngularBracket", anyToken, 32 /* GreaterThanToken */, [isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext], 16 /* DeleteSpace */), - rule("NoSpaceAfterCloseAngularBracket", 32 /* GreaterThanToken */, [21 /* OpenParenToken */, 23 /* OpenBracketToken */, 32 /* GreaterThanToken */, 28 /* CommaToken */], [ - isNonJsxSameLineTokenContext, - isTypeArgumentOrParameterOrAssertionContext, - isNotFunctionDeclContext, - /*To prevent an interference with the SpaceBeforeOpenParenInFuncDecl rule*/ - isNonTypeAssertionContext - ], 16 /* DeleteSpace */), - // decorators - rule("SpaceBeforeAt", [22 /* CloseParenToken */, 80 /* Identifier */], 60 /* AtToken */, [isNonJsxSameLineTokenContext], 4 /* InsertSpace */), - rule("NoSpaceAfterAt", 60 /* AtToken */, anyToken, [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */), - // Insert space after @ in decorator - rule( - "SpaceAfterDecorator", - anyToken, - [ - 128 /* AbstractKeyword */, - 80 /* Identifier */, - 95 /* ExportKeyword */, - 90 /* DefaultKeyword */, - 86 /* ClassKeyword */, - 126 /* StaticKeyword */, - 125 /* PublicKeyword */, - 123 /* PrivateKeyword */, - 124 /* ProtectedKeyword */, - 139 /* GetKeyword */, - 153 /* SetKeyword */, - 23 /* OpenBracketToken */, - 42 /* AsteriskToken */ - ], - [isEndOfDecoratorContextOnSameLine], - 4 /* InsertSpace */ - ), - rule("NoSpaceBeforeNonNullAssertionOperator", anyToken, 54 /* ExclamationToken */, [isNonJsxSameLineTokenContext, isNonNullAssertionContext], 16 /* DeleteSpace */), - rule("NoSpaceAfterNewKeywordOnConstructorSignature", 105 /* NewKeyword */, 21 /* OpenParenToken */, [isNonJsxSameLineTokenContext, isConstructorSignatureContext], 16 /* DeleteSpace */), - rule("SpaceLessThanAndNonJSXTypeAnnotation", 30 /* LessThanToken */, 30 /* LessThanToken */, [isNonJsxSameLineTokenContext], 4 /* InsertSpace */) - ]; + // Leave comments alone + rule("IgnoreBeforeComment", anyToken, comments, anyContext, 1 /* StopProcessingSpaceActions */), rule("IgnoreAfterLineComment", 2 /* SingleLineCommentTrivia */, anyToken, anyContext, 1 /* StopProcessingSpaceActions */), rule("NotSpaceBeforeColon", anyToken, 59 /* ColonToken */, [isNonJsxSameLineTokenContext, isNotBinaryOpContext, isNotTypeAnnotationContext], 16 /* DeleteSpace */), rule("SpaceAfterColon", 59 /* ColonToken */, anyToken, [isNonJsxSameLineTokenContext, isNotBinaryOpContext, isNextTokenParentNotJsxNamespacedName], 4 /* InsertSpace */), rule("NoSpaceBeforeQuestionMark", anyToken, 58 /* QuestionToken */, [isNonJsxSameLineTokenContext, isNotBinaryOpContext, isNotTypeAnnotationContext], 16 /* DeleteSpace */), + // insert space after '?' only when it is used in conditional operator + rule("SpaceAfterQuestionMarkInConditionalOperator", 58 /* QuestionToken */, anyToken, [isNonJsxSameLineTokenContext, isConditionalOperatorContext], 4 /* InsertSpace */), + // in other cases there should be no space between '?' and next token + rule("NoSpaceAfterQuestionMark", 58 /* QuestionToken */, anyToken, [isNonJsxSameLineTokenContext, isNonOptionalPropertyContext], 16 /* DeleteSpace */), rule("NoSpaceBeforeDot", anyToken, [25 /* DotToken */, 29 /* QuestionDotToken */], [isNonJsxSameLineTokenContext, isNotPropertyAccessOnIntegerLiteral], 16 /* DeleteSpace */), rule("NoSpaceAfterDot", [25 /* DotToken */, 29 /* QuestionDotToken */], anyToken, [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */), rule("NoSpaceBetweenImportParenInImportType", 102 /* ImportKeyword */, 21 /* OpenParenToken */, [isNonJsxSameLineTokenContext, isImportTypeContext], 16 /* DeleteSpace */), + // Special handling of unary operators. + // Prefix operators generally shouldn't have a space between + // them and their target unary expression. + rule("NoSpaceAfterUnaryPrefixOperator", unaryPrefixOperators, unaryPrefixExpressions, [isNonJsxSameLineTokenContext, isNotBinaryOpContext], 16 /* DeleteSpace */), rule("NoSpaceAfterUnaryPreincrementOperator", 46 /* PlusPlusToken */, unaryPreincrementExpressions, [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */), rule("NoSpaceAfterUnaryPredecrementOperator", 47 /* MinusMinusToken */, unaryPredecrementExpressions, [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */), rule("NoSpaceBeforeUnaryPostincrementOperator", unaryPostincrementExpressions, 46 /* PlusPlusToken */, [isNonJsxSameLineTokenContext, isNotStatementConditionContext], 16 /* DeleteSpace */), rule("NoSpaceBeforeUnaryPostdecrementOperator", unaryPostdecrementExpressions, 47 /* MinusMinusToken */, [isNonJsxSameLineTokenContext, isNotStatementConditionContext], 16 /* DeleteSpace */), + // More unary operator special-casing. + // DevDiv 181814: Be careful when removing leading whitespace + // around unary operators. Examples: + // 1 - -2 --X--> 1--2 + // a + ++b --X--> a+++b + rule("SpaceAfterPostincrementWhenFollowedByAdd", 46 /* PlusPlusToken */, 40 /* PlusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 4 /* InsertSpace */), rule("SpaceAfterAddWhenFollowedByUnaryPlus", 40 /* PlusToken */, 40 /* PlusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 4 /* InsertSpace */), rule("SpaceAfterAddWhenFollowedByPreincrement", 40 /* PlusToken */, 46 /* PlusPlusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 4 /* InsertSpace */), rule("SpaceAfterPostdecrementWhenFollowedBySubtract", 47 /* MinusMinusToken */, 41 /* MinusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 4 /* InsertSpace */), rule("SpaceAfterSubtractWhenFollowedByUnaryMinus", 41 /* MinusToken */, 41 /* MinusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 4 /* InsertSpace */), rule("SpaceAfterSubtractWhenFollowedByPredecrement", 41 /* MinusToken */, 47 /* MinusMinusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 4 /* InsertSpace */), rule("NoSpaceAfterCloseBrace", 20 /* CloseBraceToken */, [28 /* CommaToken */, 27 /* SemicolonToken */], [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */), + // For functions and control block place } on a new line [multi-line rule] + rule("NewLineBeforeCloseBraceInBlockContext", anyTokenIncludingMultilineComments, 20 /* CloseBraceToken */, [isMultilineBlockContext], 8 /* InsertNewLine */), + // Space/new line after }. + rule("SpaceAfterCloseBrace", 20 /* CloseBraceToken */, anyTokenExcept(22 /* CloseParenToken */), [isNonJsxSameLineTokenContext, isAfterCodeBlockContext], 4 /* InsertSpace */), + // Special case for (}, else) and (}, while) since else & while tokens are not part of the tree which makes SpaceAfterCloseBrace rule not applied + // Also should not apply to }) + rule("SpaceBetweenCloseBraceAndElse", 20 /* CloseBraceToken */, 93 /* ElseKeyword */, [isNonJsxSameLineTokenContext], 4 /* InsertSpace */), rule("SpaceBetweenCloseBraceAndWhile", 20 /* CloseBraceToken */, 117 /* WhileKeyword */, [isNonJsxSameLineTokenContext], 4 /* InsertSpace */), rule("NoSpaceBetweenEmptyBraceBrackets", 19 /* OpenBraceToken */, 20 /* CloseBraceToken */, [isNonJsxSameLineTokenContext, isObjectContext], 16 /* DeleteSpace */), + // Add a space after control dec context if the next character is an open bracket ex: 'if (false)[a, b] = [1, 2];' -> 'if (false) [a, b] = [1, 2];' + rule("SpaceAfterConditionalClosingParen", 22 /* CloseParenToken */, 23 /* OpenBracketToken */, [isControlDeclContext], 4 /* InsertSpace */), rule("NoSpaceBetweenFunctionKeywordAndStar", 100 /* FunctionKeyword */, 42 /* AsteriskToken */, [isFunctionDeclarationOrFunctionExpressionContext], 16 /* DeleteSpace */), rule("SpaceAfterStarInGeneratorDeclaration", 42 /* AsteriskToken */, 80 /* Identifier */, [isFunctionDeclarationOrFunctionExpressionContext], 4 /* InsertSpace */), rule("SpaceAfterFunctionInFuncDecl", 100 /* FunctionKeyword */, anyToken, [isFunctionDeclContext], 4 /* InsertSpace */), + // Insert new line after { and before } in multi-line contexts. + rule("NewLineAfterOpenBraceInBlockContext", 19 /* OpenBraceToken */, anyToken, [isMultilineBlockContext], 8 /* InsertNewLine */), + // For get/set members, we check for (identifier,identifier) since get/set don't have tokens and they are represented as just an identifier token. + // Though, we do extra check on the context to make sure we are dealing with get/set node. Example: + // get x() {} + // set x(val) {} + rule("SpaceAfterGetSetInMember", [139 /* GetKeyword */, 153 /* SetKeyword */], 80 /* Identifier */, [isFunctionDeclContext], 4 /* InsertSpace */), rule("NoSpaceBetweenYieldKeywordAndStar", 127 /* YieldKeyword */, 42 /* AsteriskToken */, [isNonJsxSameLineTokenContext, isYieldOrYieldStarWithOperand], 16 /* DeleteSpace */), rule("SpaceBetweenYieldOrYieldStarAndOperand", [127 /* YieldKeyword */, 42 /* AsteriskToken */], anyToken, [isNonJsxSameLineTokenContext, isYieldOrYieldStarWithOperand], 4 /* InsertSpace */), rule("NoSpaceBetweenReturnAndSemicolon", 107 /* ReturnKeyword */, 27 /* SemicolonToken */, [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */), rule("SpaceAfterCertainKeywords", [115 /* VarKeyword */, 111 /* ThrowKeyword */, 105 /* NewKeyword */, 91 /* DeleteKeyword */, 107 /* ReturnKeyword */, 114 /* TypeOfKeyword */, 135 /* AwaitKeyword */], anyToken, [isNonJsxSameLineTokenContext], 4 /* InsertSpace */), rule("SpaceAfterLetConstInVariableDeclaration", [121 /* LetKeyword */, 87 /* ConstKeyword */], anyToken, [isNonJsxSameLineTokenContext, isStartOfVariableDeclarationList], 4 /* InsertSpace */), rule("NoSpaceBeforeOpenParenInFuncCall", anyToken, 21 /* OpenParenToken */, [isNonJsxSameLineTokenContext, isFunctionCallOrNewContext, isPreviousTokenNotComma], 16 /* DeleteSpace */), + // Special case for binary operators (that are keywords). For these we have to add a space and shouldn't follow any user options. + rule("SpaceBeforeBinaryKeywordOperator", anyToken, binaryKeywordOperators, [isNonJsxSameLineTokenContext, isBinaryOpContext], 4 /* InsertSpace */), rule("SpaceAfterBinaryKeywordOperator", binaryKeywordOperators, anyToken, [isNonJsxSameLineTokenContext, isBinaryOpContext], 4 /* InsertSpace */), rule("SpaceAfterVoidOperator", 116 /* VoidKeyword */, anyToken, [isNonJsxSameLineTokenContext, isVoidOpContext], 4 /* InsertSpace */), + // Async-await + rule("SpaceBetweenAsyncAndOpenParen", 134 /* AsyncKeyword */, 21 /* OpenParenToken */, [isArrowFunctionContext, isNonJsxSameLineTokenContext], 4 /* InsertSpace */), rule("SpaceBetweenAsyncAndFunctionKeyword", 134 /* AsyncKeyword */, [100 /* FunctionKeyword */, 80 /* Identifier */], [isNonJsxSameLineTokenContext], 4 /* InsertSpace */), + // Template string + rule("NoSpaceBetweenTagAndTemplateString", [80 /* Identifier */, 22 /* CloseParenToken */], [15 /* NoSubstitutionTemplateLiteral */, 16 /* TemplateHead */], [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */), + // JSX opening elements + rule("SpaceBeforeJsxAttribute", anyToken, 80 /* Identifier */, [isNextTokenParentJsxAttribute, isNonJsxSameLineTokenContext], 4 /* InsertSpace */), rule("SpaceBeforeSlashInJsxOpeningElement", anyToken, 44 /* SlashToken */, [isJsxSelfClosingElementContext, isNonJsxSameLineTokenContext], 4 /* InsertSpace */), rule("NoSpaceBeforeGreaterThanTokenInJsxOpeningElement", 44 /* SlashToken */, 32 /* GreaterThanToken */, [isJsxSelfClosingElementContext, isNonJsxSameLineTokenContext], 16 /* DeleteSpace */), rule("NoSpaceBeforeEqualInJsxAttribute", anyToken, 64 /* EqualsToken */, [isJsxAttributeContext, isNonJsxSameLineTokenContext], 16 /* DeleteSpace */), rule("NoSpaceAfterEqualInJsxAttribute", 64 /* EqualsToken */, anyToken, [isJsxAttributeContext, isNonJsxSameLineTokenContext], 16 /* DeleteSpace */), rule("NoSpaceBeforeJsxNamespaceColon", 80 /* Identifier */, 59 /* ColonToken */, [isNextTokenParentJsxNamespacedName], 16 /* DeleteSpace */), rule("NoSpaceAfterJsxNamespaceColon", 59 /* ColonToken */, 80 /* Identifier */, [isNextTokenParentJsxNamespacedName], 16 /* DeleteSpace */), + // TypeScript-specific rules + // Use of module as a function call. e.g.: import m2 = module("m2"); + rule("NoSpaceAfterModuleImport", [144 /* ModuleKeyword */, 149 /* RequireKeyword */], 21 /* OpenParenToken */, [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */), + // Add a space around certain TypeScript keywords + rule("SpaceAfterCertainTypeScriptKeywords", [128 /* AbstractKeyword */, 129 /* AccessorKeyword */, 86 /* ClassKeyword */, 138 /* DeclareKeyword */, 90 /* DefaultKeyword */, 94 /* EnumKeyword */, 95 /* ExportKeyword */, 96 /* ExtendsKeyword */, 139 /* GetKeyword */, 119 /* ImplementsKeyword */, 102 /* ImportKeyword */, 120 /* InterfaceKeyword */, 144 /* ModuleKeyword */, 145 /* NamespaceKeyword */, 123 /* PrivateKeyword */, 125 /* PublicKeyword */, 124 /* ProtectedKeyword */, 148 /* ReadonlyKeyword */, 153 /* SetKeyword */, 126 /* StaticKeyword */, 156 /* TypeKeyword */, 161 /* FromKeyword */, 143 /* KeyOfKeyword */, 140 /* InferKeyword */], anyToken, [isNonJsxSameLineTokenContext], 4 /* InsertSpace */), rule("SpaceBeforeCertainTypeScriptKeywords", anyToken, [96 /* ExtendsKeyword */, 119 /* ImplementsKeyword */, 161 /* FromKeyword */], [isNonJsxSameLineTokenContext], 4 /* InsertSpace */), + // Treat string literals in module names as identifiers, and add a space between the literal and the opening Brace braces, e.g.: module "m2" { + rule("SpaceAfterModuleName", 11 /* StringLiteral */, 19 /* OpenBraceToken */, [isModuleDeclContext], 4 /* InsertSpace */), + // Lambda expressions + rule("SpaceBeforeArrow", anyToken, 39 /* EqualsGreaterThanToken */, [isNonJsxSameLineTokenContext], 4 /* InsertSpace */), rule("SpaceAfterArrow", 39 /* EqualsGreaterThanToken */, anyToken, [isNonJsxSameLineTokenContext], 4 /* InsertSpace */), + // Optional parameters and let args + rule("NoSpaceAfterEllipsis", 26 /* DotDotDotToken */, 80 /* Identifier */, [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */), rule("NoSpaceAfterOptionalParameters", 58 /* QuestionToken */, [22 /* CloseParenToken */, 28 /* CommaToken */], [isNonJsxSameLineTokenContext, isNotBinaryOpContext], 16 /* DeleteSpace */), + // Remove spaces in empty interface literals. e.g.: x: {} + rule("NoSpaceBetweenEmptyInterfaceBraceBrackets", 19 /* OpenBraceToken */, 20 /* CloseBraceToken */, [isNonJsxSameLineTokenContext, isObjectTypeContext], 16 /* DeleteSpace */), + // generics and type assertions + rule("NoSpaceBeforeOpenAngularBracket", typeNames, 30 /* LessThanToken */, [isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext], 16 /* DeleteSpace */), rule("NoSpaceBetweenCloseParenAndAngularBracket", 22 /* CloseParenToken */, 30 /* LessThanToken */, [isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext], 16 /* DeleteSpace */), rule("NoSpaceAfterOpenAngularBracket", 30 /* LessThanToken */, anyToken, [isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext], 16 /* DeleteSpace */), rule("NoSpaceBeforeCloseAngularBracket", anyToken, 32 /* GreaterThanToken */, [isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext], 16 /* DeleteSpace */), rule("NoSpaceAfterCloseAngularBracket", 32 /* GreaterThanToken */, [21 /* OpenParenToken */, 23 /* OpenBracketToken */, 32 /* GreaterThanToken */, 28 /* CommaToken */], [isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext, isNotFunctionDeclContext, /*To prevent an interference with the SpaceBeforeOpenParenInFuncDecl rule*/ + isNonTypeAssertionContext], 16 /* DeleteSpace */), + // decorators + rule("SpaceBeforeAt", [22 /* CloseParenToken */, 80 /* Identifier */], 60 /* AtToken */, [isNonJsxSameLineTokenContext], 4 /* InsertSpace */), rule("NoSpaceAfterAt", 60 /* AtToken */, anyToken, [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */), + // Insert space after @ in decorator + rule("SpaceAfterDecorator", anyToken, [128 /* AbstractKeyword */, 80 /* Identifier */, 95 /* ExportKeyword */, 90 /* DefaultKeyword */, 86 /* ClassKeyword */, 126 /* StaticKeyword */, 125 /* PublicKeyword */, 123 /* PrivateKeyword */, 124 /* ProtectedKeyword */, 139 /* GetKeyword */, 153 /* SetKeyword */, 23 /* OpenBracketToken */, 42 /* AsteriskToken */], [isEndOfDecoratorContextOnSameLine], 4 /* InsertSpace */), rule("NoSpaceBeforeNonNullAssertionOperator", anyToken, 54 /* ExclamationToken */, [isNonJsxSameLineTokenContext, isNonNullAssertionContext], 16 /* DeleteSpace */), rule("NoSpaceAfterNewKeywordOnConstructorSignature", 105 /* NewKeyword */, 21 /* OpenParenToken */, [isNonJsxSameLineTokenContext, isConstructorSignatureContext], 16 /* DeleteSpace */), rule("SpaceLessThanAndNonJSXTypeAnnotation", 30 /* LessThanToken */, 30 /* LessThanToken */, [isNonJsxSameLineTokenContext], 4 /* InsertSpace */)]; + const userConfigurableRules = [ - // Treat constructor as an identifier in a function declaration, and remove spaces between constructor and following left parentheses - rule("SpaceAfterConstructor", 137 /* ConstructorKeyword */, 21 /* OpenParenToken */, [isOptionEnabled("insertSpaceAfterConstructor"), isNonJsxSameLineTokenContext], 4 /* InsertSpace */), - rule("NoSpaceAfterConstructor", 137 /* ConstructorKeyword */, 21 /* OpenParenToken */, [isOptionDisabledOrUndefined("insertSpaceAfterConstructor"), isNonJsxSameLineTokenContext], 16 /* DeleteSpace */), - rule("SpaceAfterComma", 28 /* CommaToken */, anyToken, [isOptionEnabled("insertSpaceAfterCommaDelimiter"), isNonJsxSameLineTokenContext, isNonJsxElementOrFragmentContext, isNextTokenNotCloseBracket, isNextTokenNotCloseParen], 4 /* InsertSpace */), - rule("NoSpaceAfterComma", 28 /* CommaToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterCommaDelimiter"), isNonJsxSameLineTokenContext, isNonJsxElementOrFragmentContext], 16 /* DeleteSpace */), - // Insert space after function keyword for anonymous functions - rule("SpaceAfterAnonymousFunctionKeyword", [100 /* FunctionKeyword */, 42 /* AsteriskToken */], 21 /* OpenParenToken */, [isOptionEnabled("insertSpaceAfterFunctionKeywordForAnonymousFunctions"), isFunctionDeclContext], 4 /* InsertSpace */), - rule("NoSpaceAfterAnonymousFunctionKeyword", [100 /* FunctionKeyword */, 42 /* AsteriskToken */], 21 /* OpenParenToken */, [isOptionDisabledOrUndefined("insertSpaceAfterFunctionKeywordForAnonymousFunctions"), isFunctionDeclContext], 16 /* DeleteSpace */), - // Insert space after keywords in control flow statements - rule("SpaceAfterKeywordInControl", keywords, 21 /* OpenParenToken */, [isOptionEnabled("insertSpaceAfterKeywordsInControlFlowStatements"), isControlDeclContext], 4 /* InsertSpace */), - rule("NoSpaceAfterKeywordInControl", keywords, 21 /* OpenParenToken */, [isOptionDisabledOrUndefined("insertSpaceAfterKeywordsInControlFlowStatements"), isControlDeclContext], 16 /* DeleteSpace */), - // Insert space after opening and before closing nonempty parenthesis - rule("SpaceAfterOpenParen", 21 /* OpenParenToken */, anyToken, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), isNonJsxSameLineTokenContext], 4 /* InsertSpace */), - rule("SpaceBeforeCloseParen", anyToken, 22 /* CloseParenToken */, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), isNonJsxSameLineTokenContext], 4 /* InsertSpace */), - rule("SpaceBetweenOpenParens", 21 /* OpenParenToken */, 21 /* OpenParenToken */, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), isNonJsxSameLineTokenContext], 4 /* InsertSpace */), - rule("NoSpaceBetweenParens", 21 /* OpenParenToken */, 22 /* CloseParenToken */, [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */), - rule("NoSpaceAfterOpenParen", 21 /* OpenParenToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), isNonJsxSameLineTokenContext], 16 /* DeleteSpace */), - rule("NoSpaceBeforeCloseParen", anyToken, 22 /* CloseParenToken */, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), isNonJsxSameLineTokenContext], 16 /* DeleteSpace */), - // Insert space after opening and before closing nonempty brackets - rule("SpaceAfterOpenBracket", 23 /* OpenBracketToken */, anyToken, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), isNonJsxSameLineTokenContext], 4 /* InsertSpace */), - rule("SpaceBeforeCloseBracket", anyToken, 24 /* CloseBracketToken */, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), isNonJsxSameLineTokenContext], 4 /* InsertSpace */), - rule("NoSpaceBetweenBrackets", 23 /* OpenBracketToken */, 24 /* CloseBracketToken */, [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */), - rule("NoSpaceAfterOpenBracket", 23 /* OpenBracketToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), isNonJsxSameLineTokenContext], 16 /* DeleteSpace */), - rule("NoSpaceBeforeCloseBracket", anyToken, 24 /* CloseBracketToken */, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), isNonJsxSameLineTokenContext], 16 /* DeleteSpace */), - // Insert a space after { and before } in single-line contexts, but remove space from empty object literals {}. - rule("SpaceAfterOpenBrace", 19 /* OpenBraceToken */, anyToken, [isOptionEnabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), isBraceWrappedContext], 4 /* InsertSpace */), - rule("SpaceBeforeCloseBrace", anyToken, 20 /* CloseBraceToken */, [isOptionEnabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), isBraceWrappedContext], 4 /* InsertSpace */), - rule("NoSpaceBetweenEmptyBraceBrackets", 19 /* OpenBraceToken */, 20 /* CloseBraceToken */, [isNonJsxSameLineTokenContext, isObjectContext], 16 /* DeleteSpace */), - rule("NoSpaceAfterOpenBrace", 19 /* OpenBraceToken */, anyToken, [isOptionDisabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), isNonJsxSameLineTokenContext], 16 /* DeleteSpace */), - rule("NoSpaceBeforeCloseBrace", anyToken, 20 /* CloseBraceToken */, [isOptionDisabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), isNonJsxSameLineTokenContext], 16 /* DeleteSpace */), - // Insert a space after opening and before closing empty brace brackets - rule("SpaceBetweenEmptyBraceBrackets", 19 /* OpenBraceToken */, 20 /* CloseBraceToken */, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingEmptyBraces")], 4 /* InsertSpace */), - rule("NoSpaceBetweenEmptyBraceBrackets", 19 /* OpenBraceToken */, 20 /* CloseBraceToken */, [isOptionDisabled("insertSpaceAfterOpeningAndBeforeClosingEmptyBraces"), isNonJsxSameLineTokenContext], 16 /* DeleteSpace */), - // Insert space after opening and before closing template string braces - rule("SpaceAfterTemplateHeadAndMiddle", [16 /* TemplateHead */, 17 /* TemplateMiddle */], anyToken, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), isNonJsxTextContext], 4 /* InsertSpace */, 1 /* CanDeleteNewLines */), - rule("SpaceBeforeTemplateMiddleAndTail", anyToken, [17 /* TemplateMiddle */, 18 /* TemplateTail */], [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), isNonJsxSameLineTokenContext], 4 /* InsertSpace */), - rule("NoSpaceAfterTemplateHeadAndMiddle", [16 /* TemplateHead */, 17 /* TemplateMiddle */], anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), isNonJsxTextContext], 16 /* DeleteSpace */, 1 /* CanDeleteNewLines */), - rule("NoSpaceBeforeTemplateMiddleAndTail", anyToken, [17 /* TemplateMiddle */, 18 /* TemplateTail */], [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), isNonJsxSameLineTokenContext], 16 /* DeleteSpace */), - // No space after { and before } in JSX expression - rule("SpaceAfterOpenBraceInJsxExpression", 19 /* OpenBraceToken */, anyToken, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), isNonJsxSameLineTokenContext, isJsxExpressionContext], 4 /* InsertSpace */), - rule("SpaceBeforeCloseBraceInJsxExpression", anyToken, 20 /* CloseBraceToken */, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), isNonJsxSameLineTokenContext, isJsxExpressionContext], 4 /* InsertSpace */), - rule("NoSpaceAfterOpenBraceInJsxExpression", 19 /* OpenBraceToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), isNonJsxSameLineTokenContext, isJsxExpressionContext], 16 /* DeleteSpace */), - rule("NoSpaceBeforeCloseBraceInJsxExpression", anyToken, 20 /* CloseBraceToken */, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), isNonJsxSameLineTokenContext, isJsxExpressionContext], 16 /* DeleteSpace */), - // Insert space after semicolon in for statement - rule("SpaceAfterSemicolonInFor", 27 /* SemicolonToken */, anyToken, [isOptionEnabled("insertSpaceAfterSemicolonInForStatements"), isNonJsxSameLineTokenContext, isForContext], 4 /* InsertSpace */), - rule("NoSpaceAfterSemicolonInFor", 27 /* SemicolonToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterSemicolonInForStatements"), isNonJsxSameLineTokenContext, isForContext], 16 /* DeleteSpace */), - // Insert space before and after binary operators - rule("SpaceBeforeBinaryOperator", anyToken, binaryOperators, [isOptionEnabled("insertSpaceBeforeAndAfterBinaryOperators"), isNonJsxSameLineTokenContext, isBinaryOpContext], 4 /* InsertSpace */), - rule("SpaceAfterBinaryOperator", binaryOperators, anyToken, [isOptionEnabled("insertSpaceBeforeAndAfterBinaryOperators"), isNonJsxSameLineTokenContext, isBinaryOpContext], 4 /* InsertSpace */), - rule("NoSpaceBeforeBinaryOperator", anyToken, binaryOperators, [isOptionDisabledOrUndefined("insertSpaceBeforeAndAfterBinaryOperators"), isNonJsxSameLineTokenContext, isBinaryOpContext], 16 /* DeleteSpace */), - rule("NoSpaceAfterBinaryOperator", binaryOperators, anyToken, [isOptionDisabledOrUndefined("insertSpaceBeforeAndAfterBinaryOperators"), isNonJsxSameLineTokenContext, isBinaryOpContext], 16 /* DeleteSpace */), - rule("SpaceBeforeOpenParenInFuncDecl", anyToken, 21 /* OpenParenToken */, [isOptionEnabled("insertSpaceBeforeFunctionParenthesis"), isNonJsxSameLineTokenContext, isFunctionDeclContext], 4 /* InsertSpace */), - rule("NoSpaceBeforeOpenParenInFuncDecl", anyToken, 21 /* OpenParenToken */, [isOptionDisabledOrUndefined("insertSpaceBeforeFunctionParenthesis"), isNonJsxSameLineTokenContext, isFunctionDeclContext], 16 /* DeleteSpace */), - // Open Brace braces after control block - rule("NewLineBeforeOpenBraceInControl", controlOpenBraceLeftTokenRange, 19 /* OpenBraceToken */, [isOptionEnabled("placeOpenBraceOnNewLineForControlBlocks"), isControlDeclContext, isBeforeMultilineBlockContext], 8 /* InsertNewLine */, 1 /* CanDeleteNewLines */), - // Open Brace braces after function - // TypeScript: Function can have return types, which can be made of tons of different token kinds - rule("NewLineBeforeOpenBraceInFunction", functionOpenBraceLeftTokenRange, 19 /* OpenBraceToken */, [isOptionEnabled("placeOpenBraceOnNewLineForFunctions"), isFunctionDeclContext, isBeforeMultilineBlockContext], 8 /* InsertNewLine */, 1 /* CanDeleteNewLines */), - // Open Brace braces after TypeScript module/class/interface - rule("NewLineBeforeOpenBraceInTypeScriptDeclWithBlock", typeScriptOpenBraceLeftTokenRange, 19 /* OpenBraceToken */, [isOptionEnabled("placeOpenBraceOnNewLineForFunctions"), isTypeScriptDeclWithBlockContext, isBeforeMultilineBlockContext], 8 /* InsertNewLine */, 1 /* CanDeleteNewLines */), - rule("SpaceAfterTypeAssertion", 32 /* GreaterThanToken */, anyToken, [isOptionEnabled("insertSpaceAfterTypeAssertion"), isNonJsxSameLineTokenContext, isTypeAssertionContext], 4 /* InsertSpace */), - rule("NoSpaceAfterTypeAssertion", 32 /* GreaterThanToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterTypeAssertion"), isNonJsxSameLineTokenContext, isTypeAssertionContext], 16 /* DeleteSpace */), - rule("SpaceBeforeTypeAnnotation", anyToken, [58 /* QuestionToken */, 59 /* ColonToken */], [isOptionEnabled("insertSpaceBeforeTypeAnnotation"), isNonJsxSameLineTokenContext, isTypeAnnotationContext], 4 /* InsertSpace */), - rule("NoSpaceBeforeTypeAnnotation", anyToken, [58 /* QuestionToken */, 59 /* ColonToken */], [isOptionDisabledOrUndefined("insertSpaceBeforeTypeAnnotation"), isNonJsxSameLineTokenContext, isTypeAnnotationContext], 16 /* DeleteSpace */), - rule("NoOptionalSemicolon", 27 /* SemicolonToken */, anyTokenIncludingEOF, [optionEquals("semicolons", "remove" /* Remove */), isSemicolonDeletionContext], 32 /* DeleteToken */), - rule("OptionalSemicolon", anyToken, anyTokenIncludingEOF, [optionEquals("semicolons", "insert" /* Insert */), isSemicolonInsertionContext], 64 /* InsertTrailingSemicolon */) - ]; + // Treat constructor as an identifier in a function declaration, and remove spaces between constructor and following left parentheses + rule("SpaceAfterConstructor", 137 /* ConstructorKeyword */, 21 /* OpenParenToken */, [isOptionEnabled("insertSpaceAfterConstructor"), isNonJsxSameLineTokenContext], 4 /* InsertSpace */), rule("NoSpaceAfterConstructor", 137 /* ConstructorKeyword */, 21 /* OpenParenToken */, [isOptionDisabledOrUndefined("insertSpaceAfterConstructor"), isNonJsxSameLineTokenContext], 16 /* DeleteSpace */), rule("SpaceAfterComma", 28 /* CommaToken */, anyToken, [isOptionEnabled("insertSpaceAfterCommaDelimiter"), isNonJsxSameLineTokenContext, isNonJsxElementOrFragmentContext, isNextTokenNotCloseBracket, isNextTokenNotCloseParen], 4 /* InsertSpace */), rule("NoSpaceAfterComma", 28 /* CommaToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterCommaDelimiter"), isNonJsxSameLineTokenContext, isNonJsxElementOrFragmentContext], 16 /* DeleteSpace */), + // Insert space after function keyword for anonymous functions + rule("SpaceAfterAnonymousFunctionKeyword", [100 /* FunctionKeyword */, 42 /* AsteriskToken */], 21 /* OpenParenToken */, [isOptionEnabled("insertSpaceAfterFunctionKeywordForAnonymousFunctions"), isFunctionDeclContext], 4 /* InsertSpace */), rule("NoSpaceAfterAnonymousFunctionKeyword", [100 /* FunctionKeyword */, 42 /* AsteriskToken */], 21 /* OpenParenToken */, [isOptionDisabledOrUndefined("insertSpaceAfterFunctionKeywordForAnonymousFunctions"), isFunctionDeclContext], 16 /* DeleteSpace */), + // Insert space after keywords in control flow statements + rule("SpaceAfterKeywordInControl", keywords, 21 /* OpenParenToken */, [isOptionEnabled("insertSpaceAfterKeywordsInControlFlowStatements"), isControlDeclContext], 4 /* InsertSpace */), rule("NoSpaceAfterKeywordInControl", keywords, 21 /* OpenParenToken */, [isOptionDisabledOrUndefined("insertSpaceAfterKeywordsInControlFlowStatements"), isControlDeclContext], 16 /* DeleteSpace */), + // Insert space after opening and before closing nonempty parenthesis + rule("SpaceAfterOpenParen", 21 /* OpenParenToken */, anyToken, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), isNonJsxSameLineTokenContext], 4 /* InsertSpace */), rule("SpaceBeforeCloseParen", anyToken, 22 /* CloseParenToken */, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), isNonJsxSameLineTokenContext], 4 /* InsertSpace */), rule("SpaceBetweenOpenParens", 21 /* OpenParenToken */, 21 /* OpenParenToken */, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), isNonJsxSameLineTokenContext], 4 /* InsertSpace */), rule("NoSpaceBetweenParens", 21 /* OpenParenToken */, 22 /* CloseParenToken */, [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */), rule("NoSpaceAfterOpenParen", 21 /* OpenParenToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), isNonJsxSameLineTokenContext], 16 /* DeleteSpace */), rule("NoSpaceBeforeCloseParen", anyToken, 22 /* CloseParenToken */, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis"), isNonJsxSameLineTokenContext], 16 /* DeleteSpace */), + // Insert space after opening and before closing nonempty brackets + rule("SpaceAfterOpenBracket", 23 /* OpenBracketToken */, anyToken, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), isNonJsxSameLineTokenContext], 4 /* InsertSpace */), rule("SpaceBeforeCloseBracket", anyToken, 24 /* CloseBracketToken */, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), isNonJsxSameLineTokenContext], 4 /* InsertSpace */), rule("NoSpaceBetweenBrackets", 23 /* OpenBracketToken */, 24 /* CloseBracketToken */, [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */), rule("NoSpaceAfterOpenBracket", 23 /* OpenBracketToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), isNonJsxSameLineTokenContext], 16 /* DeleteSpace */), rule("NoSpaceBeforeCloseBracket", anyToken, 24 /* CloseBracketToken */, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets"), isNonJsxSameLineTokenContext], 16 /* DeleteSpace */), + // Insert a space after { and before } in single-line contexts, but remove space from empty object literals {}. + rule("SpaceAfterOpenBrace", 19 /* OpenBraceToken */, anyToken, [isOptionEnabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), isBraceWrappedContext], 4 /* InsertSpace */), rule("SpaceBeforeCloseBrace", anyToken, 20 /* CloseBraceToken */, [isOptionEnabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), isBraceWrappedContext], 4 /* InsertSpace */), rule("NoSpaceBetweenEmptyBraceBrackets", 19 /* OpenBraceToken */, 20 /* CloseBraceToken */, [isNonJsxSameLineTokenContext, isObjectContext], 16 /* DeleteSpace */), rule("NoSpaceAfterOpenBrace", 19 /* OpenBraceToken */, anyToken, [isOptionDisabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), isNonJsxSameLineTokenContext], 16 /* DeleteSpace */), rule("NoSpaceBeforeCloseBrace", anyToken, 20 /* CloseBraceToken */, [isOptionDisabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), isNonJsxSameLineTokenContext], 16 /* DeleteSpace */), + // Insert a space after opening and before closing empty brace brackets + rule("SpaceBetweenEmptyBraceBrackets", 19 /* OpenBraceToken */, 20 /* CloseBraceToken */, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingEmptyBraces")], 4 /* InsertSpace */), rule("NoSpaceBetweenEmptyBraceBrackets", 19 /* OpenBraceToken */, 20 /* CloseBraceToken */, [isOptionDisabled("insertSpaceAfterOpeningAndBeforeClosingEmptyBraces"), isNonJsxSameLineTokenContext], 16 /* DeleteSpace */), + // Insert space after opening and before closing template string braces + rule("SpaceAfterTemplateHeadAndMiddle", [16 /* TemplateHead */, 17 /* TemplateMiddle */], anyToken, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), isNonJsxTextContext], 4 /* InsertSpace */, 1 /* CanDeleteNewLines */), rule("SpaceBeforeTemplateMiddleAndTail", anyToken, [17 /* TemplateMiddle */, 18 /* TemplateTail */], [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), isNonJsxSameLineTokenContext], 4 /* InsertSpace */), rule("NoSpaceAfterTemplateHeadAndMiddle", [16 /* TemplateHead */, 17 /* TemplateMiddle */], anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), isNonJsxTextContext], 16 /* DeleteSpace */, 1 /* CanDeleteNewLines */), rule("NoSpaceBeforeTemplateMiddleAndTail", anyToken, [17 /* TemplateMiddle */, 18 /* TemplateTail */], [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), isNonJsxSameLineTokenContext], 16 /* DeleteSpace */), + // No space after { and before } in JSX expression + rule("SpaceAfterOpenBraceInJsxExpression", 19 /* OpenBraceToken */, anyToken, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), isNonJsxSameLineTokenContext, isJsxExpressionContext], 4 /* InsertSpace */), rule("SpaceBeforeCloseBraceInJsxExpression", anyToken, 20 /* CloseBraceToken */, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), isNonJsxSameLineTokenContext, isJsxExpressionContext], 4 /* InsertSpace */), rule("NoSpaceAfterOpenBraceInJsxExpression", 19 /* OpenBraceToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), isNonJsxSameLineTokenContext, isJsxExpressionContext], 16 /* DeleteSpace */), rule("NoSpaceBeforeCloseBraceInJsxExpression", anyToken, 20 /* CloseBraceToken */, [isOptionDisabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces"), isNonJsxSameLineTokenContext, isJsxExpressionContext], 16 /* DeleteSpace */), + // Insert space after semicolon in for statement + rule("SpaceAfterSemicolonInFor", 27 /* SemicolonToken */, anyToken, [isOptionEnabled("insertSpaceAfterSemicolonInForStatements"), isNonJsxSameLineTokenContext, isForContext], 4 /* InsertSpace */), rule("NoSpaceAfterSemicolonInFor", 27 /* SemicolonToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterSemicolonInForStatements"), isNonJsxSameLineTokenContext, isForContext], 16 /* DeleteSpace */), + // Insert space before and after binary operators + rule("SpaceBeforeBinaryOperator", anyToken, binaryOperators, [isOptionEnabled("insertSpaceBeforeAndAfterBinaryOperators"), isNonJsxSameLineTokenContext, isBinaryOpContext], 4 /* InsertSpace */), rule("SpaceAfterBinaryOperator", binaryOperators, anyToken, [isOptionEnabled("insertSpaceBeforeAndAfterBinaryOperators"), isNonJsxSameLineTokenContext, isBinaryOpContext], 4 /* InsertSpace */), rule("NoSpaceBeforeBinaryOperator", anyToken, binaryOperators, [isOptionDisabledOrUndefined("insertSpaceBeforeAndAfterBinaryOperators"), isNonJsxSameLineTokenContext, isBinaryOpContext], 16 /* DeleteSpace */), rule("NoSpaceAfterBinaryOperator", binaryOperators, anyToken, [isOptionDisabledOrUndefined("insertSpaceBeforeAndAfterBinaryOperators"), isNonJsxSameLineTokenContext, isBinaryOpContext], 16 /* DeleteSpace */), rule("SpaceBeforeOpenParenInFuncDecl", anyToken, 21 /* OpenParenToken */, [isOptionEnabled("insertSpaceBeforeFunctionParenthesis"), isNonJsxSameLineTokenContext, isFunctionDeclContext], 4 /* InsertSpace */), rule("NoSpaceBeforeOpenParenInFuncDecl", anyToken, 21 /* OpenParenToken */, [isOptionDisabledOrUndefined("insertSpaceBeforeFunctionParenthesis"), isNonJsxSameLineTokenContext, isFunctionDeclContext], 16 /* DeleteSpace */), + // Open Brace braces after control block + rule("NewLineBeforeOpenBraceInControl", controlOpenBraceLeftTokenRange, 19 /* OpenBraceToken */, [isOptionEnabled("placeOpenBraceOnNewLineForControlBlocks"), isControlDeclContext, isBeforeMultilineBlockContext], 8 /* InsertNewLine */, 1 /* CanDeleteNewLines */), + // Open Brace braces after function + // TypeScript: Function can have return types, which can be made of tons of different token kinds + rule("NewLineBeforeOpenBraceInFunction", functionOpenBraceLeftTokenRange, 19 /* OpenBraceToken */, [isOptionEnabled("placeOpenBraceOnNewLineForFunctions"), isFunctionDeclContext, isBeforeMultilineBlockContext], 8 /* InsertNewLine */, 1 /* CanDeleteNewLines */), + // Open Brace braces after TypeScript module/class/interface + rule("NewLineBeforeOpenBraceInTypeScriptDeclWithBlock", typeScriptOpenBraceLeftTokenRange, 19 /* OpenBraceToken */, [isOptionEnabled("placeOpenBraceOnNewLineForFunctions"), isTypeScriptDeclWithBlockContext, isBeforeMultilineBlockContext], 8 /* InsertNewLine */, 1 /* CanDeleteNewLines */), rule("SpaceAfterTypeAssertion", 32 /* GreaterThanToken */, anyToken, [isOptionEnabled("insertSpaceAfterTypeAssertion"), isNonJsxSameLineTokenContext, isTypeAssertionContext], 4 /* InsertSpace */), rule("NoSpaceAfterTypeAssertion", 32 /* GreaterThanToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterTypeAssertion"), isNonJsxSameLineTokenContext, isTypeAssertionContext], 16 /* DeleteSpace */), rule("SpaceBeforeTypeAnnotation", anyToken, [58 /* QuestionToken */, 59 /* ColonToken */], [isOptionEnabled("insertSpaceBeforeTypeAnnotation"), isNonJsxSameLineTokenContext, isTypeAnnotationContext], 4 /* InsertSpace */), rule("NoSpaceBeforeTypeAnnotation", anyToken, [58 /* QuestionToken */, 59 /* ColonToken */], [isOptionDisabledOrUndefined("insertSpaceBeforeTypeAnnotation"), isNonJsxSameLineTokenContext, isTypeAnnotationContext], 16 /* DeleteSpace */), rule("NoOptionalSemicolon", 27 /* SemicolonToken */, anyTokenIncludingEOF, [optionEquals("semicolons", "remove" /* Remove */), isSemicolonDeletionContext], 32 /* DeleteToken */), rule("OptionalSemicolon", anyToken, anyTokenIncludingEOF, [optionEquals("semicolons", "insert" /* Insert */), isSemicolonInsertionContext], 64 /* InsertTrailingSemicolon */)]; + const lowPriorityCommonRules = [ - // Space after keyword but not before ; or : or ? - rule("NoSpaceBeforeSemicolon", anyToken, 27 /* SemicolonToken */, [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */), - rule("SpaceBeforeOpenBraceInControl", controlOpenBraceLeftTokenRange, 19 /* OpenBraceToken */, [isOptionDisabledOrUndefinedOrTokensOnSameLine("placeOpenBraceOnNewLineForControlBlocks"), isControlDeclContext, isNotFormatOnEnter, isSameLineTokenOrBeforeBlockContext], 4 /* InsertSpace */, 1 /* CanDeleteNewLines */), - rule("SpaceBeforeOpenBraceInFunction", functionOpenBraceLeftTokenRange, 19 /* OpenBraceToken */, [isOptionDisabledOrUndefinedOrTokensOnSameLine("placeOpenBraceOnNewLineForFunctions"), isFunctionDeclContext, isBeforeBlockContext, isNotFormatOnEnter, isSameLineTokenOrBeforeBlockContext], 4 /* InsertSpace */, 1 /* CanDeleteNewLines */), - rule("SpaceBeforeOpenBraceInTypeScriptDeclWithBlock", typeScriptOpenBraceLeftTokenRange, 19 /* OpenBraceToken */, [isOptionDisabledOrUndefinedOrTokensOnSameLine("placeOpenBraceOnNewLineForFunctions"), isTypeScriptDeclWithBlockContext, isNotFormatOnEnter, isSameLineTokenOrBeforeBlockContext], 4 /* InsertSpace */, 1 /* CanDeleteNewLines */), - rule("NoSpaceBeforeComma", anyToken, 28 /* CommaToken */, [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */), - // No space before and after indexer `x[]` - rule("NoSpaceBeforeOpenBracket", anyTokenExcept(134 /* AsyncKeyword */, 84 /* CaseKeyword */), 23 /* OpenBracketToken */, [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */), - rule("NoSpaceAfterCloseBracket", 24 /* CloseBracketToken */, anyToken, [isNonJsxSameLineTokenContext, isNotBeforeBlockInFunctionDeclarationContext], 16 /* DeleteSpace */), - rule("SpaceAfterSemicolon", 27 /* SemicolonToken */, anyToken, [isNonJsxSameLineTokenContext], 4 /* InsertSpace */), - // Remove extra space between for and await - rule("SpaceBetweenForAndAwaitKeyword", 99 /* ForKeyword */, 135 /* AwaitKeyword */, [isNonJsxSameLineTokenContext], 4 /* InsertSpace */), - // Add a space between statements. All keywords except (do,else,case) has open/close parens after them. - // So, we have a rule to add a space for [),Any], [do,Any], [else,Any], and [case,Any] - rule( - "SpaceBetweenStatements", - [22 /* CloseParenToken */, 92 /* DoKeyword */, 93 /* ElseKeyword */, 84 /* CaseKeyword */], - anyToken, - [isNonJsxSameLineTokenContext, isNonJsxElementOrFragmentContext, isNotForContext], - 4 /* InsertSpace */ - ), - // This low-pri rule takes care of "try {", "catch {" and "finally {" in case the rule SpaceBeforeOpenBraceInControl didn't execute on FormatOnEnter. - rule("SpaceAfterTryCatchFinally", [113 /* TryKeyword */, 85 /* CatchKeyword */, 98 /* FinallyKeyword */], 19 /* OpenBraceToken */, [isNonJsxSameLineTokenContext], 4 /* InsertSpace */) - ]; - return [ - ...highPriorityCommonRules, - ...userConfigurableRules, - ...lowPriorityCommonRules - ]; + // Space after keyword but not before ; or : or ? + rule("NoSpaceBeforeSemicolon", anyToken, 27 /* SemicolonToken */, [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */), rule("SpaceBeforeOpenBraceInControl", controlOpenBraceLeftTokenRange, 19 /* OpenBraceToken */, [isOptionDisabledOrUndefinedOrTokensOnSameLine("placeOpenBraceOnNewLineForControlBlocks"), isControlDeclContext, isNotFormatOnEnter, isSameLineTokenOrBeforeBlockContext], 4 /* InsertSpace */, 1 /* CanDeleteNewLines */), rule("SpaceBeforeOpenBraceInFunction", functionOpenBraceLeftTokenRange, 19 /* OpenBraceToken */, [isOptionDisabledOrUndefinedOrTokensOnSameLine("placeOpenBraceOnNewLineForFunctions"), isFunctionDeclContext, isBeforeBlockContext, isNotFormatOnEnter, isSameLineTokenOrBeforeBlockContext], 4 /* InsertSpace */, 1 /* CanDeleteNewLines */), rule("SpaceBeforeOpenBraceInTypeScriptDeclWithBlock", typeScriptOpenBraceLeftTokenRange, 19 /* OpenBraceToken */, [isOptionDisabledOrUndefinedOrTokensOnSameLine("placeOpenBraceOnNewLineForFunctions"), isTypeScriptDeclWithBlockContext, isNotFormatOnEnter, isSameLineTokenOrBeforeBlockContext], 4 /* InsertSpace */, 1 /* CanDeleteNewLines */), rule("NoSpaceBeforeComma", anyToken, 28 /* CommaToken */, [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */), + // No space before and after indexer `x[]` + rule("NoSpaceBeforeOpenBracket", anyTokenExcept(134 /* AsyncKeyword */, 84 /* CaseKeyword */), 23 /* OpenBracketToken */, [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */), rule("NoSpaceAfterCloseBracket", 24 /* CloseBracketToken */, anyToken, [isNonJsxSameLineTokenContext, isNotBeforeBlockInFunctionDeclarationContext], 16 /* DeleteSpace */), rule("SpaceAfterSemicolon", 27 /* SemicolonToken */, anyToken, [isNonJsxSameLineTokenContext], 4 /* InsertSpace */), + // Remove extra space between for and await + rule("SpaceBetweenForAndAwaitKeyword", 99 /* ForKeyword */, 135 /* AwaitKeyword */, [isNonJsxSameLineTokenContext], 4 /* InsertSpace */), + // Add a space between statements. All keywords except (do,else,case) has open/close parens after them. + // So, we have a rule to add a space for [),Any], [do,Any], [else,Any], and [case,Any] + rule("SpaceBetweenStatements", [22 /* CloseParenToken */, 92 /* DoKeyword */, 93 /* ElseKeyword */, 84 /* CaseKeyword */], anyToken, [isNonJsxSameLineTokenContext, isNonJsxElementOrFragmentContext, isNotForContext], 4 /* InsertSpace */), + // This low-pri rule takes care of "try {", "catch {" and "finally {" in case the rule SpaceBeforeOpenBraceInControl didn't execute on FormatOnEnter. + rule("SpaceAfterTryCatchFinally", [113 /* TryKeyword */, 85 /* CatchKeyword */, 98 /* FinallyKeyword */], 19 /* OpenBraceToken */, [isNonJsxSameLineTokenContext], 4 /* InsertSpace */)]; + + return [...highPriorityCommonRules, ...userConfigurableRules, ...lowPriorityCommonRules]; } function rule(debugName, left, right, context, action, flags = 0 /* None */) { - return { leftTokenRange: toTokenRange(left), rightTokenRange: toTokenRange(right), rule: { debugName, context, action, flags } }; + return { + leftTokenRange: toTokenRange(left), + rightTokenRange: toTokenRange(right), + rule: { + debugName, + context, + action, + flags + } + }; } function tokenRangeFrom(tokens) { - return { tokens, isSpecific: true }; + return { + tokens, + isSpecific: true + }; } function toTokenRange(arg) { return typeof arg === "number" ? tokenRangeFrom([arg]) : isArray(arg) ? tokenRangeFrom(arg) : arg; @@ -169902,26 +154121,27 @@ ${options.prefix}` : "\n" : options.prefix return tokenRangeFrom(tokens); } function optionEquals(optionName, optionValue) { - return (context) => context.options && context.options[optionName] === optionValue; + return context => context.options && context.options[optionName] === optionValue; } function isOptionEnabled(optionName) { - return (context) => context.options && hasProperty(context.options, optionName) && !!context.options[optionName]; + return context => context.options && hasProperty(context.options, optionName) && !!context.options[optionName]; } function isOptionDisabled(optionName) { - return (context) => context.options && hasProperty(context.options, optionName) && !context.options[optionName]; + return context => context.options && hasProperty(context.options, optionName) && !context.options[optionName]; } function isOptionDisabledOrUndefined(optionName) { - return (context) => !context.options || !hasProperty(context.options, optionName) || !context.options[optionName]; + return context => !context.options || !hasProperty(context.options, optionName) || !context.options[optionName]; } function isOptionDisabledOrUndefinedOrTokensOnSameLine(optionName) { - return (context) => !context.options || !hasProperty(context.options, optionName) || !context.options[optionName] || context.TokensAreOnSameLine(); + return context => !context.options || !hasProperty(context.options, optionName) || !context.options[optionName] || context.TokensAreOnSameLine(); } function isOptionEnabledOrUndefined(optionName) { - return (context) => !context.options || !hasProperty(context.options, optionName) || !!context.options[optionName]; + return context => !context.options || !hasProperty(context.options, optionName) || !!context.options[optionName]; } function isForContext(context) { return context.contextNode.kind === 248 /* ForStatement */; } + function isNotForContext(context) { return !isForContext(context); } @@ -169955,6 +154175,7 @@ ${options.prefix}` : "\n" : options.prefix case 250 /* ForOfStatement */: return context.currentTokenSpan.kind === 165 /* OfKeyword */ || context.nextTokenSpan.kind === 165 /* OfKeyword */; } + return false; } function isNotBinaryOpContext(context) { @@ -169976,6 +154197,7 @@ ${options.prefix}` : "\n" : options.prefix function isConditionalOperatorContext(context) { return context.contextNode.kind === 227 /* ConditionalExpression */ || context.contextNode.kind === 194 /* ConditionalType */; } + function isSameLineTokenOrBeforeBlockContext(context) { return context.TokensAreOnSameLine() || isBeforeBlockContext(context); } @@ -170032,6 +154254,7 @@ ${options.prefix}` : "\n" : options.prefix function isFunctionDeclarationOrFunctionExpressionContext(context) { return context.contextNode.kind === 262 /* FunctionDeclaration */ || context.contextNode.kind === 218 /* FunctionExpression */; } + function isTypeScriptDeclWithBlockContext(context) { return nodeIsTypeScriptDeclWithBlockContext(context.contextNode); } @@ -170060,12 +154283,13 @@ ${options.prefix}` : "\n" : options.prefix case 268 /* ModuleBlock */: case 255 /* SwitchStatement */: return true; - case 241 /* Block */: { - const blockParent = context.currentTokenParent.parent; - if (!blockParent || blockParent.kind !== 219 /* ArrowFunction */ && blockParent.kind !== 218 /* FunctionExpression */) { - return true; + case 241 /* Block */: + { + const blockParent = context.currentTokenParent.parent; + if (!blockParent || blockParent.kind !== 219 /* ArrowFunction */ && blockParent.kind !== 218 /* FunctionExpression */) { + return true; + } } - } } return false; } @@ -170089,57 +154313,74 @@ ${options.prefix}` : "\n" : options.prefix function isObjectContext(context) { return context.contextNode.kind === 210 /* ObjectLiteralExpression */; } + function isFunctionCallContext(context) { return context.contextNode.kind === 213 /* CallExpression */; } + function isNewContext(context) { return context.contextNode.kind === 214 /* NewExpression */; } + function isFunctionCallOrNewContext(context) { return isFunctionCallContext(context) || isNewContext(context); } function isPreviousTokenNotComma(context) { return context.currentTokenSpan.kind !== 28 /* CommaToken */; } + function isNextTokenNotCloseBracket(context) { return context.nextTokenSpan.kind !== 24 /* CloseBracketToken */; } + function isNextTokenNotCloseParen(context) { return context.nextTokenSpan.kind !== 22 /* CloseParenToken */; } + function isArrowFunctionContext(context) { return context.contextNode.kind === 219 /* ArrowFunction */; } + function isImportTypeContext(context) { return context.contextNode.kind === 205 /* ImportType */; } + function isNonJsxSameLineTokenContext(context) { return context.TokensAreOnSameLine() && context.contextNode.kind !== 12 /* JsxText */; } + function isNonJsxTextContext(context) { return context.contextNode.kind !== 12 /* JsxText */; } + function isNonJsxElementOrFragmentContext(context) { return context.contextNode.kind !== 284 /* JsxElement */ && context.contextNode.kind !== 288 /* JsxFragment */; } + function isJsxExpressionContext(context) { return context.contextNode.kind === 294 /* JsxExpression */ || context.contextNode.kind === 293 /* JsxSpreadAttribute */; } + function isNextTokenParentJsxAttribute(context) { return context.nextTokenParent.kind === 291 /* JsxAttribute */ || context.nextTokenParent.kind === 295 /* JsxNamespacedName */ && context.nextTokenParent.parent.kind === 291 /* JsxAttribute */; } + function isJsxAttributeContext(context) { return context.contextNode.kind === 291 /* JsxAttribute */; } + function isNextTokenParentNotJsxNamespacedName(context) { return context.nextTokenParent.kind !== 295 /* JsxNamespacedName */; } + function isNextTokenParentJsxNamespacedName(context) { return context.nextTokenParent.kind === 295 /* JsxNamespacedName */; } + function isJsxSelfClosingElementContext(context) { return context.contextNode.kind === 285 /* JsxSelfClosingElement */; } + function isNotBeforeBlockInFunctionDeclarationContext(context) { return !isFunctionDeclContext(context) && !isBeforeBlockContext(context); } @@ -170152,21 +154393,26 @@ ${options.prefix}` : "\n" : options.prefix } return node && node.kind === 170 /* Decorator */; } + function isStartOfVariableDeclarationList(context) { return context.currentTokenParent.kind === 261 /* VariableDeclarationList */ && context.currentTokenParent.getStart(context.sourceFile) === context.currentTokenSpan.pos; } function isNotFormatOnEnter(context) { return context.formattingRequestKind !== 2 /* FormatOnEnter */; } + function isModuleDeclContext(context) { return context.contextNode.kind === 267 /* ModuleDeclaration */; } + function isObjectTypeContext(context) { return context.contextNode.kind === 187 /* TypeLiteral */; } + function isConstructorSignatureContext(context) { return context.contextNode.kind === 180 /* ConstructSignature */; } + function isTypeArgumentOrParameterOrAssertion(token, parent2) { if (token.kind !== 30 /* LessThanToken */ && token.kind !== 32 /* GreaterThanToken */) { return false; @@ -170199,18 +154445,21 @@ ${options.prefix}` : "\n" : options.prefix function isTypeAssertionContext(context) { return context.contextNode.kind === 216 /* TypeAssertionExpression */; } + function isNonTypeAssertionContext(context) { return !isTypeAssertionContext(context); } function isVoidOpContext(context) { return context.currentTokenSpan.kind === 116 /* VoidKeyword */ && context.currentTokenParent.kind === 222 /* VoidExpression */; } + function isYieldOrYieldStarWithOperand(context) { return context.contextNode.kind === 229 /* YieldExpression */ && context.contextNode.expression !== void 0; } function isNonNullAssertionContext(context) { return context.contextNode.kind === 235 /* NonNullExpression */; } + function isNotStatementConditionContext(context) { return !isStatementConditionContext(context); } @@ -170231,11 +154480,7 @@ ${options.prefix}` : "\n" : options.prefix let nextTokenKind = context.nextTokenSpan.kind; let nextTokenStart = context.nextTokenSpan.pos; if (isTrivia(nextTokenKind)) { - const nextRealToken = context.nextTokenParent === context.currentTokenParent ? findNextToken( - context.currentTokenParent, - findAncestor(context.currentTokenParent, (a) => !a.parent), - context.sourceFile - ) : context.nextTokenParent.getFirstToken(context.sourceFile); + const nextRealToken = context.nextTokenParent === context.currentTokenParent ? findNextToken(context.currentTokenParent, findAncestor(context.currentTokenParent, a => !a.parent), context.sourceFile) : context.nextTokenParent.getFirstToken(context.sourceFile); if (!nextRealToken) { return true; } @@ -170247,17 +154492,20 @@ ${options.prefix}` : "\n" : options.prefix if (startLine === endLine) { return nextTokenKind === 20 /* CloseBraceToken */ || nextTokenKind === 1 /* EndOfFileToken */; } + if (nextTokenKind === 240 /* SemicolonClassElement */ || nextTokenKind === 27 /* SemicolonToken */) { return false; } if (context.contextNode.kind === 264 /* InterfaceDeclaration */ || context.contextNode.kind === 265 /* TypeAliasDeclaration */) { return !isPropertySignature(context.currentTokenParent) || !!context.currentTokenParent.type || nextTokenKind !== 21 /* OpenParenToken */; } + if (isPropertyDeclaration(context.currentTokenParent)) { return !context.currentTokenParent.initializer; } return context.currentTokenParent.kind !== 248 /* ForStatement */ && context.currentTokenParent.kind !== 242 /* EmptyStatement */ && context.currentTokenParent.kind !== 240 /* SemicolonClassElement */ && nextTokenKind !== 23 /* OpenBracketToken */ && nextTokenKind !== 21 /* OpenParenToken */ && nextTokenKind !== 40 /* PlusToken */ && nextTokenKind !== 41 /* MinusToken */ && nextTokenKind !== 44 /* SlashToken */ && nextTokenKind !== 14 /* RegularExpressionLiteral */ && nextTokenKind !== 28 /* CommaToken */ && nextTokenKind !== 228 /* TemplateExpression */ && nextTokenKind !== 16 /* TemplateHead */ && nextTokenKind !== 15 /* NoSubstitutionTemplateLiteral */ && nextTokenKind !== 25 /* DotToken */; } + function isSemicolonInsertionContext(context) { return positionIsASICandidate(context.currentTokenSpan.end, context.currentTokenParent, context.sourceFile); } @@ -170267,6 +154515,7 @@ ${options.prefix}` : "\n" : options.prefix var init_rules = __esm({ "src/services/formatting/rules.ts"() { "use strict"; + init_ts4(); init_ts_formatting(); } @@ -170274,7 +154523,11 @@ ${options.prefix}` : "\n" : options.prefix // src/services/formatting/rulesMap.ts function getFormatContext(options, host) { - return { options, getRules: getRulesMap(), host }; + return { + options, + getRules: getRulesMap(), + host + }; } function getRulesMap() { if (rulesMapCache === void 0) { @@ -170287,27 +154540,31 @@ ${options.prefix}` : "\n" : options.prefix if (ruleAction & 1 /* StopProcessingSpaceActions */) { mask2 |= 28 /* ModifySpaceAction */; } + if (ruleAction & 2 /* StopProcessingTokenActions */) { mask2 |= 96 /* ModifyTokenAction */; } + if (ruleAction & 28 /* ModifySpaceAction */) { mask2 |= 28 /* ModifySpaceAction */; } + if (ruleAction & 96 /* ModifyTokenAction */) { mask2 |= 96 /* ModifyTokenAction */; } + return mask2; } function createRulesMap(rules) { const map2 = buildMap(rules); - return (context) => { + return context => { const bucket = map2[getRuleBucketIndex(context.currentTokenSpan.kind, context.nextTokenSpan.kind)]; if (bucket) { const rules2 = []; let ruleActionMask = 0; for (const rule2 of bucket) { const acceptRuleActions = ~getRuleActionExclusion(ruleActionMask); - if (rule2.action & acceptRuleActions && every(rule2.context, (c) => c(context))) { + if (rule2.action & acceptRuleActions && every(rule2.context, c => c(context))) { rules2.push(rule2); ruleActionMask |= rule2.action; } @@ -170363,12 +154620,13 @@ ${options.prefix}` : "\n" : options.prefix var init_rulesMap = __esm({ "src/services/formatting/rulesMap.ts"() { "use strict"; + init_ts4(); init_ts_formatting(); maskBitSize = 5; mask = 31; mapRowLength = 165 /* LastToken */ + 1; - RulesPosition = ((RulesPosition2) => { + RulesPosition = (RulesPosition2 => { RulesPosition2[RulesPosition2["StopRulesSpecific"] = 0] = "StopRulesSpecific"; RulesPosition2[RulesPosition2["StopRulesAny"] = maskBitSize * 1] = "StopRulesAny"; RulesPosition2[RulesPosition2["ContextRulesSpecific"] = maskBitSize * 2] = "ContextRulesSpecific"; @@ -170382,7 +154640,11 @@ ${options.prefix}` : "\n" : options.prefix // src/services/formatting/formatting.ts function createTextRangeWithKind(pos, end, kind) { - const textRangeWithKind = { pos, end, kind }; + const textRangeWithKind = { + pos, + end, + kind + }; if (Debug.isDebugging) { Object.defineProperty(textRangeWithKind, "__debugKind", { get: () => Debug.formatSyntaxKind(kind) @@ -170410,10 +154672,12 @@ ${options.prefix}` : "\n" : options.prefix }; return formatSpan(span, sourceFile, formatContext, 2 /* FormatOnEnter */); } + function formatOnSemicolon(position, sourceFile, formatContext) { const semicolon = findImmediatelyPrecedingTokenOfKind(position, 27 /* SemicolonToken */, sourceFile); return formatNodeLines(findOutermostNodeWithinListLevel(semicolon), sourceFile, formatContext, 3 /* FormatOnSemicolon */); } + function formatOnOpeningCurly(position, sourceFile, formatContext) { const openingCurly = findImmediatelyPrecedingTokenOfKind(position, 19 /* OpenBraceToken */, sourceFile); if (!openingCurly) { @@ -170428,10 +154692,12 @@ ${options.prefix}` : "\n" : options.prefix }; return formatSpan(textRange, sourceFile, formatContext, 4 /* FormatOnOpeningCurlyBrace */); } + function formatOnClosingCurly(position, sourceFile, formatContext) { const precedingToken = findImmediatelyPrecedingTokenOfKind(position, 20 /* CloseBraceToken */, sourceFile); return formatNodeLines(findOutermostNodeWithinListLevel(precedingToken), sourceFile, formatContext, 5 /* FormatOnClosingCurlyBrace */); } + function formatDocument(sourceFile, formatContext) { const span = { pos: 0, @@ -170439,6 +154705,7 @@ ${options.prefix}` : "\n" : options.prefix }; return formatSpan(span, sourceFile, formatContext, 0 /* FormatDocument */); } + function formatSelection(start, end, sourceFile, formatContext) { const span = { pos: getLineStartPositionForPosition(start, sourceFile), @@ -170446,6 +154713,7 @@ ${options.prefix}` : "\n" : options.prefix }; return formatSpan(span, sourceFile, formatContext, 1 /* FormatSelection */); } + function findImmediatelyPrecedingTokenOfKind(end, expectedTokenKind, sourceFile) { const precedingToken = findPrecedingToken(end, sourceFile); return precedingToken && precedingToken.kind === expectedTokenKind && end === precedingToken.getEnd() ? precedingToken : void 0; @@ -170477,7 +154745,7 @@ ${options.prefix}` : "\n" : options.prefix function findEnclosingNode(range, sourceFile) { return find2(sourceFile); function find2(n) { - const candidate = forEachChild(n, (c) => startEndContainsRange(c.getStart(sourceFile), c.end, range) && c); + const candidate = forEachChild(n, c => startEndContainsRange(c.getStart(sourceFile), c.end, range) && c); if (candidate) { const result = find2(candidate); if (result) { @@ -170491,12 +154759,12 @@ ${options.prefix}` : "\n" : options.prefix if (!errors.length) { return rangeHasNoErrors; } - const sorted = errors.filter((d) => rangeOverlapsWithStartEnd(originalRange, d.start, d.start + d.length)).sort((e1, e2) => e1.start - e2.start); + const sorted = errors.filter(d => rangeOverlapsWithStartEnd(originalRange, d.start, d.start + d.length)).sort((e1, e2) => e1.start - e2.start); if (!sorted.length) { return rangeHasNoErrors; } let index = 0; - return (r) => { + return r => { while (true) { if (index >= sorted.length) { return false; @@ -170547,19 +154815,13 @@ ${options.prefix}` : "\n" : options.prefix return 0; } function formatNodeGivenIndentation(node, sourceFileLike, languageVariant, initialIndentation, delta, formatContext) { - const range = { pos: node.pos, end: node.end }; - return getFormattingScanner(sourceFileLike.text, languageVariant, range.pos, range.end, (scanner2) => formatSpanWorker( - range, - node, - initialIndentation, - delta, - scanner2, - formatContext, - 1 /* FormatSelection */, - (_) => false, - // assume that node does not have any errors - sourceFileLike - )); + const range = { + pos: node.pos, + end: node.end + }; + return getFormattingScanner(sourceFileLike.text, languageVariant, range.pos, range.end, scanner2 => formatSpanWorker(range, node, initialIndentation, delta, scanner2, formatContext, 1 /* FormatSelection */, _ => false, + // assume that node does not have any errors + sourceFileLike)); } function formatNodeLines(node, sourceFile, formatContext, requestKind) { if (!node) { @@ -170573,25 +154835,13 @@ ${options.prefix}` : "\n" : options.prefix } function formatSpan(originalRange, sourceFile, formatContext, requestKind) { const enclosingNode = findEnclosingNode(originalRange, sourceFile); - return getFormattingScanner( - sourceFile.text, - sourceFile.languageVariant, - getScanStartPosition(enclosingNode, originalRange, sourceFile), - originalRange.end, - (scanner2) => formatSpanWorker( - originalRange, - enclosingNode, - SmartIndenter.getIndentationForNode(enclosingNode, originalRange, sourceFile, formatContext.options), - getOwnOrInheritedDelta(enclosingNode, formatContext.options, sourceFile), - scanner2, - formatContext, - requestKind, - prepareRangeContainsErrorFunction(sourceFile.parseDiagnostics, originalRange), - sourceFile - ) - ); + return getFormattingScanner(sourceFile.text, sourceFile.languageVariant, getScanStartPosition(enclosingNode, originalRange, sourceFile), originalRange.end, scanner2 => formatSpanWorker(originalRange, enclosingNode, SmartIndenter.getIndentationForNode(enclosingNode, originalRange, sourceFile, formatContext.options), getOwnOrInheritedDelta(enclosingNode, formatContext.options, sourceFile), scanner2, formatContext, requestKind, prepareRangeContainsErrorFunction(sourceFile.parseDiagnostics, originalRange), sourceFile)); } - function formatSpanWorker(originalRange, enclosingNode, initialIndentation, delta, formattingScanner, { options, getRules, host }, requestKind, rangeContainsError, sourceFile) { + function formatSpanWorker(originalRange, enclosingNode, initialIndentation, delta, formattingScanner, { + options, + getRules, + host + }, requestKind, rangeContainsError, sourceFile) { var _a; const formattingContext = new FormattingContext(sourceFile, requestKind, options); let previousRangeTriviaEnd; @@ -170612,37 +154862,16 @@ ${options.prefix}` : "\n" : options.prefix } const remainingTrivia = formattingScanner.getCurrentLeadingTrivia(); if (remainingTrivia) { - const indentation = SmartIndenter.nodeWillIndentChild( - options, - enclosingNode, - /*child*/ - void 0, - sourceFile, - /*indentByDefault*/ - false - ) ? initialIndentation + options.indentSize : initialIndentation; - indentTriviaItems( - remainingTrivia, - indentation, - /*indentNextTokenOrTrivia*/ - true, - (item) => { - processRange( - item, - sourceFile.getLineAndCharacterOfPosition(item.pos), - enclosingNode, - enclosingNode, - /*dynamicIndentation*/ - void 0 - ); - insertIndentation( - item.pos, - indentation, - /*lineAdded*/ - false - ); - } - ); + const indentation = SmartIndenter.nodeWillIndentChild(options, enclosingNode, /*child*/ + void 0, sourceFile, /*indentByDefault*/ + false) ? initialIndentation + options.indentSize : initialIndentation; + indentTriviaItems(remainingTrivia, indentation, /*indentNextTokenOrTrivia*/ + true, item => { + processRange(item, sourceFile.getLineAndCharacterOfPosition(item.pos), enclosingNode, enclosingNode, /*dynamicIndentation*/ + void 0); + insertIndentation(item.pos, indentation, /*lineAdded*/ + false); + }); if (options.trimTrailingWhitespace !== false) { trimTrailingWhitespacesForRemainingRange(remainingTrivia); } @@ -170651,17 +154880,8 @@ ${options.prefix}` : "\n" : options.prefix const tokenInfo = formattingScanner.isOnEOF() ? formattingScanner.readEOFTokenRange() : formattingScanner.isOnToken() ? formattingScanner.readTokenInfo(enclosingNode).token : void 0; if (tokenInfo && tokenInfo.pos === previousRangeTriviaEnd) { const parent2 = ((_a = findPrecedingToken(tokenInfo.end, sourceFile, enclosingNode)) == null ? void 0 : _a.parent) || previousParent; - processPair( - tokenInfo, - sourceFile.getLineAndCharacterOfPosition(tokenInfo.pos).line, - parent2, - previousRange, - previousRangeStartLine, - previousParent, - parent2, - /*dynamicIndentation*/ - void 0 - ); + processPair(tokenInfo, sourceFile.getLineAndCharacterOfPosition(tokenInfo.pos).line, parent2, previousRange, previousRangeStartLine, previousParent, parent2, /*dynamicIndentation*/ + void 0); } } return edits; @@ -170681,6 +154901,7 @@ ${options.prefix}` : "\n" : options.prefix } return -1 /* Unknown */; } + function computeIndentation(node, startLine, inheritedIndentation, parent2, parentDynamicIndentation, effectiveParentStartLine) { const delta2 = SmartIndenter.shouldIndentChildNode(options, node) ? options.indentSize : 0; if (effectiveParentStartLine === startLine) { @@ -170690,21 +154911,32 @@ ${options.prefix}` : "\n" : options.prefix }; } else if (inheritedIndentation === -1 /* Unknown */) { if (node.kind === 21 /* OpenParenToken */ && startLine === lastIndentedLine) { - return { indentation: indentationOnLastIndentedLine, delta: parentDynamicIndentation.getDelta(node) }; + return { + indentation: indentationOnLastIndentedLine, + delta: parentDynamicIndentation.getDelta(node) + }; } else if (SmartIndenter.childStartsOnTheSameLineWithElseInIfStatement(parent2, node, startLine, sourceFile) || SmartIndenter.childIsUnindentedBranchOfConditionalExpression(parent2, node, startLine, sourceFile) || SmartIndenter.argumentStartsOnSameLineAsPreviousArgument(parent2, node, startLine, sourceFile)) { - return { indentation: parentDynamicIndentation.getIndentation(), delta: delta2 }; + return { + indentation: parentDynamicIndentation.getIndentation(), + delta: delta2 + }; } else { - return { indentation: parentDynamicIndentation.getIndentation() + parentDynamicIndentation.getDelta(node), delta: delta2 }; + return { + indentation: parentDynamicIndentation.getIndentation() + parentDynamicIndentation.getDelta(node), + delta: delta2 + }; } } else { - return { indentation: inheritedIndentation, delta: delta2 }; + return { + indentation: inheritedIndentation, + delta: delta2 + }; } } 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 */: @@ -170723,6 +154955,7 @@ ${options.prefix}` : "\n" : options.prefix if (node.asteriskToken) { return 42 /* AsteriskToken */; } + case 172 /* PropertyDeclaration */: case 169 /* Parameter */: const name = getNameOfDeclaration(node); @@ -170790,14 +155023,8 @@ ${options.prefix}` : "\n" : options.prefix return nodeStartLine !== line && !(hasDecorators(node) && kind === getFirstNonDecoratorTokenOfNode(node)); } function getDelta(child) { - return SmartIndenter.nodeWillIndentChild( - options, - node, - child, - sourceFile, - /*indentByDefault*/ - true - ) ? delta2 : 0; + return SmartIndenter.nodeWillIndentChild(options, node, child, sourceFile, /*indentByDefault*/ + true) ? delta2 : 0; } } function processNode(node, contextNode, nodeStartLine, undecoratedNodeStartLine, indentation, delta2) { @@ -170806,25 +155033,13 @@ ${options.prefix}` : "\n" : options.prefix } const nodeDynamicIndentation = getDynamicIndentation(node, nodeStartLine, indentation, delta2); let childContextNode = contextNode; - forEachChild( - node, - (child) => { - processChildNode( - child, - /*inheritedIndentation*/ - -1 /* Unknown */, - node, - nodeDynamicIndentation, - nodeStartLine, - undecoratedNodeStartLine, - /*isListItem*/ - false - ); - }, - (nodes) => { - processChildNodes(nodes, node, nodeStartLine, nodeDynamicIndentation); - } - ); + forEachChild(node, child => { + processChildNode(child, /*inheritedIndentation*/ + -1 /* Unknown */, node, nodeDynamicIndentation, nodeStartLine, undecoratedNodeStartLine, /*isListItem*/ + false); + }, nodes => { + processChildNodes(nodes, node, nodeStartLine, nodeDynamicIndentation); + }); while (formattingScanner.isOnToken() && formattingScanner.getTokenFullStart() < originalRange.end) { const tokenInfo = formattingScanner.readTokenInfo(node); if (tokenInfo.token.end > Math.min(node.end, originalRange.end)) { @@ -170928,18 +155143,9 @@ ${options.prefix}` : "\n" : options.prefix let inheritedIndentation = -1 /* Unknown */; for (let i = 0; i < nodes.length; i++) { const child = nodes[i]; - inheritedIndentation = processChildNode( - child, - inheritedIndentation, - node, - listDynamicIndentation, - startLine, - startLine, - /*isListItem*/ - true, - /*isFirstListItem*/ - i === 0 - ); + inheritedIndentation = processChildNode(child, inheritedIndentation, node, listDynamicIndentation, startLine, startLine, /*isListItem*/ + true, /*isFirstListItem*/ + i === 0); } const listEndToken = getCloseTokenForOpenToken(listStartToken); if (listEndToken !== 0 /* Unknown */ && formattingScanner.isOnToken() && formattingScanner.getTokenFullStart() < originalRange.end) { @@ -170949,14 +155155,8 @@ ${options.prefix}` : "\n" : options.prefix tokenInfo = formattingScanner.isOnToken() ? formattingScanner.readTokenInfo(parent2) : void 0; } if (tokenInfo && tokenInfo.token.kind === listEndToken && rangeContainsRange(parent2, tokenInfo.token)) { - consumeTokenAndAdvanceScanner( - tokenInfo, - parent2, - listDynamicIndentation, - parent2, - /*isListEndToken*/ - true - ); + consumeTokenAndAdvanceScanner(tokenInfo, parent2, listDynamicIndentation, parent2, /*isListEndToken*/ + true); } } } @@ -170983,6 +155183,7 @@ ${options.prefix}` : "\n" : options.prefix } } } + if (currentTokenInfo.trailingTrivia) { previousRangeTriviaEnd = last(currentTokenInfo.trailingTrivia).end; processTrivia(currentTokenInfo.trailingTrivia, parent2, childContextNode, dynamicIndentation); @@ -170992,12 +155193,8 @@ ${options.prefix}` : "\n" : options.prefix let indentNextTokenOrTrivia = true; if (currentTokenInfo.leadingTrivia) { const commentIndentation = dynamicIndentation.getIndentationForComment(currentTokenInfo.token.kind, tokenIndentation, container); - indentNextTokenOrTrivia = indentTriviaItems(currentTokenInfo.leadingTrivia, commentIndentation, indentNextTokenOrTrivia, (item) => insertIndentation( - item.pos, - commentIndentation, - /*lineAdded*/ - false - )); + indentNextTokenOrTrivia = indentTriviaItems(currentTokenInfo.leadingTrivia, commentIndentation, indentNextTokenOrTrivia, item => insertIndentation(item.pos, commentIndentation, /*lineAdded*/ + false)); } if (tokenIndentation !== -1 /* Unknown */ && indentNextTokenOrTrivia) { insertIndentation(currentTokenInfo.token.pos, tokenIndentation, lineAction === 1 /* LineAdded */); @@ -171015,12 +155212,8 @@ ${options.prefix}` : "\n" : options.prefix switch (triviaItem.kind) { case 3 /* MultiLineCommentTrivia */: if (triviaInRange) { - indentMultilineComment( - triviaItem, - commentIndentation, - /*firstLineIsIndented*/ - !indentNextTokenOrTrivia - ); + indentMultilineComment(triviaItem, commentIndentation, /*firstLineIsIndented*/ + !indentNextTokenOrTrivia); } indentNextTokenOrTrivia = false; break; @@ -171068,37 +155261,33 @@ ${options.prefix}` : "\n" : options.prefix let trimTrailingWhitespaces = formattingContext.options.trimTrailingWhitespace !== false; let lineAction = 0 /* None */; if (rules) { - forEachRight(rules, (rule2) => { + forEachRight(rules, rule2 => { lineAction = applyRuleEdits(rule2, previousItem, previousStartLine, currentItem, currentStartLine); if (dynamicIndentation) { switch (lineAction) { case 2 /* LineRemoved */: if (currentParent.getStart(sourceFile) === currentItem.pos) { - dynamicIndentation.recomputeIndentation( - /*lineAddedByFormatting*/ - false, - contextNode - ); + dynamicIndentation.recomputeIndentation( /*lineAddedByFormatting*/ + false, contextNode); } break; case 1 /* LineAdded */: if (currentParent.getStart(sourceFile) === currentItem.pos) { - dynamicIndentation.recomputeIndentation( - /*lineAddedByFormatting*/ - true, - contextNode - ); + dynamicIndentation.recomputeIndentation( /*lineAddedByFormatting*/ + true, contextNode); } break; default: Debug.assert(lineAction === 0 /* None */); } } + trimTrailingWhitespaces = trimTrailingWhitespaces && !(rule2.action & 16 /* DeleteSpace */) && rule2.flags !== 1 /* CanDeleteNewLines */; }); } else { trimTrailingWhitespaces = trimTrailingWhitespaces && currentItem.kind !== 1 /* EndOfFileToken */; } + if (currentStartLine !== previousStartLine && trimTrailingWhitespaces) { trimTrailingWhitespacesForLines(previousStartLine, currentStartLine, previousItem); } @@ -171135,12 +155324,8 @@ ${options.prefix}` : "\n" : options.prefix const endLine = sourceFile.getLineAndCharacterOfPosition(commentRange.end).line; if (startLine === endLine) { if (!firstLineIsIndented) { - insertIndentation( - commentRange.pos, - indentation, - /*lineAdded*/ - false - ); + insertIndentation(commentRange.pos, indentation, /*lineAdded*/ + false); } return; } @@ -171148,14 +155333,19 @@ ${options.prefix}` : "\n" : options.prefix let startPos = commentRange.pos; for (let line = startLine; line < endLine; line++) { const endOfLine = getEndLinePosition(line, sourceFile); - parts.push({ pos: startPos, end: endOfLine }); + parts.push({ + pos: startPos, + end: endOfLine + }); startPos = getStartPositionOfLine(line + 1, sourceFile); } if (indentFinalLine) { - parts.push({ pos: startPos, end: commentRange.end }); + 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; @@ -171244,6 +155434,7 @@ ${options.prefix}` : "\n" : options.prefix recordDelete(previousRange2.end, currentRange.pos - previousRange2.end); return onLaterLine ? 2 /* LineRemoved */ : 0 /* None */; } + break; case 32 /* DeleteToken */: recordDelete(previousRange2.pos, previousRange2.end - previousRange2.pos); @@ -171252,21 +155443,25 @@ ${options.prefix}` : "\n" : options.prefix if (rule2.flags !== 1 /* CanDeleteNewLines */ && previousStartLine !== currentStartLine) { return 0 /* None */; } + const lineDelta = currentStartLine - previousStartLine; if (lineDelta !== 1) { recordReplace(previousRange2.end, currentRange.pos - previousRange2.end, getNewLineOrDefaultFromHost(host, options)); return onLaterLine ? 0 /* None */ : 1 /* LineAdded */; } + break; case 4 /* InsertSpace */: if (rule2.flags !== 1 /* CanDeleteNewLines */ && previousStartLine !== currentStartLine) { return 0 /* None */; } + const posDelta = currentRange.pos - previousRange2.end; if (posDelta !== 1 || sourceFile.text.charCodeAt(previousRange2.end) !== 32 /* space */) { recordReplace(previousRange2.end, currentRange.pos - previousRange2.end, " "); return onLaterLine ? 2 /* LineRemoved */ : 0 /* None */; } + break; case 64 /* InsertTrailingSemicolon */: recordInsert(previousRange2.end, ";"); @@ -171274,10 +155469,10 @@ ${options.prefix}` : "\n" : options.prefix return 0 /* None */; } } + 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; @@ -171286,7 +155481,8 @@ ${options.prefix}` : "\n" : options.prefix const trailingRangesOfPreviousToken = precedingToken && getTrailingCommentRanges(sourceFile.text, precedingToken.end); const leadingCommentRangesOfNextToken = getLeadingCommentRangesOfNode(tokenAtPosition, sourceFile); const commentRanges = concatenate(trailingRangesOfPreviousToken, leadingCommentRangesOfNextToken); - return commentRanges && find(commentRanges, (range) => rangeContainsPositionExclusive(range, position) || // The end marker of a single-line comment does not include the newline character. + return commentRanges && find(commentRanges, range => rangeContainsPositionExclusive(range, position) || + // The end marker of a single-line comment does not include the newline character. // With caret at `^`, in the following case, we are inside a comment (^ denotes the cursor position): // // // asdf ^\n @@ -171320,6 +155516,7 @@ ${options.prefix}` : "\n" : options.prefix } else if (node.parameters === list) { return 21 /* OpenParenToken */; } + break; case 213 /* CallExpression */: case 214 /* NewExpression */: @@ -171328,6 +155525,7 @@ ${options.prefix}` : "\n" : options.prefix } else if (node.arguments === list) { return 21 /* OpenParenToken */; } + break; case 263 /* ClassDeclaration */: case 231 /* ClassExpression */: @@ -171336,6 +155534,7 @@ ${options.prefix}` : "\n" : options.prefix if (node.typeParameters === list) { return 30 /* LessThanToken */; } + break; case 183 /* TypeReference */: case 215 /* TaggedTemplateExpression */: @@ -171345,12 +155544,15 @@ ${options.prefix}` : "\n" : options.prefix if (node.typeArguments === list) { return 30 /* LessThanToken */; } + break; case 187 /* TypeLiteral */: return 19 /* OpenBraceToken */; } + return 0 /* Unknown */; } + function getCloseTokenForOpenToken(kind) { switch (kind) { case 21 /* OpenParenToken */: @@ -171360,12 +155562,17 @@ ${options.prefix}` : "\n" : options.prefix case 19 /* OpenBraceToken */: return 20 /* CloseBraceToken */; } + return 0 /* Unknown */; } + function getIndentationString(indentation, options) { - const resetInternedStrings = !internedSizes || (internedSizes.tabSize !== options.tabSize || internedSizes.indentSize !== options.indentSize); + const resetInternedStrings = !internedSizes || internedSizes.tabSize !== options.tabSize || internedSizes.indentSize !== options.indentSize; if (resetInternedStrings) { - internedSizes = { tabSize: options.tabSize, indentSize: options.indentSize }; + internedSizes = { + tabSize: options.tabSize, + indentSize: options.indentSize + }; internedTabsIndentation = internedSpacesIndentation = void 0; } if (!options.convertTabsToSpaces) { @@ -171401,6 +155608,7 @@ ${options.prefix}` : "\n" : options.prefix var init_formatting = __esm({ "src/services/formatting/formatting.ts"() { "use strict"; + init_ts4(); init_ts_formatting(); } @@ -171411,11 +155619,12 @@ ${options.prefix}` : "\n" : options.prefix var init_smartIndenter = __esm({ "src/services/formatting/smartIndenter.ts"() { "use strict"; + init_ts4(); init_ts_formatting(); - ((SmartIndenter2) => { + (SmartIndenter2 => { let Value; - ((Value2) => { + (Value2 => { Value2[Value2["Unknown"] = -1] = "Unknown"; })(Value || (Value = {})); function getIndentation(position, sourceFile, options, assumeNewLineBeforeCloseBrace = false) { @@ -171425,14 +155634,9 @@ ${options.prefix}` : "\n" : options.prefix if (options.indentStyle === 0 /* None */) { return 0; } - const precedingToken = findPrecedingToken( - position, - sourceFile, - /*startNode*/ - void 0, - /*excludeJsdoc*/ - true - ); + const precedingToken = findPrecedingToken(position, sourceFile, /*startNode*/ + void 0, /*excludeJsdoc*/ + true); const enclosingCommentRange = getRangeOfEnclosingComment(sourceFile, position, precedingToken || null); if (enclosingCommentRange && enclosingCommentRange.kind === 3 /* MultiLineCommentTrivia */) { return getCommentIndent(sourceFile, position, options, enclosingCommentRange); @@ -171473,7 +155677,10 @@ ${options.prefix}` : "\n" : options.prefix return findFirstNonWhitespaceColumn(getStartPositionOfLine(commentStartLine, sourceFile), position, sourceFile, options); } const startPositionOfLine = getStartPositionOfLine(previousLine, sourceFile); - const { column, character } = findFirstNonWhitespaceCharacterAndColumn(startPositionOfLine, position, sourceFile, options); + const { + column, + character + } = findFirstNonWhitespaceCharacterAndColumn(startPositionOfLine, position, sourceFile, options); if (column === 0) { return column; } @@ -171496,36 +155703,17 @@ ${options.prefix}` : "\n" : options.prefix let previous; let current = precedingToken; while (current) { - if (positionBelongsToNode(current, position, sourceFile) && shouldIndentChildNode( - options, - current, - previous, - sourceFile, - /*isNextChild*/ - true - )) { + if (positionBelongsToNode(current, position, sourceFile) && shouldIndentChildNode(options, current, previous, sourceFile, /*isNextChild*/ + true)) { const currentStart = getStartLineAndCharacterForNode(current, sourceFile); const nextTokenKind = nextTokenIsCurlyBraceOnSameLineAsCursor(precedingToken, current, lineAtPosition, sourceFile); const indentationDelta = nextTokenKind !== 0 /* Unknown */ ? assumeNewLineBeforeCloseBrace && nextTokenKind === 2 /* CloseBrace */ ? options.indentSize : 0 : lineAtPosition !== currentStart.line ? options.indentSize : 0; - return getIndentationForNodeWorker( - current, - currentStart, - /*ignoreActualIndentationRange*/ - void 0, - indentationDelta, - sourceFile, - /*isNextChild*/ - true, - options - ); + return getIndentationForNodeWorker(current, currentStart, /*ignoreActualIndentationRange*/ + void 0, indentationDelta, sourceFile, /*isNextChild*/ + true, options); } - const actualIndentation = getActualIndentationForListItem( - current, - sourceFile, - options, - /*listIndentsChild*/ - true - ); + const actualIndentation = getActualIndentationForListItem(current, sourceFile, options, /*listIndentsChild*/ + true); if (actualIndentation !== -1 /* Unknown */) { return actualIndentation; } @@ -171536,17 +155724,9 @@ ${options.prefix}` : "\n" : options.prefix } function getIndentationForNode(n, ignoreActualIndentationRange, sourceFile, options) { const start = sourceFile.getLineAndCharacterOfPosition(n.getStart(sourceFile)); - return getIndentationForNodeWorker( - n, - start, - ignoreActualIndentationRange, - /*indentationDelta*/ - 0, - sourceFile, - /*isNextChild*/ - false, - options - ); + return getIndentationForNodeWorker(n, start, ignoreActualIndentationRange, /*indentationDelta*/ + 0, sourceFile, /*isNextChild*/ + false, options); } SmartIndenter2.getIndentationForNode = getIndentationForNode; function getBaseIndentation(options) { @@ -171599,15 +155779,17 @@ ${options.prefix}` : "\n" : options.prefix return -1 /* Unknown */; } } + function getActualIndentationForNode(current, parent2, currentLineAndChar, parentAndChildShareLine, sourceFile, options) { const useActualIndentation = (isDeclaration(current) || isStatementButNotDeclaration(current)) && (parent2.kind === 312 /* SourceFile */ || !parentAndChildShareLine); if (!useActualIndentation) { return -1 /* Unknown */; } + return findColumnForFirstNonWhitespaceCharacterInLine(currentLineAndChar, sourceFile, options); } let NextTokenKind; - ((NextTokenKind2) => { + (NextTokenKind2 => { NextTokenKind2[NextTokenKind2["Unknown"] = 0] = "Unknown"; NextTokenKind2[NextTokenKind2["OpenBrace"] = 1] = "OpenBrace"; NextTokenKind2[NextTokenKind2["CloseBrace"] = 2] = "CloseBrace"; @@ -171617,14 +155799,17 @@ ${options.prefix}` : "\n" : options.prefix if (!nextToken) { return 0 /* Unknown */; } + if (nextToken.kind === 19 /* OpenBraceToken */) { return 1 /* OpenBrace */; } else if (nextToken.kind === 20 /* CloseBraceToken */) { const nextTokenStartLine = getStartLineAndCharacterForNode(nextToken, sourceFile).line; return lineAtPosition === nextTokenStartLine ? 2 /* CloseBrace */ : 0 /* Unknown */; } + return 0 /* Unknown */; } + function getStartLineAndCharacterForNode(n, sourceFile) { return sourceFile.getLineAndCharacterOfPosition(n.getStart(sourceFile)); } @@ -171663,14 +155848,11 @@ ${options.prefix}` : "\n" : options.prefix SmartIndenter2.childIsUnindentedBranchOfConditionalExpression = childIsUnindentedBranchOfConditionalExpression; function argumentStartsOnSameLineAsPreviousArgument(parent2, child, childStartLine, sourceFile) { if (isCallOrNewExpression(parent2)) { - if (!parent2.arguments) - return false; - const currentNode = find(parent2.arguments, (arg) => arg.pos === child.pos); - if (!currentNode) - return false; + if (!parent2.arguments) return false; + const currentNode = find(parent2.arguments, arg => arg.pos === child.pos); + 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) { @@ -171735,7 +155917,10 @@ ${options.prefix}` : "\n" : options.prefix const children = node.getChildren(sourceFile); for (let i = 1; i < children.length - 1; i++) { if (children[i].pos === list.pos && children[i].end === list.end) { - return { pos: children[i - 1].end, end: children[i + 1].getStart(sourceFile) }; + return { + pos: children[i - 1].end, + end: children[i + 1].getStart(sourceFile) + }; } } return list; @@ -171744,12 +155929,14 @@ ${options.prefix}` : "\n" : options.prefix if (!list) { return -1 /* Unknown */; } + return findColumnForFirstNonWhitespaceCharacterInLine(sourceFile.getLineAndCharacterOfPosition(list.pos), sourceFile, options); } function getActualIndentationForListItem(node, sourceFile, options, listIndentsChild) { if (node.parent && node.parent.kind === 261 /* VariableDeclarationList */) { return -1 /* Unknown */; } + const containingList = getContainingList(node, sourceFile); if (containingList) { const index = containingList.indexOf(node); @@ -171763,6 +155950,7 @@ ${options.prefix}` : "\n" : options.prefix } return -1 /* Unknown */; } + function deriveActualIndentationFromList(list, index, sourceFile, options) { Debug.assert(index >= 0 && index < list.length); const node = list[index]; @@ -171779,6 +155967,7 @@ ${options.prefix}` : "\n" : options.prefix } return -1 /* Unknown */; } + function findColumnForFirstNonWhitespaceCharacterInLine(lineAndCharacter, sourceFile, options) { const lineStart = sourceFile.getPositionOfLineAndCharacter(lineAndCharacter.line, 0); return findFirstNonWhitespaceColumn(lineStart, lineStart + lineAndCharacter.character, sourceFile, options); @@ -171798,7 +155987,10 @@ ${options.prefix}` : "\n" : options.prefix } character++; } - return { column, character }; + return { + column, + character + }; } SmartIndenter2.findFirstNonWhitespaceCharacterAndColumn = findFirstNonWhitespaceCharacterAndColumn; function findFirstNonWhitespaceColumn(startPos, endPos, sourceFile, options) { @@ -171806,6 +155998,7 @@ ${options.prefix}` : "\n" : options.prefix } SmartIndenter2.findFirstNonWhitespaceColumn = findFirstNonWhitespaceColumn; function nodeWillIndentChild(settings, parent2, child, sourceFile, indentByDefault) { + var _settings$indentSwitc; const childKind = child ? child.kind : 0 /* Unknown */; switch (parent2.kind) { case 244 /* ExpressionStatement */: @@ -171853,7 +156046,7 @@ ${options.prefix}` : "\n" : options.prefix case 297 /* DefaultClause */: return true; case 269 /* CaseBlock */: - return settings.indentSwitchCase ?? true; + return (_settings$indentSwitc = settings.indentSwitchCase) !== null && _settings$indentSwitc !== void 0 ? _settings$indentSwitc : true; case 260 /* VariableDeclaration */: case 303 /* PropertyAssignment */: case 226 /* BinaryExpression */: @@ -171917,14 +156110,8 @@ ${options.prefix}` : "\n" : options.prefix } } function shouldIndentChildNode(settings, parent2, child, sourceFile, isNextChild = false) { - return nodeWillIndentChild( - settings, - parent2, - child, - sourceFile, - /*indentByDefault*/ - false - ) && !(isNextChild && child && isControlFlowEndingStatement(child.kind, parent2)); + return nodeWillIndentChild(settings, parent2, child, sourceFile, /*indentByDefault*/ + false) && !(isNextChild && child && isControlFlowEndingStatement(child.kind, parent2)); } SmartIndenter2.shouldIndentChildNode = shouldIndentChildNode; function rangeIsOnOneLine(sourceFile, range) { @@ -171963,6 +156150,7 @@ ${options.prefix}` : "\n" : options.prefix var init_ts_formatting = __esm({ "src/services/_namespaces/ts.formatting.ts"() { "use strict"; + init_formattingContext(); init_formattingScanner(); init_rule(); @@ -171977,6 +156165,7 @@ ${options.prefix}` : "\n" : options.prefix var init_ts4 = __esm({ "src/services/_namespaces/ts.ts"() { "use strict"; + init_ts2(); init_ts3(); init_types3(); @@ -172018,7 +156207,8 @@ ${options.prefix}` : "\n" : options.prefix // src/deprecatedCompat/deprecate.ts function getTypeScriptVersion() { - return typeScriptVersion2 ?? (typeScriptVersion2 = new Version(version)); + var _typeScriptVersion; + return (_typeScriptVersion = typeScriptVersion2) !== null && _typeScriptVersion !== void 0 ? _typeScriptVersion : typeScriptVersion2 = new Version(version); } function formatDeprecationMessage(name, error2, errorAfter, since, message) { let deprecationMessage = error2 ? "DeprecationError: " : "DeprecationWarning: "; @@ -172029,14 +156219,8 @@ ${options.prefix}` : "\n" : options.prefix return deprecationMessage; } function createErrorDeprecation(name, errorAfter, since, message) { - const deprecationMessage = formatDeprecationMessage( - name, - /*error*/ - true, - errorAfter, - since, - message - ); + const deprecationMessage = formatDeprecationMessage(name, /*error*/ + true, errorAfter, since, message); return () => { throw new TypeError(deprecationMessage); }; @@ -172045,41 +156229,38 @@ ${options.prefix}` : "\n" : options.prefix let hasWrittenDeprecation = false; return () => { if (enableDeprecationWarnings && !hasWrittenDeprecation) { - Debug.log.warn(formatDeprecationMessage( - name, - /*error*/ - false, - errorAfter, - since, - message - )); + Debug.log.warn(formatDeprecationMessage(name, /*error*/ + false, errorAfter, since, message)); hasWrittenDeprecation = true; } }; } function createDeprecation(name, options = {}) { - const version2 = typeof options.typeScriptVersion === "string" ? new Version(options.typeScriptVersion) : options.typeScriptVersion ?? getTypeScriptVersion(); + var _options$typeScriptVe, _options$since; + const version2 = typeof options.typeScriptVersion === "string" ? new Version(options.typeScriptVersion) : (_options$typeScriptVe = options.typeScriptVersion) !== null && _options$typeScriptVe !== void 0 ? _options$typeScriptVe : getTypeScriptVersion(); const errorAfter = typeof options.errorAfter === "string" ? new Version(options.errorAfter) : options.errorAfter; const warnAfter = typeof options.warnAfter === "string" ? new Version(options.warnAfter) : options.warnAfter; - const since = typeof options.since === "string" ? new Version(options.since) : options.since ?? warnAfter; + const since = typeof options.since === "string" ? new Version(options.since) : (_options$since = options.since) !== null && _options$since !== void 0 ? _options$since : warnAfter; const error2 = options.error || errorAfter && version2.compareTo(errorAfter) >= 0; const warn = !warnAfter || version2.compareTo(warnAfter) >= 0; return error2 ? createErrorDeprecation(name, errorAfter, since, options.message) : warn ? createWarningDeprecation(name, errorAfter, since, options.message) : noop; } function wrapFunction(deprecation, func) { - return function() { + return function () { deprecation(); return func.apply(this, arguments); }; } function deprecate(func, options) { - const deprecation = createDeprecation((options == null ? void 0 : options.name) ?? Debug.getFunctionName(func), options); + var _ref52; + const deprecation = createDeprecation((_ref52 = options == null ? void 0 : options.name) !== null && _ref52 !== void 0 ? _ref52 : Debug.getFunctionName(func), options); return wrapFunction(deprecation, func); } var enableDeprecationWarnings, typeScriptVersion2; var init_deprecate = __esm({ "src/deprecatedCompat/deprecate.ts"() { "use strict"; + init_ts5(); enableDeprecationWarnings = true; } @@ -172087,12 +156268,18 @@ ${options.prefix}` : "\n" : options.prefix // src/deprecatedCompat/deprecations.ts function createOverload(name, overloads, binder2, deprecations) { - Object.defineProperty(call, "name", { ...Object.getOwnPropertyDescriptor(call, "name"), value: name }); + Object.defineProperty(call, "name", { + ...Object.getOwnPropertyDescriptor(call, "name"), + value: name + }); if (deprecations) { for (const key of Object.keys(deprecations)) { const index = +key; if (!isNaN(index) && hasProperty(overloads, `${index}`)) { - overloads[index] = deprecate(overloads[index], { ...deprecations[index], name }); + overloads[index] = deprecate(overloads[index], { + ...deprecations[index], + name + }); } } } @@ -172108,7 +156295,7 @@ ${options.prefix}` : "\n" : options.prefix } } function createBinder2(overloads, binder2) { - return (args) => { + return args => { for (let i = 0; hasProperty(overloads, `${i}`) && hasProperty(binder2, `${i}`); i++) { const fn = binder2[i]; if (fn(args)) { @@ -172119,10 +156306,10 @@ ${options.prefix}` : "\n" : options.prefix } function buildOverload(name) { return { - overload: (overloads) => ({ - bind: (binder2) => ({ + overload: overloads => ({ + bind: binder2 => ({ finish: () => createOverload(name, overloads, binder2), - deprecate: (deprecations) => ({ + deprecate: deprecations => ({ finish: () => createOverload(name, overloads, binder2, deprecations) }) }) @@ -172132,6 +156319,7 @@ ${options.prefix}` : "\n" : options.prefix var init_deprecations = __esm({ "src/deprecatedCompat/deprecations.ts"() { "use strict"; + init_ts5(); init_deprecate(); } @@ -172141,13 +156329,14 @@ ${options.prefix}` : "\n" : options.prefix var init_identifierProperties = __esm({ "src/deprecatedCompat/5.0/identifierProperties.ts"() { "use strict"; + init_ts5(); init_deprecate(); - addObjectAllocatorPatcher((objectAllocator2) => { + addObjectAllocatorPatcher(objectAllocator2 => { const Identifier78 = objectAllocator2.getIdentifierConstructor(); if (!hasProperty(Identifier78.prototype, "originalKeywordKind")) { Object.defineProperty(Identifier78.prototype, "originalKeywordKind", { - get: deprecate(function() { + get: deprecate(function () { return identifierToKeywordKind(this); }, { name: "originalKeywordKind", @@ -172160,7 +156349,7 @@ ${options.prefix}` : "\n" : options.prefix } if (!hasProperty(Identifier78.prototype, "isInJSDocNamespace")) { Object.defineProperty(Identifier78.prototype, "isInJSDocNamespace", { - get: deprecate(function() { + get: deprecate(function () { return this.flags & 4096 /* IdentifierIsInJSDocNamespace */ ? true : void 0; }, { name: "isInJSDocNamespace", @@ -172179,6 +156368,7 @@ ${options.prefix}` : "\n" : options.prefix var init_ts5 = __esm({ "src/deprecatedCompat/_namespaces/ts.ts"() { "use strict"; + init_ts2(); init_deprecations(); init_identifierProperties(); @@ -172189,6 +156379,7 @@ ${options.prefix}` : "\n" : options.prefix var init_ts6 = __esm({ "src/typingsInstallerCore/_namespaces/ts.ts"() { "use strict"; + init_ts2(); init_ts3(); init_ts_server2(); @@ -172198,7 +156389,9 @@ ${options.prefix}` : "\n" : options.prefix // src/typingsInstallerCore/typingsInstaller.ts function typingToFileName(cachePath, packageName, installTypingHost, log) { try { - const result = resolveModuleName(packageName, combinePaths(cachePath, "index.d.ts"), { moduleResolution: 2 /* Node10 */ }, installTypingHost); + const result = resolveModuleName(packageName, combinePaths(cachePath, "index.d.ts"), { + moduleResolution: 2 /* Node10 */ + }, installTypingHost); return result.resolvedModule && result.resolvedModule.resolvedFileName; } catch (e) { if (log.isEnabled()) { @@ -172209,7 +156402,7 @@ ${options.prefix}` : "\n" : options.prefix } function installNpmPackages(npmPath, tsVersion, packageNames, install) { let hasError = false; - for (let remaining = packageNames.length; remaining > 0; ) { + for (let remaining = packageNames.length; remaining > 0;) { const result = getNpmCommandForInstallation(npmPath, tsVersion, packageNames, remaining); remaining = result.remaining; hasError = install(result.command) || hasError; @@ -172218,7 +156411,8 @@ ${options.prefix}` : "\n" : options.prefix } function getNpmCommandForInstallation(npmPath, tsVersion, packageNames, remaining) { const sliceStart = packageNames.length - remaining; - let command, toSlice = remaining; + let command, + toSlice = remaining; while (true) { command = `${npmPath} install --ignore-scripts ${(toSlice === packageNames.length ? packageNames : packageNames.slice(sliceStart, sliceStart + toSlice)).join(" ")} --save-dev --user-agent="typesInstaller/${tsVersion}"`; if (command.length < 8e3) { @@ -172226,7 +156420,10 @@ ${options.prefix}` : "\n" : options.prefix } toSlice = toSlice - Math.floor(toSlice / 2); } - return { command, remaining: remaining - toSlice }; + return { + command, + remaining: remaining - toSlice + }; } function typingsName(packageName) { return `@types/${packageName}@ts${versionMajorMinor}`; @@ -172235,6 +156432,7 @@ ${options.prefix}` : "\n" : options.prefix var init_typingsInstaller = __esm({ "src/typingsInstallerCore/typingsInstaller.ts"() { "use strict"; + init_ts6(); init_ts_server2(); nullLog = { @@ -172249,10 +156447,10 @@ ${options.prefix}` : "\n" : options.prefix this.typesMapLocation = typesMapLocation; this.throttleLimit = throttleLimit; this.log = log; - this.packageNameToTypingLocation = /* @__PURE__ */ new Map(); - this.missingTypingsSet = /* @__PURE__ */ new Set(); - this.knownCachesSet = /* @__PURE__ */ new Set(); - this.projectWatchers = /* @__PURE__ */ new Map(); + this.packageNameToTypingLocation = /* @__PURE__ */new Map(); + this.missingTypingsSet = /* @__PURE__ */new Set(); + this.knownCachesSet = /* @__PURE__ */new Set(); + this.projectWatchers = /* @__PURE__ */new Map(); /** @internal */ this.pendingRunRequests = []; this.installRunCount = 1; @@ -172279,7 +156477,11 @@ ${options.prefix}` : "\n" : options.prefix return; } this.projectWatchers.delete(projectName); - this.sendResponse({ kind: ActionWatchTypingLocations, projectName, files: [] }); + this.sendResponse({ + kind: ActionWatchTypingLocations, + projectName, + files: [] + }); if (this.log.isEnabled()) { this.log.writeLine(`Closing file watchers for project '${projectName}' - done.`); } @@ -172297,18 +156499,7 @@ ${options.prefix}` : "\n" : options.prefix if (this.safeList === void 0) { this.initializeSafeList(); } - const discoverTypingsResult = ts_JsTyping_exports.discoverTypings( - this.installTypingHost, - this.log.isEnabled() ? (s) => this.log.writeLine(s) : void 0, - req.fileNames, - req.projectRootPath, - this.safeList, - this.packageNameToTypingLocation, - req.typeAcquisition, - req.unresolvedImports, - this.typesRegistry, - req.compilerOptions - ); + const discoverTypingsResult = ts_JsTyping_exports.discoverTypings(this.installTypingHost, this.log.isEnabled() ? s => this.log.writeLine(s) : void 0, req.fileNames, req.projectRootPath, this.safeList, this.packageNameToTypingLocation, req.typeAcquisition, req.unresolvedImports, this.typesRegistry, req.compilerOptions); this.watchFiles(req.projectName, discoverTypingsResult.filesToWatch); if (discoverTypingsResult.newTypingNames.length) { this.installTypings(req, req.cachePath || this.globalCachePath, discoverTypingsResult.cachedTypingPaths, discoverTypingsResult.newTypingNames); @@ -172384,7 +156575,10 @@ ${options.prefix}` : "\n" : options.prefix if (!version2) { continue; } - const newTyping = { typingLocation: typingFile, version: new Version(version2) }; + const newTyping = { + typingLocation: typingFile, + version: new Version(version2) + }; this.packageNameToTypingLocation.set(packageName, newTyping); } } @@ -172395,28 +156589,24 @@ ${options.prefix}` : "\n" : options.prefix this.knownCachesSet.add(cacheLocation); } filterTypings(typingsToInstall) { - return mapDefined(typingsToInstall, (typing) => { + 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; @@ -172457,7 +156647,7 @@ ${options.prefix}` : "\n" : options.prefix projectName: req.projectName }); const scopedTypings = filteredTypings.map(typingsName); - this.installTypingsAsync(requestId, scopedTypings, cachePath, (ok) => { + this.installTypingsAsync(requestId, scopedTypings, cachePath, ok => { try { if (!ok) { if (this.log.isEnabled()) { @@ -172480,7 +156670,10 @@ ${options.prefix}` : "\n" : options.prefix } const distTags = this.typesRegistry.get(packageName); const newVersion = new Version(distTags[`ts${versionMajorMinor}`] || distTags[this.latestDistTag]); - const newTyping = { typingLocation: typingFile, version: newVersion }; + const newTyping = { + typingLocation: typingFile, + version: newVersion + }; this.packageNameToTypingLocation.set(packageName, newTyping); installedTypingFiles.push(typingFile); } @@ -172517,11 +156710,19 @@ ${options.prefix}` : "\n" : options.prefix } const existing = this.projectWatchers.get(projectName); const newSet = new Set(files); - if (!existing || forEachKey(newSet, (s) => !existing.has(s)) || forEachKey(existing, (s) => !newSet.has(s))) { + if (!existing || forEachKey(newSet, s => !existing.has(s)) || forEachKey(existing, s => !newSet.has(s))) { this.projectWatchers.set(projectName, newSet); - this.sendResponse({ kind: ActionWatchTypingLocations, projectName, files }); + this.sendResponse({ + kind: ActionWatchTypingLocations, + projectName, + files + }); } else { - this.sendResponse({ kind: ActionWatchTypingLocations, projectName, files: void 0 }); + this.sendResponse({ + kind: ActionWatchTypingLocations, + projectName, + files: void 0 + }); } } createSetTypings(request, typings) { @@ -172535,14 +156736,19 @@ ${options.prefix}` : "\n" : options.prefix }; } installTypingsAsync(requestId, packageNames, cwd, onRequestCompleted) { - this.pendingRunRequests.unshift({ requestId, packageNames, cwd, onRequestCompleted }); + this.pendingRunRequests.unshift({ + requestId, + packageNames, + cwd, + onRequestCompleted + }); this.executeWithThrottling(); } executeWithThrottling() { while (this.inFlightRequestCount < this.throttleLimit && this.pendingRunRequests.length) { this.inFlightRequestCount++; const request = this.pendingRunRequests.pop(); - this.installWorker(request.requestId, request.packageNames, request.cwd, (ok) => { + this.installWorker(request.requestId, request.packageNames, request.cwd, ok => { this.inFlightRequestCount--; request.onRequestCompleted(ok); this.executeWithThrottling(); @@ -172564,6 +156770,7 @@ ${options.prefix}` : "\n" : options.prefix var init_ts_server_typingsInstaller = __esm({ "src/typingsInstallerCore/_namespaces/ts.server.typingsInstaller.ts"() { "use strict"; + init_typingsInstaller(); } }); @@ -172572,6 +156779,7 @@ ${options.prefix}` : "\n" : options.prefix var init_ts_server2 = __esm({ "src/typingsInstallerCore/_namespaces/ts.server.ts"() { "use strict"; + init_ts_server(); init_ts_server_typingsInstaller(); } @@ -172588,12 +156796,9 @@ ${options.prefix}` : "\n" : options.prefix function createInstallTypingsRequest(project, typeAcquisition, unresolvedImports, cachePath) { return { projectName: project.getProjectName(), - fileNames: project.getFileNames( - /*excludeFilesFromExternalLibraries*/ - true, - /*excludeConfigFiles*/ - true - ).concat(project.getExcludedFiles()), + fileNames: project.getFileNames( /*excludeFilesFromExternalLibraries*/ + true, /*excludeConfigFiles*/ + true).concat(project.getExcludedFiles()), compilerOptions: project.getCompilationSettings(), typeAcquisition, unresolvedImports, @@ -172613,7 +156818,7 @@ ${options.prefix}` : "\n" : options.prefix return fileName; } function createNormalizedPathMap() { - const map2 = /* @__PURE__ */ new Map(); + const map2 = /* @__PURE__ */new Map(); return { get(path) { return map2.get(path); @@ -172648,8 +156853,9 @@ ${options.prefix}` : "\n" : options.prefix var init_utilitiesPublic3 = __esm({ "src/server/utilitiesPublic.ts"() { "use strict"; + init_ts7(); - LogLevel2 = /* @__PURE__ */ ((LogLevel3) => { + LogLevel2 = /* @__PURE__ */(LogLevel3 => { LogLevel3[LogLevel3["terse"] = 0] = "terse"; LogLevel3[LogLevel3["normal"] = 1] = "normal"; LogLevel3[LogLevel3["requestTime"] = 2] = "requestTime"; @@ -172657,13 +156863,13 @@ ${options.prefix}` : "\n" : options.prefix return LogLevel3; })(LogLevel2 || {}); emptyArray2 = createSortedArray2(); - Msg = /* @__PURE__ */ ((Msg2) => { + Msg = /* @__PURE__ */(Msg2 => { Msg2["Err"] = "Err"; Msg2["Info"] = "Info"; Msg2["Perf"] = "Perf"; return Msg2; })(Msg || {}); - ((Errors2) => { + (Errors2 => { function ThrowNoProject() { throw new Error("No Project."); } @@ -172702,12 +156908,13 @@ ${options.prefix}` : "\n" : options.prefix var init_utilities5 = __esm({ "src/server/utilities.ts"() { "use strict"; + init_ts7(); init_ts_server3(); ThrottledOperations = class _ThrottledOperations { constructor(host, logger) { this.host = host; - this.pendingTimeouts = /* @__PURE__ */ new Map(); + this.pendingTimeouts = /* @__PURE__ */new Map(); this.logger = logger.hasLevel(3 /* verbose */) ? logger : void 0; } /** @@ -172728,8 +156935,7 @@ ${options.prefix}` : "\n" : options.prefix } 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); } @@ -172778,7 +156984,8 @@ ${options.prefix}` : "\n" : options.prefix var init_protocol = __esm({ "src/server/protocol.ts"() { "use strict"; - CommandTypes = /* @__PURE__ */ ((CommandTypes2) => { + + CommandTypes = /* @__PURE__ */(CommandTypes2 => { CommandTypes2["JsxClosingTag"] = "jsxClosingTag"; CommandTypes2["LinkedEditingRange"] = "linkedEditingRange"; CommandTypes2["Brace"] = "brace"; @@ -172891,13 +157098,13 @@ ${options.prefix}` : "\n" : options.prefix CommandTypes2["WatchChange"] = "watchChange"; return CommandTypes2; })(CommandTypes || {}); - OrganizeImportsMode2 = /* @__PURE__ */ ((OrganizeImportsMode3) => { + OrganizeImportsMode2 = /* @__PURE__ */(OrganizeImportsMode3 => { OrganizeImportsMode3["All"] = "All"; OrganizeImportsMode3["SortAndCombine"] = "SortAndCombine"; OrganizeImportsMode3["RemoveUnused"] = "RemoveUnused"; return OrganizeImportsMode3; })(OrganizeImportsMode2 || {}); - WatchFileKind2 = /* @__PURE__ */ ((WatchFileKind3) => { + WatchFileKind2 = /* @__PURE__ */(WatchFileKind3 => { WatchFileKind3["FixedPollingInterval"] = "FixedPollingInterval"; WatchFileKind3["PriorityPollingInterval"] = "PriorityPollingInterval"; WatchFileKind3["DynamicPriorityPolling"] = "DynamicPriorityPolling"; @@ -172906,46 +157113,46 @@ ${options.prefix}` : "\n" : options.prefix WatchFileKind3["UseFsEventsOnParentDirectory"] = "UseFsEventsOnParentDirectory"; return WatchFileKind3; })(WatchFileKind2 || {}); - WatchDirectoryKind2 = /* @__PURE__ */ ((WatchDirectoryKind3) => { + WatchDirectoryKind2 = /* @__PURE__ */(WatchDirectoryKind3 => { WatchDirectoryKind3["UseFsEvents"] = "UseFsEvents"; WatchDirectoryKind3["FixedPollingInterval"] = "FixedPollingInterval"; WatchDirectoryKind3["DynamicPriorityPolling"] = "DynamicPriorityPolling"; WatchDirectoryKind3["FixedChunkSizePolling"] = "FixedChunkSizePolling"; return WatchDirectoryKind3; })(WatchDirectoryKind2 || {}); - PollingWatchKind2 = /* @__PURE__ */ ((PollingWatchKind3) => { + PollingWatchKind2 = /* @__PURE__ */(PollingWatchKind3 => { PollingWatchKind3["FixedInterval"] = "FixedInterval"; PollingWatchKind3["PriorityInterval"] = "PriorityInterval"; PollingWatchKind3["DynamicPriority"] = "DynamicPriority"; PollingWatchKind3["FixedChunkSize"] = "FixedChunkSize"; return PollingWatchKind3; })(PollingWatchKind2 || {}); - CompletionTriggerKind2 = /* @__PURE__ */ ((CompletionTriggerKind4) => { + CompletionTriggerKind2 = /* @__PURE__ */(CompletionTriggerKind4 => { CompletionTriggerKind4[CompletionTriggerKind4["Invoked"] = 1] = "Invoked"; CompletionTriggerKind4[CompletionTriggerKind4["TriggerCharacter"] = 2] = "TriggerCharacter"; CompletionTriggerKind4[CompletionTriggerKind4["TriggerForIncompleteCompletions"] = 3] = "TriggerForIncompleteCompletions"; return CompletionTriggerKind4; })(CompletionTriggerKind2 || {}); - IndentStyle2 = /* @__PURE__ */ ((IndentStyle3) => { + IndentStyle2 = /* @__PURE__ */(IndentStyle3 => { IndentStyle3["None"] = "None"; IndentStyle3["Block"] = "Block"; IndentStyle3["Smart"] = "Smart"; return IndentStyle3; })(IndentStyle2 || {}); - SemicolonPreference2 = /* @__PURE__ */ ((SemicolonPreference3) => { + SemicolonPreference2 = /* @__PURE__ */(SemicolonPreference3 => { SemicolonPreference3["Ignore"] = "ignore"; SemicolonPreference3["Insert"] = "insert"; SemicolonPreference3["Remove"] = "remove"; return SemicolonPreference3; })(SemicolonPreference2 || {}); - JsxEmit2 = /* @__PURE__ */ ((JsxEmit3) => { + JsxEmit2 = /* @__PURE__ */(JsxEmit3 => { JsxEmit3["None"] = "None"; JsxEmit3["Preserve"] = "Preserve"; JsxEmit3["ReactNative"] = "ReactNative"; JsxEmit3["React"] = "React"; return JsxEmit3; })(JsxEmit2 || {}); - ModuleKind2 = /* @__PURE__ */ ((ModuleKind3) => { + ModuleKind2 = /* @__PURE__ */(ModuleKind3 => { ModuleKind3["None"] = "None"; ModuleKind3["CommonJS"] = "CommonJS"; ModuleKind3["AMD"] = "AMD"; @@ -172956,17 +157163,17 @@ ${options.prefix}` : "\n" : options.prefix ModuleKind3["ESNext"] = "ESNext"; return ModuleKind3; })(ModuleKind2 || {}); - ModuleResolutionKind2 = /* @__PURE__ */ ((ModuleResolutionKind3) => { + ModuleResolutionKind2 = /* @__PURE__ */(ModuleResolutionKind3 => { ModuleResolutionKind3["Classic"] = "Classic"; ModuleResolutionKind3["Node"] = "Node"; return ModuleResolutionKind3; })(ModuleResolutionKind2 || {}); - NewLineKind2 = /* @__PURE__ */ ((NewLineKind3) => { + NewLineKind2 = /* @__PURE__ */(NewLineKind3 => { NewLineKind3["Crlf"] = "Crlf"; NewLineKind3["Lf"] = "Lf"; return NewLineKind3; })(NewLineKind2 || {}); - ScriptTarget10 = /* @__PURE__ */ ((ScriptTarget11) => { + ScriptTarget10 = /* @__PURE__ */(ScriptTarget11 => { ScriptTarget11["ES3"] = "ES3"; ScriptTarget11["ES5"] = "ES5"; ScriptTarget11["ES6"] = "ES6"; @@ -172981,7 +157188,7 @@ ${options.prefix}` : "\n" : options.prefix ScriptTarget11["ESNext"] = "ESNext"; return ScriptTarget11; })(ScriptTarget10 || {}); - ClassificationType2 = /* @__PURE__ */ ((ClassificationType3) => { + ClassificationType2 = /* @__PURE__ */(ClassificationType3 => { ClassificationType3[ClassificationType3["comment"] = 1] = "comment"; ClassificationType3[ClassificationType3["identifier"] = 2] = "identifier"; ClassificationType3[ClassificationType3["keyword"] = 3] = "keyword"; @@ -173033,6 +157240,7 @@ ${options.prefix}` : "\n" : options.prefix var init_ts_server_protocol = __esm({ "src/server/_namespaces/ts.server.protocol.ts"() { "use strict"; + init_protocol(); } }); @@ -173061,6 +157269,7 @@ ${options.prefix}` : "\n" : options.prefix var init_scriptInfo = __esm({ "src/server/scriptInfo.ts"() { "use strict"; + init_ts7(); init_ts_server3(); TextStorage = class { @@ -173136,7 +157345,13 @@ ${options.prefix}` : "\n" : options.prefix * returns true if text changed */ reloadWithFileText(tempFileName) { - const { text: newText, fileSize } = tempFileName || !this.info.isDynamicOrHasMixedContent() ? this.getFileTextAndSize(tempFileName) : { text: "", fileSize: void 0 }; + const { + text: newText, + fileSize + } = tempFileName || !this.info.isDynamicOrHasMixedContent() ? this.getFileTextAndSize(tempFileName) : { + text: "", + fileSize: void 0 + }; const reloaded = this.reload(newText); this.fileSize = fileSize; this.ownFileText = !tempFileName || tempFileName === this.info.fileName; @@ -173163,13 +157378,13 @@ ${options.prefix}` : "\n" : options.prefix return !!this.fileSize ? this.fileSize : !!this.text ? this.text.length : !!this.svc ? this.svc.getSnapshot().getLength() : this.getSnapshot().getLength(); } getSnapshot() { + var _this$textSnapshot; var _a; - return ((_a = this.tryUseScriptVersionCache()) == null ? void 0 : _a.getSnapshot()) || (this.textSnapshot ?? (this.textSnapshot = ScriptSnapshot.fromString(Debug.checkDefined(this.text)))); + return ((_a = this.tryUseScriptVersionCache()) == null ? void 0 : _a.getSnapshot()) || ((_this$textSnapshot = this.textSnapshot) !== null && _this$textSnapshot !== void 0 ? _this$textSnapshot : this.textSnapshot = ScriptSnapshot.fromString(Debug.checkDefined(this.text))); } 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], @@ -173184,8 +157399,7 @@ ${options.prefix}` : "\n" : options.prefix */ 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; @@ -173201,10 +157415,15 @@ ${options.prefix}` : "\n" : options.prefix } positionToLineOffset(position) { const svc = this.tryUseScriptVersionCache(); - if (svc) - return svc.positionToLineOffset(position); - const { line, character } = computeLineAndCharacterOfPosition(this.getLineMap(), position); - return { line: line + 1, offset: character + 1 }; + if (svc) return svc.positionToLineOffset(position); + const { + line, + character + } = computeLineAndCharacterOfPosition(this.getLineMap(), position); + return { + line: line + 1, + offset: character + 1 + }; } getFileTextAndSize(tempFileName) { let text; @@ -173217,10 +157436,15 @@ ${options.prefix}` : "\n" : options.prefix const service = this.info.containingProjects[0].projectService; service.logger.info(`Skipped loading contents of large file ${fileName} for info ${this.info.fileName}: fileSize: ${fileSize}`); this.info.containingProjects[0].projectService.sendLargeFileReferencedEvent(fileName, fileSize); - return { text: "", fileSize }; + return { + text: "", + fileSize + }; } } - return { text: getText() }; + return { + text: getText() + }; } /** @internal */ switchToScriptVersionCache() { @@ -173260,7 +157484,7 @@ ${options.prefix}` : "\n" : options.prefix if (svc) { return { getLineCount: () => svc.getLineCount(), - getLineText: (line) => svc.getAbsolutePositionAndLineText(line + 1).lineText + getLineText: line => svc.getAbsolutePositionAndLineText(line + 1).lineText }; } const lineMap = this.getLineMap(); @@ -173395,14 +157619,11 @@ ${options.prefix}` : "\n" : options.prefix if (isConfiguredProject(p)) { p.getCachedDirectoryStructureHost().addOrDeleteFile(this.fileName, this.path, 2 /* Deleted */); } + const existingRoot = p.getRootFilesMap().get(this.path); - p.removeFile( - this, - /*fileExists*/ - false, - /*detachFromProject*/ - false - ); + p.removeFile(this, /*fileExists*/ + false, /*detachFromProject*/ + false); p.onFileAddedOrRemoved(this.isSymlink()); if (existingRoot && !isInferredProject(p)) { p.addMissingFileRoot(existingRoot.fileName); @@ -173429,22 +157650,17 @@ ${options.prefix}` : "\n" : options.prefix 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 (defaultConfiguredProject === project) return project; + if (!firstNonSourceOfProjectReferenceRedirect) firstNonSourceOfProjectReferenceRedirect = project; } - if (!firstConfiguredProject) - firstConfiguredProject = project; + if (!firstConfiguredProject) firstConfiguredProject = project; } else if (!firstExternalProject && isExternalProject(project)) { firstExternalProject = project; } else if (!firstInferredProject && isInferredProject(project)) { firstInferredProject = project; } } - return ensurePrimaryProjectKind( - defaultConfiguredProject || firstNonSourceOfProjectReferenceRedirect || firstConfiguredProject || firstExternalProject || firstInferredProject - ); + return ensurePrimaryProjectKind(defaultConfiguredProject || firstNonSourceOfProjectReferenceRedirect || firstConfiguredProject || firstExternalProject || firstInferredProject); } } registerFileUpdate() { @@ -173458,14 +157674,20 @@ ${options.prefix}` : "\n" : options.prefix this.formatSettings = getDefaultFormatCodeSettings(this.host.newLine); assign(this.formatSettings, formatSettings); } else { - this.formatSettings = { ...this.formatSettings, ...formatSettings }; + this.formatSettings = { + ...this.formatSettings, + ...formatSettings + }; } } if (preferences) { if (!this.preferences) { this.preferences = emptyOptions; } - this.preferences = { ...this.preferences, ...preferences }; + this.preferences = { + ...this.preferences, + ...preferences + }; } } getLatestVersion() { @@ -173498,14 +157720,11 @@ ${options.prefix}` : "\n" : options.prefix } } isOrphan() { - return !forEach(this.containingProjects, (p) => !p.isOrphan()); + return !forEach(this.containingProjects, p => !p.isOrphan()); } /** @internal */ isContainedByBackgroundProject() { - return some( - this.containingProjects, - isBackgroundProject - ); + return some(this.containingProjects, isBackgroundProject); } /** * @param line 1 based index @@ -173545,7 +157764,7 @@ ${options.prefix}` : "\n" : options.prefix if ((arr1 || emptyArray2).length === 0 && (arr2 || emptyArray2).length === 0) { return true; } - const set = /* @__PURE__ */ new Map(); + const set = /* @__PURE__ */new Map(); let unique = 0; for (const v of arr1) { if (set.get(v) !== true) { @@ -173581,6 +157800,7 @@ ${options.prefix}` : "\n" : options.prefix var init_typingsCache = __esm({ "src/server/typingsCache.ts"() { "use strict"; + init_ts7(); init_ts_server3(); nullTypingsInstaller = { @@ -173593,10 +157813,11 @@ ${options.prefix}` : "\n" : options.prefix globalTypingsCacheLocation: void 0 // TODO: GH#18217 }; + TypingsCache = class { constructor(installer) { this.installer = installer; - this.perProjectCache = /* @__PURE__ */ new Map(); + this.perProjectCache = /* @__PURE__ */new Map(); } isKnownTypesPackageName(name) { return this.installer.isKnownTypesPackageName(name); @@ -173701,30 +157922,30 @@ ${options.prefix}` : "\n" : options.prefix return counts2.ts === 0 && counts2.tsx === 0; } function hasNoTypeScriptSource(fileNames) { - return !fileNames.some((fileName) => fileExtensionIs(fileName, ".ts" /* Ts */) && !isDeclarationFileName(fileName) || fileExtensionIs(fileName, ".tsx" /* Tsx */)); + return !fileNames.some(fileName => fileExtensionIs(fileName, ".ts" /* Ts */) && !isDeclarationFileName(fileName) || fileExtensionIs(fileName, ".tsx" /* Tsx */)); } + function isGeneratedFileWatcher(watch) { return watch.generatedFilePath !== void 0; } function getUnresolvedImports(program, cachedUnresolvedImportsPerFile) { var _a, _b; const sourceFiles = program.getSourceFiles(); - (_a = tracing) == null ? void 0 : _a.push(tracing.Phase.Session, "getUnresolvedImports", { count: sourceFiles.length }); - const ambientModules = program.getTypeChecker().getAmbientModules().map((mod) => stripQuotes(mod.getName())); - const result = sortAndDeduplicate(flatMap(sourceFiles, (sourceFile) => extractUnresolvedImportsFromSourceFile( - program, - sourceFile, - ambientModules, - cachedUnresolvedImportsPerFile - ))); + (_a = tracing) == null ? void 0 : _a.push(tracing.Phase.Session, "getUnresolvedImports", { + count: sourceFiles.length + }); + const ambientModules = program.getTypeChecker().getAmbientModules().map(mod => stripQuotes(mod.getName())); + const result = sortAndDeduplicate(flatMap(sourceFiles, sourceFile => extractUnresolvedImportsFromSourceFile(program, sourceFile, ambientModules, cachedUnresolvedImportsPerFile))); (_b = tracing) == null ? void 0 : _b.pop(); return result; } function extractUnresolvedImportsFromSourceFile(program, file, ambientModules, cachedUnresolvedImportsPerFile) { return getOrUpdate(cachedUnresolvedImportsPerFile, file.path, () => { let unresolvedImports; - program.forEachResolvedModule(({ resolvedModule }, name) => { - if ((!resolvedModule || !resolutionExtensionIsTSOrJson(resolvedModule.extension)) && !isExternalModuleNameRelative(name) && !ambientModules.some((m) => m === name)) { + program.forEachResolvedModule(({ + resolvedModule + }, name) => { + if ((!resolvedModule || !resolutionExtensionIsTSOrJson(resolvedModule.extension)) && !isExternalModuleNameRelative(name) && !ambientModules.some(m => m === name)) { unresolvedImports = append(unresolvedImports, parsePackageName(name).packageName); } }, file); @@ -173734,23 +157955,28 @@ ${options.prefix}` : "\n" : options.prefix function isInferredProject(project) { return project.projectKind === 0 /* Inferred */; } + function isConfiguredProject(project) { return project.projectKind === 1 /* Configured */; } + function isExternalProject(project) { return project.projectKind === 2 /* External */; } + function isBackgroundProject(project) { return project.projectKind === 3 /* AutoImportProvider */ || project.projectKind === 4 /* Auxiliary */; } + var ProjectKind, Project3, InferredProject2, AuxiliaryProject, _AutoImportProviderProject, AutoImportProviderProject, ConfiguredProject2, ExternalProject2; var init_project = __esm({ "src/server/project.ts"() { "use strict"; + init_ts7(); init_ts7(); init_ts_server3(); - ProjectKind = /* @__PURE__ */ ((ProjectKind2) => { + ProjectKind = /* @__PURE__ */(ProjectKind2 => { ProjectKind2[ProjectKind2["Inferred"] = 0] = "Inferred"; ProjectKind2[ProjectKind2["Configured"] = 1] = "Configured"; ProjectKind2[ProjectKind2["External"] = 2] = "External"; @@ -173768,7 +157994,7 @@ ${options.prefix}` : "\n" : options.prefix this.compileOnSaveEnabled = compileOnSaveEnabled; this.watchOptions = watchOptions; this.rootFiles = []; - this.rootFilesMap = /* @__PURE__ */ new Map(); + this.rootFilesMap = /* @__PURE__ */new Map(); /** @internal */ this.plugins = []; /** @@ -173778,7 +158004,7 @@ ${options.prefix}` : "\n" : options.prefix * * @internal */ - this.cachedUnresolvedImportsPerFile = /* @__PURE__ */ new Map(); + this.cachedUnresolvedImportsPerFile = /* @__PURE__ */new Map(); /** @internal */ this.hasAddedorRemovedFiles = false; /** @internal */ @@ -173843,17 +158069,13 @@ ${options.prefix}` : "\n" : options.prefix this.setInternalCompilerOptionsForEmittingJsFiles(); const host = this.projectService.host; if (this.projectService.logger.loggingEnabled()) { - this.trace = (s) => this.writeLog(s); + this.trace = s => this.writeLog(s); } else if (host.trace) { - this.trace = (s) => host.trace(s); + this.trace = s => host.trace(s); } this.realpath = maybeBind(host, host.realpath); - this.resolutionCache = createResolutionCache( - this, - this.currentDirectory, - /*logChangesWhenResolvingModule*/ - true - ); + this.resolutionCache = createResolutionCache(this, this.currentDirectory, /*logChangesWhenResolvingModule*/ + true); this.languageService = createLanguageService(this, this.documentRegistry, this.projectService.serverMode); if (lastFileExceededProgramSize) { this.disableLanguageService(lastFileExceededProgramSize); @@ -173877,7 +158099,9 @@ ${options.prefix}` : "\n" : options.prefix return hasOneOrMoreJsAndNoTsFiles(this); } static resolveModule(moduleName, initialDir, host, log) { - return _Project.importServicePluginSync({ name: moduleName }, [initialDir], host, log).resolvedModule; + return _Project.importServicePluginSync({ + name: moduleName + }, [initialDir], host, log).resolvedModule; } /** @internal */ static importServicePluginSync(pluginConfigEntry, searchPaths, host, log) { @@ -173885,6 +158109,7 @@ ${options.prefix}` : "\n" : options.prefix let errorLogs; let resolvedModule; for (const initialDir of searchPaths) { + var _errorLogs; const resolvedPath = normalizeSlashes(host.resolvePath(combinePaths(initialDir, "node_modules"))); log(`Loading ${pluginConfigEntry.name} from ${initialDir} (resolved to ${resolvedPath})`); const result = host.require(resolvedPath, pluginConfigEntry.name); @@ -173893,9 +158118,13 @@ ${options.prefix}` : "\n" : options.prefix break; } const err = result.error.stack || result.error.message || JSON.stringify(result.error); - (errorLogs ?? (errorLogs = [])).push(`Failed to load module '${pluginConfigEntry.name}' from ${resolvedPath}: ${err}`); + ((_errorLogs = errorLogs) !== null && _errorLogs !== void 0 ? _errorLogs : errorLogs = []).push(`Failed to load module '${pluginConfigEntry.name}' from ${resolvedPath}: ${err}`); } - return { pluginConfigEntry, resolvedModule, errorLogs }; + return { + pluginConfigEntry, + resolvedModule, + errorLogs + }; } /** @internal */ static async importServicePluginAsync(pluginConfigEntry, searchPaths, host, log) { @@ -173903,28 +158132,40 @@ ${options.prefix}` : "\n" : options.prefix let errorLogs; let resolvedModule; for (const initialDir of searchPaths) { + var _errorLogs2; const resolvedPath = combinePaths(initialDir, "node_modules"); log(`Dynamically importing ${pluginConfigEntry.name} from ${initialDir} (resolved to ${resolvedPath})`); let result; try { result = await host.importPlugin(resolvedPath, pluginConfigEntry.name); } catch (e) { - result = { module: void 0, error: e }; + result = { + module: void 0, + error: e + }; } if (!result.error) { resolvedModule = result.module; break; } const err = result.error.stack || result.error.message || JSON.stringify(result.error); - (errorLogs ?? (errorLogs = [])).push(`Failed to dynamically import module '${pluginConfigEntry.name}' from ${resolvedPath}: ${err}`); + ((_errorLogs2 = errorLogs) !== null && _errorLogs2 !== void 0 ? _errorLogs2 : errorLogs = []).push(`Failed to dynamically import module '${pluginConfigEntry.name}' from ${resolvedPath}: ${err}`); } - return { pluginConfigEntry, resolvedModule, errorLogs }; + return { + pluginConfigEntry, + resolvedModule, + errorLogs + }; } isKnownTypesPackageName(name) { return this.typingsCache.isKnownTypesPackageName(name); } installPackage(options) { - return this.typingsCache.installPackage({ ...options, projectName: this.projectName, projectRootPath: this.toPath(this.currentDirectory) }); + return this.typingsCache.installPackage({ + ...options, + projectName: this.projectName, + projectRootPath: this.toPath(this.currentDirectory) + }); } /** @internal */ getGlobalTypingsCacheLocation() { @@ -173939,11 +158180,7 @@ ${options.prefix}` : "\n" : options.prefix this.symlinks = createSymlinkCache(this.getCurrentDirectory(), this.getCanonicalFileName); } if (this.program && !this.symlinks.hasProcessedResolutions()) { - this.symlinks.setSymlinksFromResolutions( - this.program.forEachResolvedModule, - this.program.forEachResolvedTypeReferenceDirective, - this.program.getAutomaticTypeDirectiveResolutions() - ); + this.symlinks.setSymlinksFromResolutions(this.program.forEachResolvedModule, this.program.forEachResolvedTypeReferenceDirective, this.program.getAutomaticTypeDirectiveResolutions()); } return this.symlinks; } @@ -173969,7 +158206,7 @@ ${options.prefix}` : "\n" : options.prefix return emptyArray; } let result; - this.rootFilesMap.forEach((value) => { + this.rootFilesMap.forEach(value => { if (this.languageServiceEnabled || value.info && value.info.isScriptOpen()) { (result || (result = [])).push(value.fileName); } @@ -174038,14 +158275,7 @@ ${options.prefix}` : "\n" : options.prefix } /** @internal */ resolveTypeReferenceDirectiveReferences(typeDirectiveReferences, containingFile, redirectedReference, options, containingSourceFile, reusedNames) { - return this.resolutionCache.resolveTypeReferenceDirectiveReferences( - typeDirectiveReferences, - containingFile, - redirectedReference, - options, - containingSourceFile, - reusedNames - ); + return this.resolutionCache.resolveTypeReferenceDirectiveReferences(typeDirectiveReferences, containingFile, redirectedReference, options, containingSourceFile, reusedNames); } /** @internal */ resolveLibrary(libraryName, resolveFrom, options, libFileName) { @@ -174067,25 +158297,11 @@ ${options.prefix}` : "\n" : options.prefix } /** @internal */ watchDirectoryOfFailedLookupLocation(directory, cb, flags) { - return this.projectService.watchFactory.watchDirectory( - directory, - cb, - flags, - this.projectService.getWatchOptions(this), - WatchType.FailedLookupLocations, - this - ); + return this.projectService.watchFactory.watchDirectory(directory, cb, flags, this.projectService.getWatchOptions(this), WatchType.FailedLookupLocations, this); } /** @internal */ watchAffectingFileLocation(file, cb) { - return this.projectService.watchFactory.watchFile( - file, - cb, - 2e3 /* High */, - this.projectService.getWatchOptions(this), - WatchType.AffectingFileLocation, - this - ); + return this.projectService.watchFactory.watchFile(file, cb, 2e3 /* High */, this.projectService.getWatchOptions(this), WatchType.AffectingFileLocation, this); } /** @internal */ clearInvalidateResolutionOfFailedLookupTimer() { @@ -174093,16 +158309,12 @@ ${options.prefix}` : "\n" : options.prefix } /** @internal */ scheduleInvalidateResolutionsOfFailedLookupLocations() { - this.projectService.throttledOperations.schedule( - `${this.getProjectName()}FailedLookupInvalidation`, - /*delay*/ - 1e3, - () => { - if (this.resolutionCache.invalidateResolutionsOfFailedLookupLocations()) { - this.projectService.delayUpdateProjectGraphAndEnsureProjectStructureForOpenFiles(this); - } + this.projectService.throttledOperations.schedule(`${this.getProjectName()}FailedLookupInvalidation`, /*delay*/ + 1e3, () => { + if (this.resolutionCache.invalidateResolutionsOfFailedLookupLocations()) { + this.projectService.delayUpdateProjectGraphAndEnsureProjectStructureForOpenFiles(this); } - ); + }); } /** @internal */ invalidateResolutionsOfFailedLookupLocations() { @@ -174117,14 +158329,7 @@ ${options.prefix}` : "\n" : options.prefix } /** @internal */ watchTypeRootsDirectory(directory, cb, flags) { - return this.projectService.watchFactory.watchDirectory( - directory, - cb, - flags, - this.projectService.getWatchOptions(this), - WatchType.TypeRoots, - this - ); + return this.projectService.watchFactory.watchDirectory(directory, cb, flags, this.projectService.getWatchOptions(this), WatchType.TypeRoots, this); } /** @internal */ hasChangedAutomaticTypeDirectiveNames() { @@ -174152,6 +158357,7 @@ ${options.prefix}` : "\n" : options.prefix error(s) { this.projectService.logger.msg(s, "Err" /* Err */); } + setInternalCompilerOptionsForEmittingJsFiles() { if (this.projectKind === 0 /* Inferred */ || this.projectKind === 2 /* External */) { this.compilerOptions.noEmitForJsFiles = true; @@ -174161,7 +158367,7 @@ ${options.prefix}` : "\n" : options.prefix * Get the errors that dont have any file name associated */ getGlobalProjectErrors() { - return filter(this.projectErrors, (diagnostic) => !diagnostic.file) || emptyArray2; + return filter(this.projectErrors, diagnostic => !diagnostic.file) || emptyArray2; } /** * Get all the project errors @@ -174203,38 +158409,32 @@ ${options.prefix}` : "\n" : options.prefix return []; } updateProjectIfDirty(this); - this.builderState = BuilderState.create( - this.program, - this.builderState, - /*disableUseFileVersionAsSignature*/ - true - ); - return mapDefined( - BuilderState.getFilesAffectedBy( - this.builderState, - this.program, - scriptInfo.path, - this.cancellationToken, - this.projectService.host - ), - (sourceFile) => this.shouldEmitFile(this.projectService.getScriptInfoForPath(sourceFile.path)) ? sourceFile.fileName : void 0 - ); + this.builderState = BuilderState.create(this.program, this.builderState, /*disableUseFileVersionAsSignature*/ + true); + return mapDefined(BuilderState.getFilesAffectedBy(this.builderState, this.program, scriptInfo.path, this.cancellationToken, this.projectService.host), sourceFile => this.shouldEmitFile(this.projectService.getScriptInfoForPath(sourceFile.path)) ? sourceFile.fileName : void 0); } /** * Returns true if emit was conducted */ emitFile(scriptInfo, writeFile2) { if (!this.languageServiceEnabled || !this.shouldEmitFile(scriptInfo)) { - return { emitSkipped: true, diagnostics: emptyArray2 }; + return { + emitSkipped: true, + diagnostics: emptyArray2 + }; } - const { emitSkipped, diagnostics, outputFiles } = this.getLanguageService().getEmitOutput(scriptInfo.fileName); + const { + emitSkipped, + diagnostics, + outputFiles + } = this.getLanguageService().getEmitOutput(scriptInfo.fileName); if (!emitSkipped) { for (const outputFile of outputFiles) { const outputFileAbsoluteFileName = getNormalizedAbsolutePath(outputFile.name, this.currentDirectory); writeFile2(outputFileAbsoluteFileName, outputFile.text, outputFile.writeByteOrderMark); } if (this.builderState && getEmitDeclarations(this.compilerOptions)) { - const dtsFiles = outputFiles.filter((f) => isDeclarationFileName(f.name)); + const dtsFiles = outputFiles.filter(f => isDeclarationFileName(f.name)); if (dtsFiles.length === 1) { const sourceFile = this.program.getSourceFile(scriptInfo.fileName); const signature = this.projectService.host.createHash ? this.projectService.host.createHash(dtsFiles[0].text) : generateDjb2Hash(dtsFiles[0].text); @@ -174242,7 +158442,10 @@ ${options.prefix}` : "\n" : options.prefix } } } - return { emitSkipped, diagnostics }; + return { + emitSkipped, + diagnostics + }; } enableLanguageService() { if (this.languageServiceEnabled || this.projectService.serverMode === 2 /* Syntactic */) { @@ -174250,11 +158453,8 @@ ${options.prefix}` : "\n" : options.prefix } this.languageServiceEnabled = true; this.lastFileExceededProgramSize = void 0; - this.projectService.onUpdateLanguageServiceStateForProject( - this, - /*languageServiceEnabled*/ - true - ); + this.projectService.onUpdateLanguageServiceStateForProject(this, /*languageServiceEnabled*/ + true); } /** @internal */ cleanupProgram() { @@ -174262,7 +158462,7 @@ ${options.prefix}` : "\n" : options.prefix for (const f of this.program.getSourceFiles()) { this.detachScriptInfoIfNotRoot(f.fileName); } - this.program.forEachResolvedProjectReference((ref) => this.detachScriptInfoFromProject(ref.sourceFile.fileName)); + this.program.forEachResolvedProjectReference(ref => this.detachScriptInfoFromProject(ref.sourceFile.fileName)); this.program = void 0; } } @@ -174283,11 +158483,8 @@ ${options.prefix}` : "\n" : options.prefix this.resolutionCache.closeTypeRootsWatch(); this.clearGeneratedFileWatch(); this.projectService.verifyDocumentRegistry(); - this.projectService.onUpdateLanguageServiceStateForProject( - this, - /*languageServiceEnabled*/ - false - ); + this.projectService.onUpdateLanguageServiceStateForProject(this, /*languageServiceEnabled*/ + false); } getProjectName() { return this.projectName; @@ -174296,12 +158493,14 @@ ${options.prefix}` : "\n" : options.prefix if (!newTypeAcquisition || !newTypeAcquisition.include) { return newTypeAcquisition; } - return { ...newTypeAcquisition, include: this.removeExistingTypings(newTypeAcquisition.include) }; + return { + ...newTypeAcquisition, + include: this.removeExistingTypings(newTypeAcquisition.include) + }; } getExternalFiles(updateLevel) { - return sort(flatMap(this.plugins, (plugin) => { - if (typeof plugin.module.getExternalFiles !== "function") - return; + return sort(flatMap(this.plugins, plugin => { + if (typeof plugin.module.getExternalFiles !== "function") return; try { return plugin.module.getExternalFiles(this, updateLevel || 0 /* Update */); } catch (e) { @@ -174327,7 +158526,7 @@ ${options.prefix}` : "\n" : options.prefix this.projectService.typingsCache.onProjectClosed(this); this.closeWatchingTypingLocations(); this.cleanupProgram(); - forEach(this.externalFiles, (externalFile) => this.detachScriptInfoIfNotRoot(externalFile)); + forEach(this.externalFiles, externalFile => this.detachScriptInfoIfNotRoot(externalFile)); for (const root of this.rootFiles) { root.detachFromProject(this); } @@ -174379,7 +158578,7 @@ ${options.prefix}` : "\n" : options.prefix return false; } getRootFiles() { - return this.rootFiles && this.rootFiles.map((info) => info.fileName); + return this.rootFiles && this.rootFiles.map(info => info.fileName); } /** @internal */ getRootFilesMap() { @@ -174392,7 +158591,7 @@ ${options.prefix}` : "\n" : options.prefix if (!this.languageServiceEnabled) { return this.rootFiles; } - return map(this.program.getSourceFiles(), (sourceFile) => { + return map(this.program.getSourceFiles(), sourceFile => { const scriptInfo = this.projectService.getScriptInfoForPath(sourceFile.resolvedPath); Debug.assert(!!scriptInfo, "getScriptInfo", () => `scriptInfo for a file '${sourceFile.fileName}' Path: '${sourceFile.path}' / '${sourceFile.resolvedPath}' is missing.`); return scriptInfo; @@ -174437,7 +158636,7 @@ ${options.prefix}` : "\n" : options.prefix } /** @internal */ getFileNamesWithRedirectInfo(includeProjectReferenceRedirectInfo) { - return this.getFileNames().map((fileName) => ({ + return this.getFileNames().map(fileName => ({ fileName, isSourceOfProjectReferenceRedirect: includeProjectReferenceRedirectInfo && this.isSourceOfProjectReferenceRedirect(fileName) })); @@ -174461,10 +158660,8 @@ ${options.prefix}` : "\n" : options.prefix 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; } @@ -174483,14 +158680,19 @@ ${options.prefix}` : "\n" : options.prefix addRoot(info, fileName) { Debug.assert(!this.isRoot(info)); this.rootFiles.push(info); - this.rootFilesMap.set(info.path, { fileName: fileName || info.fileName, info }); + this.rootFilesMap.set(info.path, { + fileName: fileName || info.fileName, + info + }); info.attachToProject(this); this.markAsDirty(); } // add a root file that doesnt exist on host addMissingFileRoot(fileName) { const path = this.projectService.toPath(fileName); - this.rootFilesMap.set(path, { fileName }); + this.rootFilesMap.set(path, { + fileName + }); this.markAsDirty(); } removeFile(info, fileExists, detachFromProject) { @@ -174509,13 +158711,13 @@ ${options.prefix}` : "\n" : options.prefix this.markAsDirty(); } registerFileUpdate(fileName) { - (this.updatedFileNames || (this.updatedFileNames = /* @__PURE__ */ new Set())).add(fileName); + (this.updatedFileNames || (this.updatedFileNames = /* @__PURE__ */new Set())).add(fileName); } /** @internal */ markFileAsDirty(changedFile) { this.markAsDirty(); if (this.exportMapCache && !this.exportMapCache.isEmpty()) { - (this.changedFilesForExportMapCache || (this.changedFilesForExportMapCache = /* @__PURE__ */ new Set())).add(changedFile); + (this.changedFilesForExportMapCache || (this.changedFilesForExportMapCache = /* @__PURE__ */new Set())).add(changedFile); } } markAsDirty() { @@ -174560,7 +158762,10 @@ ${options.prefix}` : "\n" : options.prefix */ updateGraph() { var _a, _b, _c, _d, _e; - (_a = tracing) == null ? void 0 : _a.push(tracing.Phase.Session, "updateGraph", { name: this.projectName, kind: ProjectKind[this.projectKind] }); + (_a = tracing) == null ? void 0 : _a.push(tracing.Phase.Session, "updateGraph", { + name: this.projectName, + kind: ProjectKind[this.projectKind] + }); (_b = perfLogger) == null ? void 0 : _b.logStartUpdateGraph(); this.resolutionCache.startRecordingFilesWithChangedResolutions(); const hasNewProgram = this.updateGraphWorker(); @@ -174584,8 +158789,7 @@ ${options.prefix}` : "\n" : options.prefix this.projectProgramVersion++; } if (hasAddedorRemovedFiles) { - if (!this.autoImportProviderHost) - this.autoImportProviderHost = void 0; + if (!this.autoImportProviderHost) this.autoImportProviderHost = void 0; (_c = this.autoImportProviderHost) == null ? void 0 : _c.markAsDirty(); } if (isFirstProgramLoad) { @@ -174597,14 +158801,8 @@ ${options.prefix}` : "\n" : options.prefix } /** @internal */ updateTypingFiles(typingFiles) { - if (enumerateInsertsAndDeletes( - typingFiles, - this.typingFiles, - getStringComparer(!this.useCaseSensitiveFileNames()), - /*inserted*/ - noop, - (removed) => this.detachScriptInfoFromProject(removed) - )) { + if (enumerateInsertsAndDeletes(typingFiles, this.typingFiles, getStringComparer(!this.useCaseSensitiveFileNames()), /*inserted*/ + noop, removed => this.detachScriptInfoFromProject(removed))) { this.typingFiles = typingFiles; this.resolutionCache.setFilesWithInvalidatedNonRelativeUnresolvedImports(this.cachedUnresolvedImportsPerFile); this.projectService.delayUpdateProjectGraphAndEnsureProjectStructureForOpenFiles(this); @@ -174612,14 +158810,16 @@ ${options.prefix}` : "\n" : options.prefix } /** @internal */ closeWatchingTypingLocations() { - if (this.typingWatchers) - clearMap(this.typingWatchers, closeFileWatcher); + if (this.typingWatchers) clearMap(this.typingWatchers, closeFileWatcher); this.typingWatchers = void 0; } /** @internal */ onTypingInstallerWatchInvoke() { this.typingWatchers.isInvoked = true; - this.projectService.updateTypingsForProject({ projectName: this.getProjectName(), kind: ActionInvalidate }); + this.projectService.updateTypingsForProject({ + projectName: this.getProjectName(), + kind: ActionInvalidate + }); } /** @internal */ watchTypingLocations(files) { @@ -174632,39 +158832,18 @@ ${options.prefix}` : "\n" : options.prefix 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); toRemove.delete(canonicalPath); if (!this.typingWatchers.has(canonicalPath)) { - this.typingWatchers.set( - canonicalPath, - typingsWatcherType === "FileWatcher" /* FileWatcher */ ? this.projectService.watchFactory.watchFile( - path, - () => !this.typingWatchers.isInvoked ? this.onTypingInstallerWatchInvoke() : this.writeLog(`TypingWatchers already invoked`), - 2e3 /* High */, - this.projectService.getWatchOptions(this), - WatchType.TypingInstallerLocationFile, - this - ) : 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`); - this.onTypingInstallerWatchInvoke(); - }, - 1 /* Recursive */, - this.projectService.getWatchOptions(this), - WatchType.TypingInstallerLocationDirectory, - this - ) - ); + this.typingWatchers.set(canonicalPath, typingsWatcherType === "FileWatcher" /* FileWatcher */ ? this.projectService.watchFactory.watchFile(path, () => !this.typingWatchers.isInvoked ? this.onTypingInstallerWatchInvoke() : this.writeLog(`TypingWatchers already invoked`), 2e3 /* High */, this.projectService.getWatchOptions(this), WatchType.TypingInstallerLocationFile, this) : 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`); + this.onTypingInstallerWatchInvoke(); + }, 1 /* Recursive */, this.projectService.getWatchOptions(this), WatchType.TypingInstallerLocationDirectory, this)); } }; for (const file of files) { @@ -174680,6 +158859,7 @@ ${options.prefix}` : "\n" : options.prefix } else { createProjectWatcher(file, "DirectoryWatcher" /* DirectoryWatcher */); } + continue; } if (containsPath(this.projectService.typingsInstaller.globalTypingsCacheLocation, file, this.currentDirectory, !this.useCaseSensitiveFileNames())) { @@ -174688,6 +158868,7 @@ ${options.prefix}` : "\n" : options.prefix } createProjectWatcher(file, "DirectoryWatcher" /* DirectoryWatcher */); } + toRemove.forEach((watch, path) => { watch.close(); this.typingWatchers.delete(path); @@ -174699,7 +158880,7 @@ ${options.prefix}` : "\n" : options.prefix } removeExistingTypings(include) { const existing = getAutomaticTypeDirectiveNames(this.getCompilerOptions(), this.directoryStructureHost); - return include.filter((i) => !existing.includes(i)); + return include.filter(i => !existing.includes(i)); } updateGraphWorker() { var _a, _b; @@ -174708,7 +158889,10 @@ ${options.prefix}` : "\n" : options.prefix Debug.assert(!this.isClosed(), "Called update graph worker of closed project"); this.writeLog(`Starting updateGraphWorker: Project: ${this.getProjectName()}`); const start = timestamp(); - const { hasInvalidatedResolutions, hasInvalidatedLibResolutions } = this.resolutionCache.createHasInvalidatedResolutions(returnFalse, returnFalse); + const { + hasInvalidatedResolutions, + hasInvalidatedLibResolutions + } = this.resolutionCache.createHasInvalidatedResolutions(returnFalse, returnFalse); this.hasInvalidatedResolutions = hasInvalidatedResolutions; this.hasInvalidatedLibResolutions = hasInvalidatedLibResolutions; this.resolutionCache.startCachingPerDirectoryResolution(); @@ -174725,39 +158909,25 @@ ${options.prefix}` : "\n" : options.prefix for (const f of oldProgram.getSourceFiles()) { const newFile = this.program.getSourceFileByPath(f.resolvedPath); if (!newFile || f.resolvedPath === f.path && newFile.resolvedPath !== f.path) { - this.detachScriptInfoFromProject( - f.fileName, - !!this.program.getSourceFileByPath(f.path), - /*syncDirWatcherRemove*/ - true - ); + this.detachScriptInfoFromProject(f.fileName, !!this.program.getSourceFileByPath(f.path), /*syncDirWatcherRemove*/ + true); } } - oldProgram.forEachResolvedProjectReference((resolvedProjectReference) => { + oldProgram.forEachResolvedProjectReference(resolvedProjectReference => { if (!this.program.getResolvedProjectReferenceByPath(resolvedProjectReference.sourceFile.path)) { - this.detachScriptInfoFromProject( - resolvedProjectReference.sourceFile.fileName, - /*noRemoveResolution*/ - void 0, - /*syncDirWatcherRemove*/ - true - ); + this.detachScriptInfoFromProject(resolvedProjectReference.sourceFile.fileName, /*noRemoveResolution*/ + void 0, /*syncDirWatcherRemove*/ + true); } }); } - updateMissingFilePathsWatch( - this.program, - this.missingFilesMap || (this.missingFilesMap = /* @__PURE__ */ new Map()), - // Watch the missing files - (missingFilePath) => this.addMissingFileWatcher(missingFilePath) - ); + updateMissingFilePathsWatch(this.program, this.missingFilesMap || (this.missingFilesMap = /* @__PURE__ */new Map()), + // Watch the missing files + missingFilePath => this.addMissingFileWatcher(missingFilePath)); if (this.generatedFilesMap) { const outPath = outFile(this.compilerOptions); if (isGeneratedFileWatcher(this.generatedFilesMap)) { - if (!outPath || !this.isValidGeneratedFileWatcher( - removeFileExtension(outPath) + ".d.ts" /* Dts */, - this.generatedFilesMap - )) { + if (!outPath || !this.isValidGeneratedFileWatcher(removeFileExtension(outPath) + ".d.ts" /* Dts */, this.generatedFilesMap)) { this.clearGeneratedFileWatch(); } } else { @@ -174766,10 +158936,7 @@ ${options.prefix}` : "\n" : options.prefix } else { this.generatedFilesMap.forEach((watcher, source) => { const sourceFile = this.program.getSourceFileByPath(source); - if (!sourceFile || sourceFile.resolvedPath !== source || !this.isValidGeneratedFileWatcher( - getDeclarationEmitOutputFilePathWorker(sourceFile.fileName, this.compilerOptions, this.currentDirectory, this.program.getCommonSourceDirectory(), this.getCanonicalFileName), - watcher - )) { + if (!sourceFile || sourceFile.resolvedPath !== source || !this.isValidGeneratedFileWatcher(getDeclarationEmitOutputFilePathWorker(sourceFile.fileName, this.compilerOptions, this.currentDirectory, this.program.getCommonSourceDirectory(), this.getCanonicalFileName), watcher)) { closeFileWatcherOf(watcher); this.generatedFilesMap.delete(source); } @@ -174787,7 +158954,7 @@ ${options.prefix}` : "\n" : options.prefix if (this.hasAddedorRemovedFiles || oldProgram && !this.program.structureIsReused) { this.exportMapCache.clear(); } else if (this.changedFilesForExportMapCache && oldProgram && this.program) { - forEachKey(this.changedFilesForExportMapCache, (fileName) => { + forEachKey(this.changedFilesForExportMapCache, fileName => { const oldSourceFile = oldProgram.getSourceFileByPath(fileName); const sourceFile = this.program.getSourceFileByPath(fileName); if (!oldSourceFile || !sourceFile) { @@ -174807,43 +158974,30 @@ ${options.prefix}` : "\n" : options.prefix } const oldExternalFiles = this.externalFiles || emptyArray2; this.externalFiles = this.getExternalFiles(); - enumerateInsertsAndDeletes( - this.externalFiles, - oldExternalFiles, - getStringComparer(!this.useCaseSensitiveFileNames()), - // Ensure a ScriptInfo is created for new external files. This is performed indirectly - // by the host for files in the program when the program is retrieved above but - // the program doesn't contain external files so this must be done explicitly. - (inserted) => { - const scriptInfo = this.projectService.getOrCreateScriptInfoNotOpenedByClient(inserted, this.currentDirectory, this.directoryStructureHost); - scriptInfo == null ? void 0 : scriptInfo.attachToProject(this); - }, - (removed) => this.detachScriptInfoFromProject(removed) - ); + enumerateInsertsAndDeletes(this.externalFiles, oldExternalFiles, getStringComparer(!this.useCaseSensitiveFileNames()), + // Ensure a ScriptInfo is created for new external files. This is performed indirectly + // by the host for files in the program when the program is retrieved above but + // the program doesn't contain external files so this must be done explicitly. + inserted => { + const scriptInfo = this.projectService.getOrCreateScriptInfoNotOpenedByClient(inserted, this.currentDirectory, this.directoryStructureHost); + scriptInfo == null ? void 0 : scriptInfo.attachToProject(this); + }, removed => this.detachScriptInfoFromProject(removed)); const elapsed = timestamp() - start; this.sendPerformanceEvent("UpdateGraph", elapsed); this.writeLog(`Finishing updateGraphWorker: Project: ${this.getProjectName()} Version: ${this.getProjectVersion()} structureChanged: ${hasNewProgram}${this.program ? ` structureIsReused:: ${StructureIsReused[this.program.structureIsReused]}` : ""} Elapsed: ${elapsed}ms`); if (this.projectService.logger.isTestLogger) { if (this.program !== oldProgram) { - this.print( - /*writeProjectFileNames*/ - true, - this.hasAddedorRemovedFiles, - /*writeFileVersionAndText*/ - true - ); + this.print( /*writeProjectFileNames*/ + true, this.hasAddedorRemovedFiles, /*writeFileVersionAndText*/ + true); } else { this.writeLog(`Same program as before`); } } else if (this.hasAddedorRemovedFiles) { - this.print( - /*writeProjectFileNames*/ - true, - /*writeFileExplaination*/ - true, - /*writeFileVersionAndText*/ - false - ); + this.print( /*writeProjectFileNames*/ + true, /*writeFileExplaination*/ + true, /*writeFileVersionAndText*/ + false); } else if (this.program !== oldProgram) { this.writeLog(`Different program with same set of files`); } @@ -174867,26 +159021,18 @@ ${options.prefix}` : "\n" : options.prefix 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( - missingFilePath, - (fileName, eventKind) => { - if (isConfiguredProject(this)) { - this.getCachedDirectoryStructureHost().addOrDeleteFile(fileName, missingFilePath, eventKind); - } - if (eventKind === 0 /* Created */ && this.missingFilesMap.has(missingFilePath)) { - this.missingFilesMap.delete(missingFilePath); - fileWatcher.close(); - this.projectService.delayUpdateProjectGraphAndEnsureProjectStructureForOpenFiles(this); - } - }, - 500 /* Medium */, - this.projectService.getWatchOptions(this), - WatchType.MissingFile, - this - ); + const fileWatcher = this.projectService.watchFactory.watchFile(missingFilePath, (fileName, eventKind) => { + if (isConfiguredProject(this)) { + this.getCachedDirectoryStructureHost().addOrDeleteFile(fileName, missingFilePath, eventKind); + } + if (eventKind === 0 /* Created */ && this.missingFilesMap.has(missingFilePath)) { + this.missingFilesMap.delete(missingFilePath); + fileWatcher.close(); + this.projectService.delayUpdateProjectGraphAndEnsureProjectStructureForOpenFiles(this); + } + }, 500 /* Medium */, this.projectService.getWatchOptions(this), WatchType.MissingFile, this); return fileWatcher; } isWatchedMissingFile(path) { @@ -174905,10 +159051,9 @@ ${options.prefix}` : "\n" : options.prefix 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(); + this.generatedFilesMap = /* @__PURE__ */new Map(); } this.generatedFilesMap.set(path, this.createGeneratedFileWatcher(generatedFile)); } @@ -174916,17 +159061,10 @@ ${options.prefix}` : "\n" : options.prefix createGeneratedFileWatcher(generatedFile) { return { generatedFilePath: this.toPath(generatedFile), - watcher: this.projectService.watchFactory.watchFile( - generatedFile, - () => { - this.clearSourceMapperCache(); - this.projectService.delayUpdateProjectGraphAndEnsureProjectStructureForOpenFiles(this); - }, - 2e3 /* High */, - this.projectService.getWatchOptions(this), - WatchType.MissingGeneratedFile, - this - ) + watcher: this.projectService.watchFactory.watchFile(generatedFile, () => { + this.clearSourceMapperCache(); + this.projectService.delayUpdateProjectGraphAndEnsureProjectStructureForOpenFiles(this); + }, 2e3 /* High */, this.projectService.getWatchOptions(this), WatchType.MissingGeneratedFile, this) }; } isValidGeneratedFileWatcher(generateFile, watcher) { @@ -174953,20 +159091,14 @@ ${options.prefix}` : "\n" : options.prefix return this.projectService.getScriptInfo(uncheckedFileName); } filesToString(writeProjectFileNames) { - return this.filesToStringWorker( - writeProjectFileNames, - /*writeFileExplaination*/ - true, - /*writeFileVersionAndText*/ - false - ); + return this.filesToStringWorker(writeProjectFileNames, /*writeFileExplaination*/ + true, /*writeFileVersionAndText*/ + false); } /** @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}) `; @@ -174977,7 +159109,7 @@ ${options.prefix}` : "\n" : options.prefix } if (writeFileExplaination) { strBuilder += "\n\n"; - explainFiles(this.program, (s) => strBuilder += ` ${s} + explainFiles(this.program, s => strBuilder += ` ${s} `); } } @@ -174986,21 +159118,14 @@ ${options.prefix}` : "\n" : options.prefix /** @internal */ print(writeProjectFileNames, writeFileExplaination, writeFileVersionAndText) { this.writeLog(`Project '${this.projectName}' (${ProjectKind[this.projectKind]})`); - this.writeLog(this.filesToStringWorker( - writeProjectFileNames && this.projectService.logger.hasLevel(3 /* verbose */), - writeFileExplaination && this.projectService.logger.hasLevel(3 /* verbose */), - writeFileVersionAndText && this.projectService.logger.hasLevel(3 /* verbose */) - )); + this.writeLog(this.filesToStringWorker(writeProjectFileNames && this.projectService.logger.hasLevel(3 /* verbose */), writeFileExplaination && this.projectService.logger.hasLevel(3 /* verbose */), writeFileVersionAndText && this.projectService.logger.hasLevel(3 /* verbose */))); + this.writeLog("-----------------------------------------------"); if (this.autoImportProviderHost) { - this.autoImportProviderHost.print( - /*writeProjectFileNames*/ - false, - /*writeFileExplaination*/ - false, - /*writeFileVersionAndText*/ - false - ); + this.autoImportProviderHost.print( /*writeProjectFileNames*/ + false, /*writeFileExplaination*/ + false, /*writeFileVersionAndText*/ + false); } } setCompilerOptions(compilerOptions) { @@ -175039,10 +159164,10 @@ ${options.prefix}` : "\n" : options.prefix /** @internal */ getChangesSinceVersion(lastKnownVersion, includeProjectReferenceRedirectInfo) { var _a, _b; - const includeProjectReferenceRedirectInfoIfRequested = includeProjectReferenceRedirectInfo ? (files) => arrayFrom(files.entries(), ([fileName, isSourceOfProjectReferenceRedirect]) => ({ + const includeProjectReferenceRedirectInfoIfRequested = includeProjectReferenceRedirectInfo ? files => arrayFrom(files.entries(), ([fileName, isSourceOfProjectReferenceRedirect]) => ({ fileName, isSourceOfProjectReferenceRedirect - })) : (files) => arrayFrom(files.keys()); + })) : files => arrayFrom(files.keys()); if (!this.isInitialLoadPending()) { updateProjectIfDirty(this); } @@ -175058,20 +159183,19 @@ ${options.prefix}` : "\n" : options.prefix this.updatedFileNames = void 0; if (this.lastReportedFileNames && lastKnownVersion === this.lastReportedVersion) { if (this.projectProgramVersion === this.lastReportedVersion && !updatedFileNames) { - return { info, projectErrors: this.getGlobalProjectErrors() }; + return { + info, + projectErrors: this.getGlobalProjectErrors() + }; } const lastReportedFileNames = this.lastReportedFileNames; - const externalFiles = ((_a = this.externalFiles) == null ? void 0 : _a.map((f) => ({ + const externalFiles = ((_a = this.externalFiles) == null ? void 0 : _a.map(f => ({ fileName: toNormalizedPath(f), isSourceOfProjectReferenceRedirect: false }))) || emptyArray2; - const currentFiles = arrayToMap( - this.getFileNamesWithRedirectInfo(!!includeProjectReferenceRedirectInfo).concat(externalFiles), - (info2) => info2.fileName, - (info2) => info2.isSourceOfProjectReferenceRedirect - ); - const added = /* @__PURE__ */ new Map(); - const removed = /* @__PURE__ */ new Map(); + const currentFiles = arrayToMap(this.getFileNamesWithRedirectInfo(!!includeProjectReferenceRedirectInfo).concat(externalFiles), info2 => info2.fileName, info2 => info2.isSourceOfProjectReferenceRedirect); + const added = /* @__PURE__ */new Map(); + const removed = /* @__PURE__ */new Map(); const updated = updatedFileNames ? arrayFrom(updatedFileNames.keys()) : []; const updatedRedirects = []; forEachEntry(currentFiles, (isSourceOfProjectReferenceRedirect, fileName) => { @@ -175096,7 +159220,7 @@ ${options.prefix}` : "\n" : options.prefix changes: { added: includeProjectReferenceRedirectInfoIfRequested(added), removed: includeProjectReferenceRedirectInfoIfRequested(removed), - updated: includeProjectReferenceRedirectInfo ? updated.map((fileName) => ({ + updated: includeProjectReferenceRedirectInfo ? updated.map(fileName => ({ fileName, isSourceOfProjectReferenceRedirect: this.isSourceOfProjectReferenceRedirect(fileName) })) : updated, @@ -175106,20 +159230,16 @@ ${options.prefix}` : "\n" : options.prefix }; } else { const projectFileNames = this.getFileNamesWithRedirectInfo(!!includeProjectReferenceRedirectInfo); - const externalFiles = ((_b = this.externalFiles) == null ? void 0 : _b.map((f) => ({ + const externalFiles = ((_b = this.externalFiles) == null ? void 0 : _b.map(f => ({ fileName: toNormalizedPath(f), isSourceOfProjectReferenceRedirect: false }))) || emptyArray2; const allFiles = projectFileNames.concat(externalFiles); - this.lastReportedFileNames = arrayToMap( - allFiles, - (info2) => info2.fileName, - (info2) => info2.isSourceOfProjectReferenceRedirect - ); + this.lastReportedFileNames = arrayToMap(allFiles, info2 => info2.fileName, info2 => info2.isSourceOfProjectReferenceRedirect); this.lastReportedVersion = this.projectProgramVersion; return { info, - files: includeProjectReferenceRedirectInfo ? allFiles : allFiles.map((f) => f.fileName), + files: includeProjectReferenceRedirectInfo ? allFiles : allFiles.map(f => f.fileName), projectErrors: this.getGlobalProjectErrors() }; } @@ -175135,15 +159255,12 @@ ${options.prefix}` : "\n" : options.prefix } /** @internal */ getGlobalPluginSearchPaths() { - return [ - ...this.projectService.pluginProbeLocations, - // ../../.. to walk from X/node_modules/typescript/lib/tsserver.js to X/node_modules/ - combinePaths(this.projectService.getExecutingFilePath(), "../../..") - ]; + return [...this.projectService.pluginProbeLocations, + // ../../.. to walk from X/node_modules/typescript/lib/tsserver.js to X/node_modules/ + combinePaths(this.projectService.getExecutingFilePath(), "../../..")]; } 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"); @@ -175151,12 +159268,13 @@ ${options.prefix}` : "\n" : options.prefix } 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); + this.enablePlugin({ + name: globalPluginName, + global: true + }, searchPaths); } } enablePlugin(pluginConfigEntry, searchPaths) { @@ -175177,7 +159295,9 @@ ${options.prefix}` : "\n" : options.prefix serverHost: this.projectService.host, session: this.projectService.session }; - const pluginModule = pluginModuleFactory({ typescript: ts_exports2 }); + const pluginModule = pluginModuleFactory({ + typescript: ts_exports2 + }); const newLS = pluginModule.create(info); for (const k of Object.keys(this.languageService)) { if (!(k in newLS)) { @@ -175187,14 +159307,17 @@ ${options.prefix}` : "\n" : options.prefix } this.projectService.logger.info(`Plugin validation succeeded`); this.languageService = newLS; - this.plugins.push({ name: configEntry.name, module: pluginModule }); + this.plugins.push({ + name: configEntry.name, + module: pluginModule + }); } catch (e) { this.projectService.logger.info(`Plugin activation failed: ${e}`); } } /** @internal */ onPluginConfigurationChanged(pluginName, configuration) { - this.plugins.filter((plugin) => plugin.name === pluginName).forEach((plugin) => { + this.plugins.filter(plugin => plugin.name === pluginName).forEach(plugin => { if (plugin.module.onConfigurationChanged) { plugin.module.onConfigurationChanged(configuration); } @@ -175206,8 +159329,7 @@ ${options.prefix}` : "\n" : options.prefix } /** @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, rootDir); } /** @internal */ @@ -175217,7 +159339,7 @@ ${options.prefix}` : "\n" : options.prefix /** @internal */ getPackageJsonsForAutoImport(rootDir) { const packageJsons = this.getPackageJsonsVisibleToFile(combinePaths(this.currentDirectory, inferredTypesContainingFile), rootDir); - this.packageJsonsForAutoImport = new Set(packageJsons.map((p) => p.fileName)); + this.packageJsonsForAutoImport = new Set(packageJsons.map(p => p.fileName)); return packageJsons; } /** @internal */ @@ -175242,6 +159364,7 @@ ${options.prefix}` : "\n" : options.prefix if (this.projectService.includePackageJsonAutoImports() === 0 /* Off */ || !this.languageServiceEnabled || isInsideNodeModules(this.currentDirectory) || !this.isDefaultProjectForOpenFiles()) { return 0 /* Off */; } + return this.projectService.includePackageJsonAutoImports(); } /** @internal */ @@ -175297,10 +159420,7 @@ ${options.prefix}` : "\n" : options.prefix } /** @internal */ isDefaultProjectForOpenFiles() { - return !!forEachEntry( - this.projectService.openFiles, - (_, fileName) => this.projectService.tryGetDefaultProjectForFile(toNormalizedPath(fileName)) === this - ); + return !!forEachEntry(this.projectService.openFiles, (_, fileName) => this.projectService.tryGetDefaultProjectForFile(toNormalizedPath(fileName)) === this); } /** @internal */ watchNodeModulesForPackageJsonChanges(directoryPath) { @@ -175341,23 +159461,12 @@ ${options.prefix}` : "\n" : options.prefix InferredProject2 = class extends Project3 { /** @internal */ constructor(projectService, documentRegistry, compilerOptions, watchOptions, projectRootPath, currentDirectory, typeAcquisition) { - super( - projectService.newInferredProjectName(), - 0 /* Inferred */, - projectService, - documentRegistry, - // TODO: GH#18217 - /*files*/ - void 0, - /*lastFileExceededProgramSize*/ - void 0, - compilerOptions, - /*compileOnSaveEnabled*/ - false, - watchOptions, - projectService.host, - currentDirectory - ); + super(projectService.newInferredProjectName(), 0 /* Inferred */, projectService, documentRegistry, + // TODO: GH#18217 + /*files*/ + void 0, /*lastFileExceededProgramSize*/ + void 0, compilerOptions, /*compileOnSaveEnabled*/ + false, watchOptions, projectService.host, currentDirectory); this._isJsInferredProject = false; this.typeAcquisition = typeAcquisition; this.projectRootPath = projectRootPath && projectService.toCanonicalFileName(projectRootPath); @@ -175389,15 +159498,11 @@ ${options.prefix}` : "\n" : options.prefix Debug.assert(info.isScriptOpen()); this.projectService.startWatchingConfigFilesForInferredProjectRoot(info); if (!this._isJsInferredProject && info.isJavaScript()) { - this.toggleJsInferredProject( - /*isJsInferredProject*/ - true - ); + this.toggleJsInferredProject( /*isJsInferredProject*/ + true); } else if (this.isOrphan() && this._isJsInferredProject && !info.isJavaScript()) { - this.toggleJsInferredProject( - /*isJsInferredProject*/ - false - ); + this.toggleJsInferredProject( /*isJsInferredProject*/ + false); } super.addRoot(info); } @@ -175405,11 +159510,9 @@ ${options.prefix}` : "\n" : options.prefix this.projectService.stopWatchingConfigFilesForInferredProjectRoot(info); super.removeRoot(info); if (!this.isOrphan() && this._isJsInferredProject && info.isJavaScript()) { - if (every(this.getRootScriptInfos(), (rootInfo) => !rootInfo.isJavaScript())) { - this.toggleJsInferredProject( - /*isJsInferredProject*/ - false - ); + if (every(this.getRootScriptInfos(), rootInfo => !rootInfo.isJavaScript())) { + this.toggleJsInferredProject( /*isJsInferredProject*/ + false); } } } @@ -175421,7 +159524,7 @@ ${options.prefix}` : "\n" : options.prefix 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.stopWatchingConfigFilesForInferredProjectRoot(info)); super.close(); } getTypeAcquisition() { @@ -175434,23 +159537,11 @@ ${options.prefix}` : "\n" : options.prefix }; AuxiliaryProject = class extends Project3 { constructor(projectService, documentRegistry, compilerOptions, currentDirectory) { - super( - projectService.newAuxiliaryProjectName(), - 4 /* Auxiliary */, - projectService, - documentRegistry, - /*hasExplicitListOfFiles*/ - false, - /*lastFileExceededProgramSize*/ - void 0, - compilerOptions, - /*compileOnSaveEnabled*/ - false, - /*watchOptions*/ - void 0, - projectService.host, - currentDirectory - ); + super(projectService.newAuxiliaryProjectName(), 4 /* Auxiliary */, projectService, documentRegistry, /*hasExplicitListOfFiles*/ + false, /*lastFileExceededProgramSize*/ + void 0, compilerOptions, /*compileOnSaveEnabled*/ + false, /*watchOptions*/ + void 0, projectService.host, currentDirectory); } isOrphan() { return true; @@ -175462,22 +159553,10 @@ ${options.prefix}` : "\n" : options.prefix _AutoImportProviderProject = class _AutoImportProviderProject extends Project3 { /** @internal */ constructor(hostProject, initialRootNames, documentRegistry, compilerOptions) { - super( - hostProject.projectService.newAutoImportProviderProjectName(), - 3 /* AutoImportProvider */, - hostProject.projectService, - documentRegistry, - /*hasExplicitListOfFiles*/ - false, - /*lastFileExceededProgramSize*/ - void 0, - compilerOptions, - /*compileOnSaveEnabled*/ - false, - hostProject.getWatchOptions(), - hostProject.projectService.host, - hostProject.currentDirectory - ); + super(hostProject.projectService.newAutoImportProviderProjectName(), 3 /* AutoImportProvider */, hostProject.projectService, documentRegistry, /*hasExplicitListOfFiles*/ + false, /*lastFileExceededProgramSize*/ + void 0, compilerOptions, /*compileOnSaveEnabled*/ + false, hostProject.getWatchOptions(), hostProject.projectService.host, hostProject.currentDirectory); this.hostProject = hostProject; this.rootFileNames = initialRootNames; this.useSourceOfProjectReferenceRedirect = maybeBind(this.hostProject, this.hostProject.useSourceOfProjectReferenceRedirect); @@ -175510,13 +159589,7 @@ ${options.prefix}` : "\n" : options.prefix hostProject.log(`AutoImportProviderProject: attempted to add more than ${this.maxDependencies} dependencies. Aborting.`); return emptyArray; } - const packageJson = resolvePackageNameToPackageJson( - name, - hostProject.currentDirectory, - compilerOptions, - host, - program.getModuleResolutionCache() - ); + const packageJson = resolvePackageNameToPackageJson(name, hostProject.currentDirectory, compilerOptions, host, program.getModuleResolutionCache()); if (packageJson) { const entrypoints = getRootNamesFromPackageJson(packageJson, program, symlinkCache); if (entrypoints) { @@ -175525,15 +159598,9 @@ ${options.prefix}` : "\n" : options.prefix continue; } } - const done = forEach([hostProject.currentDirectory, hostProject.getGlobalTypingsCacheLocation()], (directory) => { + const done = forEach([hostProject.currentDirectory, hostProject.getGlobalTypingsCacheLocation()], directory => { if (directory) { - const typesPackageJson = resolvePackageNameToPackageJson( - `@types/${name}`, - directory, - compilerOptions, - host, - program.getModuleResolutionCache() - ); + const typesPackageJson = resolvePackageNameToPackageJson(`@types/${name}`, directory, compilerOptions, host, program.getModuleResolutionCache()); if (typesPackageJson) { const entrypoints = getRootNamesFromPackageJson(typesPackageJson, program, symlinkCache); rootNames = concatenate(rootNames, entrypoints); @@ -175542,16 +159609,10 @@ ${options.prefix}` : "\n" : options.prefix } } }); - if (done) - continue; + if (done) continue; if (packageJson && compilerOptions.allowJs && compilerOptions.maxNodeModuleJsDepth) { - const entrypoints = getRootNamesFromPackageJson( - packageJson, - program, - symlinkCache, - /*resolveJs*/ - true - ); + const entrypoints = getRootNamesFromPackageJson(packageJson, program, symlinkCache, /*resolveJs*/ + true); rootNames = concatenate(rootNames, entrypoints); dependenciesAdded += (entrypoints == null ? void 0 : entrypoints.length) ? 1 : 0; } @@ -175563,18 +159624,12 @@ ${options.prefix}` : "\n" : options.prefix return rootNames || emptyArray; function addDependency(dependency) { if (!startsWith(dependency, "@types/")) { - (dependencyNames || (dependencyNames = /* @__PURE__ */ new Set())).add(dependency); + (dependencyNames || (dependencyNames = /* @__PURE__ */new Set())).add(dependency); } } function getRootNamesFromPackageJson(packageJson, program2, symlinkCache, resolveJs) { var _a2; - const entrypoints = getEntrypointsFromPackageJsonInfo( - packageJson, - compilerOptions, - host, - program2.getModuleResolutionCache(), - resolveJs - ); + const entrypoints = getEntrypointsFromPackageJsonInfo(packageJson, compilerOptions, host, program2.getModuleResolutionCache(), resolveJs); if (entrypoints) { const real = (_a2 = host.realpath) == null ? void 0 : _a2.call(host, packageJson.packageDirectory); const realPath2 = real ? hostProject.toPath(real) : void 0; @@ -175585,7 +159640,7 @@ ${options.prefix}` : "\n" : options.prefix realPath: ensureTrailingDirectorySeparator(realPath2) }); } - return mapDefined(entrypoints, (entrypoint) => { + return mapDefined(entrypoints, entrypoint => { const resolvedFileName = isSymlink ? entrypoint.replace(packageJson.packageDirectory, real) : entrypoint; if (!program2.getSourceFile(resolvedFileName) && !(isSymlink && program2.getSourceFile(entrypoint))) { return resolvedFileName; @@ -175619,12 +159674,7 @@ ${options.prefix}` : "\n" : options.prefix updateGraph() { let rootFileNames = this.rootFileNames; if (!rootFileNames) { - rootFileNames = _AutoImportProviderProject.getRootFileNames( - this.hostProject.includePackageJsonAutoImports(), - this.hostProject, - this.hostProject.getHostForAutoImportProvider(), - this.getCompilationSettings() - ); + rootFileNames = _AutoImportProviderProject.getRootFileNames(this.hostProject.includePackageJsonAutoImports(), this.hostProject, this.hostProject.getHostForAutoImportProvider(), this.getCompilationSettings()); } this.projectService.setFileNamesOfAutpImportProviderOrAuxillaryProject(this, rootFileNames); this.rootFileNames = rootFileNames; @@ -175696,27 +159746,15 @@ ${options.prefix}` : "\n" : options.prefix ConfiguredProject2 = class extends Project3 { /** @internal */ constructor(configFileName, canonicalConfigFilePath, projectService, documentRegistry, cachedDirectoryStructureHost) { - super( - configFileName, - 1 /* Configured */, - projectService, - documentRegistry, - /*hasExplicitListOfFiles*/ - false, - /*lastFileExceededProgramSize*/ - void 0, - /*compilerOptions*/ - {}, - /*compileOnSaveEnabled*/ - false, - /*watchOptions*/ - void 0, - cachedDirectoryStructureHost, - getDirectoryPath(configFileName) - ); + super(configFileName, 1 /* Configured */, projectService, documentRegistry, /*hasExplicitListOfFiles*/ + false, /*lastFileExceededProgramSize*/ + void 0, /*compilerOptions*/ + {}, /*compileOnSaveEnabled*/ + false, /*watchOptions*/ + void 0, cachedDirectoryStructureHost, getDirectoryPath(configFileName)); this.canonicalConfigFilePath = canonicalConfigFilePath; /** @internal */ - this.openFileWatchTriggered = /* @__PURE__ */ new Map(); + this.openFileWatchTriggered = /* @__PURE__ */new Map(); /** @internal */ this.canConfigFileJsonReportNoInputFiles = false; /** Ref count to the project when opened from external project */ @@ -175744,7 +159782,9 @@ ${options.prefix}` : "\n" : options.prefix const canonicalConfigFilePath = asNormalizedPath(this.projectService.toCanonicalFileName(configFileName)); let configFileExistenceInfo = this.projectService.configFileExistenceInfoCache.get(canonicalConfigFilePath); if (!configFileExistenceInfo) { - this.projectService.configFileExistenceInfoCache.set(canonicalConfigFilePath, configFileExistenceInfo = { exists: this.projectService.host.fileExists(configFileName) }); + this.projectService.configFileExistenceInfoCache.set(canonicalConfigFilePath, configFileExistenceInfo = { + exists: this.projectService.host.fileExists(configFileName) + }); } this.projectService.ensureParsedConfigUptoDate(configFileName, canonicalConfigFilePath, configFileExistenceInfo, this); if (this.languageServiceEnabled && this.projectService.serverMode === 0 /* Semantic */) { @@ -175780,13 +159820,8 @@ ${options.prefix}` : "\n" : options.prefix 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, isInitialLoad, /*clearSemanticCache*/ + false); result = true; break; default: @@ -175814,7 +159849,7 @@ ${options.prefix}` : "\n" : options.prefix /** @internal */ setPotentialProjectReference(canonicalConfigPath) { Debug.assert(this.isInitialLoadPending()); - (this.potentialProjectReferences || (this.potentialProjectReferences = /* @__PURE__ */ new Set())).add(canonicalConfigPath); + (this.potentialProjectReferences || (this.potentialProjectReferences = /* @__PURE__ */new Set())).add(canonicalConfigPath); } /** @internal */ getResolvedProjectReferenceToRedirect(fileName) { @@ -175830,8 +159865,7 @@ ${options.prefix}` : "\n" : options.prefix 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"); @@ -175854,7 +159888,7 @@ ${options.prefix}` : "\n" : options.prefix * Get the errors that dont have any file name associated */ getGlobalProjectErrors() { - return filter(this.projectErrors, (diagnostic) => !diagnostic.file) || emptyArray2; + return filter(this.projectErrors, diagnostic => !diagnostic.file) || emptyArray2; } /** * Get all the project errors @@ -175890,12 +159924,7 @@ ${options.prefix}` : "\n" : options.prefix * @internal */ getDefaultChildProjectFromProjectWithReferences(info) { - return forEachResolvedProjectReferenceProject( - this, - info.path, - (child) => projectContainsInfoDirectly(child, info) ? child : void 0, - 0 /* Find */ - ); + 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 @@ -175914,18 +159943,10 @@ ${options.prefix}` : "\n" : options.prefix if (this.projectService.hasPendingProjectUpdate(this)) { return !!((_a = configFileExistenceInfo.openFilesImpactedByConfigFile) == null ? void 0 : _a.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; + 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 */ hasExternalProjectRef() { @@ -175942,20 +159963,8 @@ ${options.prefix}` : "\n" : options.prefix ExternalProject2 = class extends Project3 { /** @internal */ constructor(externalProjectName, projectService, documentRegistry, compilerOptions, lastFileExceededProgramSize, compileOnSaveEnabled, projectFilePath, watchOptions) { - super( - externalProjectName, - 2 /* External */, - projectService, - documentRegistry, - /*hasExplicitListOfFiles*/ - true, - lastFileExceededProgramSize, - compilerOptions, - compileOnSaveEnabled, - watchOptions, - projectService.host, - getDirectoryPath(projectFilePath || normalizeSlashes(externalProjectName)) - ); + super(externalProjectName, 2 /* External */, projectService, documentRegistry, /*hasExplicitListOfFiles*/ + true, lastFileExceededProgramSize, compilerOptions, compileOnSaveEnabled, watchOptions, projectService.host, getDirectoryPath(projectFilePath || normalizeSlashes(externalProjectName))); this.externalProjectName = externalProjectName; this.compileOnSaveEnabled = compileOnSaveEnabled; this.excludedFiles = []; @@ -175975,11 +159984,11 @@ ${options.prefix}` : "\n" : options.prefix // src/server/editorServices.ts function prepareConvertersForEnumLikeCompilerOptions(commandLineOptions) { - const map2 = /* @__PURE__ */ new Map(); + const map2 = /* @__PURE__ */new Map(); for (const option of commandLineOptions) { if (typeof option.type === "object") { const optionMap = option.type; - optionMap.forEach((value) => { + optionMap.forEach(value => { Debug.assert(typeof value === "number"); }); map2.set(option.name, optionMap); @@ -176006,21 +160015,22 @@ ${options.prefix}` : "\n" : options.prefix function convertWatchOptions(protocolOptions, currentDirectory) { let watchOptions; let errors; - optionsForWatch.forEach((option) => { + 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 = [])); }); - return watchOptions && { watchOptions, errors }; + return watchOptions && { + watchOptions, + errors + }; } function convertTypeAcquisition(protocolOptions) { let result; - typeAcquisitionDeclarations.forEach((option) => { + 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; @@ -176042,8 +160052,12 @@ ${options.prefix}` : "\n" : options.prefix return 0 /* Unknown */; } } + function convertUserPreferences(preferences) { - const { lazyConfiguredProjectsFromExternalProject, ...userPreferences } = preferences; + const { + lazyConfiguredProjectsFromExternalProject, + ...userPreferences + } = preferences; return userPreferences; } function findProjectByName(projectName, projects) { @@ -176062,8 +160076,7 @@ ${options.prefix}` : "\n" : options.prefix function forEachResolvedProjectReferenceProject(project, fileName, cb, projectReferenceProjectLoadKind, reason) { var _a; const resolvedRefs = (_a = project.getCurrentProgram()) == null ? void 0 : _a.getResolvedProjectReferences(); - if (!resolvedRefs) - return void 0; + if (!resolvedRefs) return void 0; let seenResolvedRefs; const possibleDefaultRef = fileName ? project.getResolvedProjectReferenceToRedirect(fileName) : void 0; if (possibleDefaultRef) { @@ -176071,31 +160084,15 @@ ${options.prefix}` : "\n" : options.prefix const child = project.projectService.findConfiguredProjectByProjectName(configFileName); if (child) { const result = cb(child); - if (result) - return result; + if (result) return result; } else if (projectReferenceProjectLoadKind !== 0 /* Find */) { - seenResolvedRefs = /* @__PURE__ */ new Map(); - const result = forEachResolvedProjectReferenceProjectWorker( - resolvedRefs, - project.getCompilerOptions(), - (ref, loadKind) => possibleDefaultRef === ref ? callback(ref, loadKind) : void 0, - projectReferenceProjectLoadKind, - project.projectService, - seenResolvedRefs - ); - if (result) - return result; + seenResolvedRefs = /* @__PURE__ */new Map(); + const result = forEachResolvedProjectReferenceProjectWorker(resolvedRefs, project.getCompilerOptions(), (ref, loadKind) => possibleDefaultRef === ref ? callback(ref, loadKind) : void 0, projectReferenceProjectLoadKind, project.projectService, seenResolvedRefs); + if (result) return result; seenResolvedRefs.clear(); } } - return forEachResolvedProjectReferenceProjectWorker( - resolvedRefs, - project.getCompilerOptions(), - (ref, loadKind) => possibleDefaultRef !== ref ? callback(ref, loadKind) : void 0, - projectReferenceProjectLoadKind, - project.projectService, - seenResolvedRefs - ); + return forEachResolvedProjectReferenceProjectWorker(resolvedRefs, project.getCompilerOptions(), (ref, loadKind) => possibleDefaultRef !== ref ? callback(ref, loadKind) : void 0, projectReferenceProjectLoadKind, project.projectService, seenResolvedRefs); 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)); @@ -176104,9 +160101,8 @@ ${options.prefix}` : "\n" : options.prefix } function forEachResolvedProjectReferenceProjectWorker(resolvedProjectReferences, parentOptions, cb, projectReferenceProjectLoadKind, projectService, seenResolvedRefs) { const loadKind = parentOptions.disableReferencedProjectLoad ? 0 /* Find */ : projectReferenceProjectLoadKind; - return forEach(resolvedProjectReferences, (ref) => { - if (!ref) - return void 0; + return forEach(resolvedProjectReferences, ref => { + 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); @@ -176117,7 +160113,7 @@ ${options.prefix}` : "\n" : options.prefix if (result) { return result; } - (seenResolvedRefs || (seenResolvedRefs = /* @__PURE__ */ new Map())).set(canonicalPath, loadKind); + (seenResolvedRefs || (seenResolvedRefs = /* @__PURE__ */new Map())).set(canonicalPath, loadKind); return ref.references && forEachResolvedProjectReferenceProjectWorker(ref.references, ref.commandLine.options, cb, loadKind, projectService, seenResolvedRefs); }); } @@ -176132,12 +160128,7 @@ ${options.prefix}` : "\n" : options.prefix return refProject && cb(refProject); } function forEachReferencedProject(project, cb) { - return forEachAnyProjectReferenceKind( - project, - (resolvedRef) => callbackRefProject(project, cb, resolvedRef.sourceFile.path), - (projectRef) => callbackRefProject(project, cb, project.toPath(resolveProjectReferencePath(projectRef))), - (potentialProjectRef) => callbackRefProject(project, cb, potentialProjectRef) - ); + return forEachAnyProjectReferenceKind(project, resolvedRef => callbackRefProject(project, cb, resolvedRef.sourceFile.path), projectRef => callbackRefProject(project, cb, project.toPath(resolveProjectReferencePath(projectRef))), potentialProjectRef => callbackRefProject(project, cb, potentialProjectRef)); } function getDetailWatchInfo(watchType, project) { return `${isString(project) ? `Config: ${project} ` : project ? `Project: ${project.getProjectName()} ` : ""}WatchType: ${watchType}`; @@ -176162,18 +160153,22 @@ ${options.prefix}` : "\n" : options.prefix return () => nameFactory(nextId++); } function getHostWatcherMap() { - return { idToCallbacks: /* @__PURE__ */ new Map(), pathToId: /* @__PURE__ */ new Map() }; + 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(); let ids = 1; - service.session.addProtocolHandler("watchChange" /* WatchChange */, (req) => { + service.session.addProtocolHandler("watchChange" /* WatchChange */, req => { onWatchChange(req.arguments); - return { responseRequired: false }; + return { + responseRequired: false + }; }); return { watchFile: watchFile2, @@ -176182,62 +160177,75 @@ ${options.prefix}` : "\n" : options.prefix useCaseSensitiveFileNames: service.host.useCaseSensitiveFileNames }; function watchFile2(path, callback) { - return getOrCreateFileWatcher( - watchedFiles, - path, - callback, - (id) => ({ eventName: CreateFileWatcherEvent, data: { id, path } }) - ); + return getOrCreateFileWatcher(watchedFiles, path, callback, id => ({ + eventName: CreateFileWatcherEvent, + data: { + id, + path + } + })); } function watchDirectory(path, callback, recursive) { - return getOrCreateFileWatcher( - recursive ? watchedDirectoriesRecursive : watchedDirectories, - path, - callback, - (id) => ({ eventName: CreateDirectoryWatcherEvent, data: { id, path, recursive: !!recursive } }) - ); + return getOrCreateFileWatcher(recursive ? watchedDirectoriesRecursive : watchedDirectories, path, callback, id => ({ + eventName: CreateDirectoryWatcherEvent, + data: { + id, + path, + recursive: !!recursive + } + })); } - function getOrCreateFileWatcher({ pathToId, idToCallbacks }, path, callback, event) { + 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()); + idToCallbacks.set(id, callbacks = /* @__PURE__ */new Set()); service.eventHandler(event(id)); } callbacks.add(callback); 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 } }); + service.eventHandler({ + eventName: CloseFileWatcherEvent, + data: { + id + } + }); } }; } - function onWatchChange({ id, path, eventType }) { + function onWatchChange({ + id, + path, + eventType + }) { onFileWatcherCallback(id, path, eventType); onDirectoryWatcherCallback(watchedDirectories, id, path, eventType); onDirectoryWatcherCallback(watchedDirectoriesRecursive, id, path, eventType); } function onFileWatcherCallback(id, eventPath, eventType) { var _a; - (_a = watchedFiles.idToCallbacks.get(id)) == null ? void 0 : _a.forEach((callback) => { + (_a = watchedFiles.idToCallbacks.get(id)) == null ? void 0 : _a.forEach(callback => { const eventKind = eventType === "create" ? 0 /* Created */ : eventType === "delete" ? 2 /* Deleted */ : 1 /* Changed */; callback(eventPath, eventKind); }); } - function onDirectoryWatcherCallback({ idToCallbacks }, id, eventPath, eventType) { + function onDirectoryWatcherCallback({ + idToCallbacks + }, id, eventPath, eventType) { var _a; - if (eventType === "update") - return; - (_a = idToCallbacks.get(id)) == null ? void 0 : _a.forEach((callback) => { + if (eventType === "update") return; + (_a = idToCallbacks.get(id)) == null ? void 0 : _a.forEach(callback => { callback(eventPath); }); } @@ -176260,19 +160268,16 @@ ${options.prefix}` : "\n" : options.prefix return config.kind !== void 0; } function printProjectWithoutFileNames(project) { - project.print( - /*writeProjectFileNames*/ - false, - /*writeFileExplaination*/ - false, - /*writeFileVersionAndText*/ - false - ); + project.print( /*writeProjectFileNames*/ + false, /*writeFileExplaination*/ + false, /*writeFileVersionAndText*/ + false); } var maxProgramSizeForNonTsFiles, maxFileSize, ProjectsUpdatedInBackgroundEvent, ProjectLoadingStartEvent, ProjectLoadingFinishEvent, LargeFileReferencedEvent, ConfigFileDiagEvent, ProjectLanguageServiceStateEvent, ProjectInfoTelemetryEvent, OpenFileInfoTelemetryEvent, CreateFileWatcherEvent, CreateDirectoryWatcherEvent, CloseFileWatcherEvent, ensureProjectForOpenFileSchedule, compilerOptionConverters, watchOptionsConverters, indentStyle, defaultTypeSafeList, fileNamePropertyReader, externalFilePropertyReader, noopConfigFileWatcher, ProjectReferenceProjectLoadKind, _ProjectService, ProjectService3; var init_editorServices = __esm({ "src/server/editorServices.ts"() { "use strict"; + init_ts7(); init_ts_server3(); init_protocol(); @@ -176297,6 +160302,7 @@ ${options.prefix}` : "\n" : options.prefix block: 1 /* Block */, smart: 2 /* Smart */ })); + defaultTypeSafeList = { "jquery": { // jquery files can have names like "jquery-1.10.2.min.js" (or "jquery.intellisense.js") @@ -176312,6 +160318,7 @@ ${options.prefix}` : "\n" : options.prefix types: ["winjs"] // And fetch the @types package for WinJS }, + "Kendo": { // e.g. /Kendo3/wwwroot/lib/kendo/kendo.all.min.js match: /^(.*\/kendo(-ui)?)\/kendo\.all(\.min)?\.js$/i, @@ -176327,19 +160334,20 @@ ${options.prefix}` : "\n" : options.prefix types: ["office"] // @types package to fetch instead }, + "References": { match: /^(.*\/_references\.js)$/i, exclude: [["^", 1, "$"]] } }; fileNamePropertyReader = { - getFileName: (x) => x, + getFileName: x => x, getScriptKind: (fileName, extraFileExtensions) => { let result; if (extraFileExtensions) { const fileExtension = getAnyExtensionFromPath(fileName); if (fileExtension) { - some(extraFileExtensions, (info) => { + some(extraFileExtensions, info => { if (info.extension === fileExtension) { result = info.scriptKind; return true; @@ -176350,16 +160358,18 @@ ${options.prefix}` : "\n" : options.prefix } return result; }, - hasMixedContent: (fileName, extraFileExtensions) => some(extraFileExtensions, (ext) => ext.isMixedContent && fileExtensionIs(fileName, ext.extension)) + hasMixedContent: (fileName, extraFileExtensions) => some(extraFileExtensions, ext => ext.isMixedContent && fileExtensionIs(fileName, ext.extension)) }; externalFilePropertyReader = { - getFileName: (x) => x.fileName, - getScriptKind: (x) => tryConvertScriptKindName(x.scriptKind), + getFileName: x => x.fileName, + getScriptKind: x => tryConvertScriptKindName(x.scriptKind), // TODO: GH#18217 - hasMixedContent: (x) => !!x.hasMixedContent + hasMixedContent: x => !!x.hasMixedContent }; - noopConfigFileWatcher = { close: noop }; - ProjectReferenceProjectLoadKind = /* @__PURE__ */ ((ProjectReferenceProjectLoadKind2) => { + noopConfigFileWatcher = { + close: noop + }; + ProjectReferenceProjectLoadKind = /* @__PURE__ */(ProjectReferenceProjectLoadKind2 => { ProjectReferenceProjectLoadKind2[ProjectReferenceProjectLoadKind2["Find"] = 0] = "Find"; ProjectReferenceProjectLoadKind2[ProjectReferenceProjectLoadKind2["FindCreate"] = 1] = "FindCreate"; ProjectReferenceProjectLoadKind2[ProjectReferenceProjectLoadKind2["FindCreateLoad"] = 2] = "FindCreateLoad"; @@ -176372,20 +160382,20 @@ ${options.prefix}` : "\n" : options.prefix * * @internal */ - this.filenameToScriptInfo = /* @__PURE__ */ new Map(); - this.nodeModulesWatchers = /* @__PURE__ */ new Map(); + this.filenameToScriptInfo = /* @__PURE__ */new Map(); + this.nodeModulesWatchers = /* @__PURE__ */new Map(); /** * Contains all the deleted script info's version information so that * it does not reset when creating script info again * (and could have potentially collided with version where contents mismatch) */ - this.filenameToScriptInfoVersion = /* @__PURE__ */ new Map(); + this.filenameToScriptInfoVersion = /* @__PURE__ */new Map(); // Set of all '.js' files ever opened. - this.allJsFilesForOpenFileTelemetry = /* @__PURE__ */ new Map(); + this.allJsFilesForOpenFileTelemetry = /* @__PURE__ */new Map(); /** * maps external project file name to list of config files that were the part of this project */ - this.externalProjectToConfiguredProjectMap = /* @__PURE__ */ new Map(); + this.externalProjectToConfiguredProjectMap = /* @__PURE__ */new Map(); /** * external projects (configuration and list of root files is not controlled by tsserver) */ @@ -176397,7 +160407,7 @@ ${options.prefix}` : "\n" : options.prefix /** * projects specified by a tsconfig.json file */ - this.configuredProjects = /* @__PURE__ */ new Map(); + this.configuredProjects = /* @__PURE__ */new Map(); /** @internal */ this.newInferredProjectName = createProjectNameFactoryWithCounter(makeInferredProjectName); /** @internal */ @@ -176407,20 +160417,20 @@ ${options.prefix}` : "\n" : options.prefix /** * Open files: with value being project root path, and key being Path of the file that is open */ - this.openFiles = /* @__PURE__ */ new Map(); + this.openFiles = /* @__PURE__ */new Map(); /** @internal */ - this.configFileForOpenFiles = /* @__PURE__ */ new Map(); + this.configFileForOpenFiles = /* @__PURE__ */new Map(); /** * Map of open files that are opened without complete path but have projectRoot as current directory */ - this.openFilesWithNonRootedDiskPath = /* @__PURE__ */ new Map(); - this.compilerOptionsForInferredProjectsPerProjectRoot = /* @__PURE__ */ new Map(); - this.watchOptionsForInferredProjectsPerProjectRoot = /* @__PURE__ */ new Map(); - this.typeAcquisitionForInferredProjectsPerProjectRoot = /* @__PURE__ */ new Map(); + this.openFilesWithNonRootedDiskPath = /* @__PURE__ */new Map(); + this.compilerOptionsForInferredProjectsPerProjectRoot = /* @__PURE__ */new Map(); + this.watchOptionsForInferredProjectsPerProjectRoot = /* @__PURE__ */new Map(); + this.typeAcquisitionForInferredProjectsPerProjectRoot = /* @__PURE__ */new Map(); /** * Project size for configured or external projects */ - this.projectToSizeMap = /* @__PURE__ */ new Map(); + this.projectToSizeMap = /* @__PURE__ */new Map(); /** * This is a map of config file paths existence that doesnt need query to disk * - The entry can be present because there is inferred project that needs to watch addition of config file to directory @@ -176430,18 +160440,18 @@ ${options.prefix}` : "\n" : options.prefix * * @internal */ - this.configFileExistenceInfoCache = /* @__PURE__ */ new Map(); + this.configFileExistenceInfoCache = /* @__PURE__ */new Map(); this.safelist = defaultTypeSafeList; - this.legacySafelist = /* @__PURE__ */ new Map(); - this.pendingProjectUpdates = /* @__PURE__ */ new Map(); + this.legacySafelist = /* @__PURE__ */new Map(); + this.pendingProjectUpdates = /* @__PURE__ */new Map(); /** @internal */ this.pendingEnsureProjectForOpenFiles = false; /** Tracks projects that we have already sent telemetry for. */ - this.seenProjects = /* @__PURE__ */ new Map(); + this.seenProjects = /* @__PURE__ */new Map(); /** @internal */ - this.sharedExtendedConfigFileWatchers = /* @__PURE__ */ new Map(); + this.sharedExtendedConfigFileWatchers = /* @__PURE__ */new Map(); /** @internal */ - this.extendedConfigCache = /* @__PURE__ */ new Map(); + this.extendedConfigCache = /* @__PURE__ */new Map(); /** @internal */ this.verifyDocumentRegistry = noop; /** @internal */ @@ -176469,6 +160479,7 @@ ${options.prefix}` : "\n" : options.prefix } else { this.serverMode = 0 /* Semantic */; } + if (this.host.realpath) { this.realpathToScriptInfos = createMultiMap(); } @@ -176491,17 +160502,12 @@ ${options.prefix}` : "\n" : options.prefix }; this.documentRegistry = createDocumentRegistryInternal(this.host.useCaseSensitiveFileNames, this.currentDirectory, this.jsDocParsingMode, this); const watchLogLevel = this.logger.hasLevel(3 /* verbose */) ? 2 /* Verbose */ : this.logger.loggingEnabled() ? 1 /* TriggerOnly */ : 0 /* None */; - const log = watchLogLevel !== 0 /* None */ ? (s) => this.logger.info(s) : noop; + const log = watchLogLevel !== 0 /* None */ ? s => this.logger.info(s) : noop; this.packageJsonCache = createPackageJsonCache(this); this.watchFactory = this.serverMode !== 0 /* Semantic */ ? { watchFile: returnNoopFileWatcher, watchDirectory: returnNoopFileWatcher - } : getWatchFactory( - createWatchFactoryHostUsingWatchEvents(this, opts.canUseWatchEvents) || this.host, - watchLogLevel, - log, - getDetailWatchInfo - ); + } : getWatchFactory(createWatchFactoryHostUsingWatchEvents(this, opts.canUseWatchEvents) || this.host, watchLogLevel, log, getDetailWatchInfo); (_a = opts.incrementalVerifier) == null ? void 0 : _a.call(opts, this); } toPath(fileName) { @@ -176518,7 +160524,10 @@ ${options.prefix}` : "\n" : options.prefix /** @internal */ setDocument(key, path, sourceFile) { const info = Debug.checkDefined(this.getScriptInfoForPath(path)); - info.cacheSourceFile = { key, sourceFile }; + info.cacheSourceFile = { + key, + sourceFile + }; } /** @internal */ getDocument(key, path) { @@ -176540,7 +160549,10 @@ ${options.prefix}` : "\n" : options.prefix } const event = { eventName: ProjectLanguageServiceStateEvent, - data: { project, languageServiceEnabled } + data: { + project, + languageServiceEnabled + } }; this.eventHandler(event); } @@ -176578,12 +160590,8 @@ ${options.prefix}` : "\n" : options.prefix project.updateTypingFiles(this.typingsCache.updateTypingsForProject(response.projectName, response.compilerOptions, response.typeAcquisition, response.unresolvedImports, response.typings)); return; case ActionInvalidate: - this.typingsCache.enqueueInstallTypingsForProject( - project, - project.lastCachedUnresolvedImportsList, - /*forceRefresh*/ - true - ); + this.typingsCache.enqueueInstallTypingsForProject(project, project.lastCachedUnresolvedImportsList, /*forceRefresh*/ + true); return; } } @@ -176594,41 +160602,31 @@ ${options.prefix}` : "\n" : options.prefix } /** @internal */ delayEnsureProjectForOpenFiles() { - if (!this.openFiles.size) - return; + if (!this.openFiles.size) return; this.pendingEnsureProjectForOpenFiles = true; - this.throttledOperations.schedule( - ensureProjectForOpenFileSchedule, - /*delay*/ - 2500, - () => { - if (this.pendingProjectUpdates.size !== 0) { - this.delayEnsureProjectForOpenFiles(); - } else { - if (this.pendingEnsureProjectForOpenFiles) { - this.ensureProjectForOpenFiles(); - this.sendProjectsUpdatedInBackgroundEvent(); - } + this.throttledOperations.schedule(ensureProjectForOpenFileSchedule, /*delay*/ + 2500, () => { + if (this.pendingProjectUpdates.size !== 0) { + this.delayEnsureProjectForOpenFiles(); + } else { + if (this.pendingEnsureProjectForOpenFiles) { + this.ensureProjectForOpenFiles(); + this.sendProjectsUpdatedInBackgroundEvent(); } } - ); + }); } delayUpdateProjectGraph(project) { project.markAsDirty(); - if (isBackgroundProject(project)) - return; + if (isBackgroundProject(project)) return; const projectName = project.getProjectName(); this.pendingProjectUpdates.set(projectName, project); - this.throttledOperations.schedule( - projectName, - /*delay*/ - 250, - () => { - if (this.pendingProjectUpdates.delete(projectName)) { - updateProjectIfDirty(project); - } + this.throttledOperations.schedule(projectName, /*delay*/ + 250, () => { + if (this.pendingProjectUpdates.delete(projectName)) { + updateProjectIfDirty(project); } - ); + }); } /** @internal */ hasPendingProjectUpdate(project) { @@ -176642,7 +160640,7 @@ ${options.prefix}` : "\n" : options.prefix const event = { eventName: ProjectsUpdatedInBackgroundEvent, data: { - openFiles: arrayFrom(this.openFiles.keys(), (path) => this.getScriptInfoForPath(path).fileName) + openFiles: arrayFrom(this.openFiles.keys(), path => this.getScriptInfoForPath(path).fileName) } }; this.eventHandler(event); @@ -176654,7 +160652,11 @@ ${options.prefix}` : "\n" : options.prefix } const event = { eventName: LargeFileReferencedEvent, - data: { file, fileSize, maxFileSize } + data: { + file, + fileSize, + maxFileSize + } }; this.eventHandler(event); } @@ -176666,7 +160668,10 @@ ${options.prefix}` : "\n" : options.prefix project.sendLoadingProjectFinish = true; const event = { eventName: ProjectLoadingStartEvent, - data: { project, reason } + data: { + project, + reason + } }; this.eventHandler(event); } @@ -176678,14 +160683,19 @@ ${options.prefix}` : "\n" : options.prefix project.sendLoadingProjectFinish = false; const event = { eventName: ProjectLoadingFinishEvent, - data: { project } + data: { + project + } }; this.eventHandler(event); } /** @internal */ sendPerformanceEvent(kind, durationMs) { if (this.performanceEventHandler) { - this.performanceEventHandler({ kind, durationMs }); + this.performanceEventHandler({ + kind, + durationMs + }); } } /** @internal */ @@ -176696,8 +160706,7 @@ ${options.prefix}` : "\n" : options.prefix delayUpdateProjectGraphs(projects, clearSourceMapperCache) { if (projects.length) { for (const project of projects) { - if (clearSourceMapperCache) - project.clearSourceMapperCache(); + if (clearSourceMapperCache) project.clearSourceMapperCache(); this.delayUpdateProjectGraph(project); } this.delayEnsureProjectForOpenFiles(); @@ -176749,7 +160758,7 @@ ${options.prefix}` : "\n" : options.prefix } /** @internal */ forEachEnabledProject(cb) { - this.forEachProject((project) => { + this.forEachProject(project => { if (!project.isOrphan() && project.languageServiceEnabled) { cb(project); } @@ -176786,7 +160795,7 @@ ${options.prefix}` : "\n" : options.prefix ensureProjectStructuresUptoDate() { let hasChanges = this.pendingEnsureProjectForOpenFiles; this.pendingProjectUpdates.clear(); - const updateGraph = (project) => { + const updateGraph = project => { hasChanges = updateProjectIfDirty(project) || hasChanges; }; this.externalProjects.forEach(updateGraph); @@ -176802,7 +160811,10 @@ ${options.prefix}` : "\n" : options.prefix } getPreferences(file) { const info = this.getScriptInfoForNormalizedPath(file); - return { ...this.hostConfiguration.preferences, ...info && info.getPreferences() }; + return { + ...this.hostConfiguration.preferences, + ...(info && info.getPreferences()) + }; } getHostFormatCodeOptions() { return this.hostConfiguration.formatCodeOptions; @@ -176815,11 +160827,8 @@ ${options.prefix}` : "\n" : options.prefix this.handleDeletedFile(info); } else if (!info.isScriptOpen()) { info.delayReloadNonMixedContentFile(); - this.delayUpdateProjectGraphs( - info.containingProjects, - /*clearSourceMapperCache*/ - false - ); + this.delayUpdateProjectGraphs(info.containingProjects, /*clearSourceMapperCache*/ + false); this.handleSourceMapProjects(info); } } @@ -176845,11 +160854,8 @@ ${options.prefix}` : "\n" : options.prefix delayUpdateProjectsOfScriptInfoPath(path) { const info = this.getScriptInfoForPath(path); if (info) { - this.delayUpdateProjectGraphs( - info.containingProjects, - /*clearSourceMapperCache*/ - true - ); + this.delayUpdateProjectGraphs(info.containingProjects, /*clearSourceMapperCache*/ + true); } } handleDeletedFile(info) { @@ -176858,11 +160864,8 @@ ${options.prefix}` : "\n" : options.prefix this.deleteScriptInfo(info); const containingProjects = info.containingProjects.slice(); info.detachAllProjects(); - this.delayUpdateProjectGraphs( - containingProjects, - /*clearSourceMapperCache*/ - false - ); + this.delayUpdateProjectGraphs(containingProjects, /*clearSourceMapperCache*/ + false); this.handleSourceMapProjects(info); info.closeSourceMapFileWatcher(); if (info.declarationInfoPath) { @@ -176879,78 +160882,63 @@ ${options.prefix}` : "\n" : options.prefix * @internal */ watchWildcardDirectory(directory, flags, configFileName, config) { - return this.watchFactory.watchDirectory( - directory, - (fileOrDirectory) => { - const fileOrDirectoryPath = this.toPath(fileOrDirectory); - const fsResult = config.cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath); - if (getBaseFileName(fileOrDirectoryPath) === "package.json" && !isInsideNodeModules(fileOrDirectoryPath) && (fsResult && fsResult.fileExists || !fsResult && this.host.fileExists(fileOrDirectoryPath))) { - this.logger.info(`Config: ${configFileName} Detected new package.json: ${fileOrDirectory}`); - this.onAddPackageJson(fileOrDirectoryPath); - } - const configuredProjectForConfig = this.findConfiguredProjectByProjectName(configFileName); - if (isIgnoredFileFromWildCardWatching({ - watchedDirPath: directory, - fileOrDirectory, - fileOrDirectoryPath, - configFileName, - extraFileExtensions: this.hostConfiguration.extraFileExtensions, - currentDirectory: this.currentDirectory, - options: config.parsedCommandLine.options, - program: (configuredProjectForConfig == null ? void 0 : configuredProjectForConfig.getCurrentProgram()) || config.parsedCommandLine.fileNames, - useCaseSensitiveFileNames: this.host.useCaseSensitiveFileNames, - 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 */; - config.projects.forEach((watchWildcardDirectories, projectCanonicalPath) => { - if (!watchWildcardDirectories) - return; - const project = this.getConfiguredProjectByCanonicalConfigFilePath(projectCanonicalPath); - if (!project) - return; - const updateLevel = configuredProjectForConfig === project ? 1 /* RootNamesAndUpdate */ : 0 /* Update */; - if (project.pendingUpdateLevel !== void 0 && project.pendingUpdateLevel > updateLevel) - return; - if (this.openFiles.has(fileOrDirectoryPath)) { - const info = Debug.checkDefined(this.getScriptInfoForPath(fileOrDirectoryPath)); - if (info.isAttached(project)) { - const loadLevelToSet = Math.max(updateLevel, project.openFileWatchTriggered.get(fileOrDirectoryPath) || 0 /* Update */); - project.openFileWatchTriggered.set(fileOrDirectoryPath, loadLevelToSet); - } else { - project.pendingUpdateLevel = updateLevel; - this.delayUpdateProjectGraphAndEnsureProjectStructureForOpenFiles(project); - } + return this.watchFactory.watchDirectory(directory, fileOrDirectory => { + const fileOrDirectoryPath = this.toPath(fileOrDirectory); + const fsResult = config.cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath); + if (getBaseFileName(fileOrDirectoryPath) === "package.json" && !isInsideNodeModules(fileOrDirectoryPath) && (fsResult && fsResult.fileExists || !fsResult && this.host.fileExists(fileOrDirectoryPath))) { + this.logger.info(`Config: ${configFileName} Detected new package.json: ${fileOrDirectory}`); + this.onAddPackageJson(fileOrDirectoryPath); + } + const configuredProjectForConfig = this.findConfiguredProjectByProjectName(configFileName); + if (isIgnoredFileFromWildCardWatching({ + watchedDirPath: directory, + fileOrDirectory, + fileOrDirectoryPath, + configFileName, + extraFileExtensions: this.hostConfiguration.extraFileExtensions, + currentDirectory: this.currentDirectory, + options: config.parsedCommandLine.options, + program: (configuredProjectForConfig == null ? void 0 : configuredProjectForConfig.getCurrentProgram()) || config.parsedCommandLine.fileNames, + useCaseSensitiveFileNames: this.host.useCaseSensitiveFileNames, + 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 */; + config.projects.forEach((watchWildcardDirectories, projectCanonicalPath) => { + if (!watchWildcardDirectories) return; + const project = this.getConfiguredProjectByCanonicalConfigFilePath(projectCanonicalPath); + if (!project) return; + const updateLevel = configuredProjectForConfig === project ? 1 /* RootNamesAndUpdate */ : 0 /* Update */; + if (project.pendingUpdateLevel !== void 0 && project.pendingUpdateLevel > updateLevel) return; + if (this.openFiles.has(fileOrDirectoryPath)) { + const info = Debug.checkDefined(this.getScriptInfoForPath(fileOrDirectoryPath)); + if (info.isAttached(project)) { + const loadLevelToSet = Math.max(updateLevel, project.openFileWatchTriggered.get(fileOrDirectoryPath) || 0 /* Update */); + project.openFileWatchTriggered.set(fileOrDirectoryPath, loadLevelToSet); } else { project.pendingUpdateLevel = updateLevel; this.delayUpdateProjectGraphAndEnsureProjectStructureForOpenFiles(project); } - }); - }, - flags, - this.getWatchOptionsFromProjectWatchOptions(config.parsedCommandLine.watchOptions), - WatchType.WildcardDirectory, - configFileName - ); + } else { + project.pendingUpdateLevel = updateLevel; + this.delayUpdateProjectGraphAndEnsureProjectStructureForOpenFiles(project); + } + }); + }, flags, this.getWatchOptionsFromProjectWatchOptions(config.parsedCommandLine.watchOptions), WatchType.WildcardDirectory, configFileName); } /** @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) => { 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); @@ -176968,60 +160956,34 @@ ${options.prefix}` : "\n" : options.prefix if (eventKind === 2 /* Deleted */) { configFileExistenceInfo.exists = false; const project = ((_a = configFileExistenceInfo.config) == null ? void 0 : _a.projects.has(canonicalConfigFilePath)) ? this.getConfiguredProjectByCanonicalConfigFilePath(canonicalConfigFilePath) : void 0; - if (project) - this.removeProject(project); + if (project) this.removeProject(project); } else { configFileExistenceInfo.exists = true; } this.delayUpdateProjectsFromParsedConfigOnConfigFileChange(canonicalConfigFilePath, "Change in config file detected"); - this.reloadConfiguredProjectForFiles( - configFileExistenceInfo.openFilesImpactedByConfigFile, - /*clearSemanticCache*/ - false, - /*delayReload*/ - true, - eventKind !== 2 /* Deleted */ ? identity : ( - // Reload open files if they are root of inferred project - returnTrue - ), - // Reload all the open files impacted by config file - "Change in config file detected" - ); + this.reloadConfiguredProjectForFiles(configFileExistenceInfo.openFilesImpactedByConfigFile, /*clearSemanticCache*/ + false, /*delayReload*/ + true, eventKind !== 2 /* Deleted */ ? identity : + // Reload open files if they are root of inferred project + returnTrue, + // Reload all the open files impacted by config file + "Change in config file detected"); this.delayEnsureProjectForOpenFiles(); } removeProject(project) { this.logger.info("`remove Project::"); - project.print( - /*writeProjectFileNames*/ - true, - /*writeFileExplaination*/ - true, - /*writeFileVersionAndText*/ - false - ); + project.print( /*writeProjectFileNames*/ + true, /*writeFileExplaination*/ + true, /*writeFileVersionAndText*/ + false); project.close(); if (Debug.shouldAssert(1 /* Normal */)) { - this.filenameToScriptInfo.forEach( - (info) => Debug.assert( - !info.isAttached(project), - "Found script Info still attached to project", - () => `${project.projectName}: ScriptInfos still attached: ${JSON.stringify( - arrayFrom( - mapDefinedIterator( - this.filenameToScriptInfo.values(), - (info2) => info2.isAttached(project) ? { - fileName: info2.fileName, - projects: info2.containingProjects.map((p) => p.projectName), - hasMixedContent: info2.hasMixedContent - } : void 0 - ) - ), - /*replacer*/ - void 0, - " " - )}` - ) - ); + this.filenameToScriptInfo.forEach(info => Debug.assert(!info.isAttached(project), "Found script Info still attached to project", () => `${project.projectName}: ScriptInfos still attached: ${JSON.stringify(arrayFrom(mapDefinedIterator(this.filenameToScriptInfo.values(), info2 => info2.isAttached(project) ? { + fileName: info2.fileName, + projects: info2.containingProjects.map(p => p.projectName), + hasMixedContent: info2.hasMixedContent + } : void 0)), /*replacer*/ + void 0, " ")}`)); } this.pendingProjectUpdates.delete(project.getProjectName()); switch (project.projectKind) { @@ -177041,14 +161003,7 @@ ${options.prefix}` : "\n" : options.prefix /** @internal */ assignOrphanScriptInfoToInferredProject(info, projectRootPath) { Debug.assert(info.isOrphan()); - const project = this.getOrCreateInferredProjectForProjectRootPathIfEnabled(info, projectRootPath) || this.getOrCreateSingleInferredProjectIfEnabled() || this.getOrCreateSingleInferredWithoutProjectRoot( - info.isDynamic ? projectRootPath || this.currentDirectory : getDirectoryPath( - isRootedDiskPath(info.fileName) ? info.fileName : getNormalizedAbsolutePath( - info.fileName, - projectRootPath ? this.getNormalizedAbsolutePath(projectRootPath) : this.currentDirectory - ) - ) - ); + const project = this.getOrCreateInferredProjectForProjectRootPathIfEnabled(info, projectRootPath) || this.getOrCreateSingleInferredProjectIfEnabled() || this.getOrCreateSingleInferredWithoutProjectRoot(info.isDynamic ? projectRootPath || this.currentDirectory : getDirectoryPath(isRootedDiskPath(info.fileName) ? info.fileName : getNormalizedAbsolutePath(info.fileName, projectRootPath ? this.getNormalizedAbsolutePath(projectRootPath) : this.currentDirectory))); project.addRoot(info); if (info.containingProjects[0] !== project) { info.detachFromProject(project); @@ -177062,14 +161017,10 @@ ${options.prefix}` : "\n" : options.prefix } const roots = inferredProject.getRootScriptInfos(); Debug.assert(roots.length === 1 || !!inferredProject.projectRootPath); - if (roots.length === 1 && forEach(roots[0].containingProjects, (p) => p !== roots[0].containingProjects[0] && !p.isOrphan())) { - inferredProject.removeFile( - roots[0], - /*fileExists*/ - true, - /*detachFromProject*/ - true - ); + if (roots.length === 1 && forEach(roots[0].containingProjects, p => p !== roots[0].containingProjects[0] && !p.isOrphan())) { + inferredProject.removeFile(roots[0], /*fileExists*/ + true, /*detachFromProject*/ + true); } } } @@ -177113,12 +161064,8 @@ ${options.prefix}` : "\n" : options.prefix if (p.isProjectWithSingleRoot()) { ensureProjectsForOpenFiles = true; } - p.removeFile( - info, - fileExists, - /*detachFromProject*/ - true - ); + p.removeFile(info, fileExists, /*detachFromProject*/ + true); } if (!p.languageServiceEnabled) { p.markAsDirty(); @@ -177149,16 +161096,19 @@ ${options.prefix}` : "\n" : options.prefix 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); + (configFileExistenceInfo.openFilesImpactedByConfigFile || (configFileExistenceInfo.openFilesImpactedByConfigFile = /* @__PURE__ */new Map())).set(info.path, false); } return configFileExistenceInfo.exists; } const exists = this.host.fileExists(configFileName); let openFilesImpactedByConfigFile; if (isOpenScriptInfo(info)) { - (openFilesImpactedByConfigFile || (openFilesImpactedByConfigFile = /* @__PURE__ */ new Map())).set(info.path, false); + (openFilesImpactedByConfigFile || (openFilesImpactedByConfigFile = /* @__PURE__ */new Map())).set(info.path, false); } - configFileExistenceInfo = { exists, openFilesImpactedByConfigFile }; + configFileExistenceInfo = { + exists, + openFilesImpactedByConfigFile + }; this.configFileExistenceInfoCache.set(canonicalConfigFilePath, configFileExistenceInfo); return exists; } @@ -177167,14 +161117,7 @@ ${options.prefix}` : "\n" : options.prefix var _a, _b; const configFileExistenceInfo = this.configFileExistenceInfoCache.get(canonicalConfigFilePath); if (!configFileExistenceInfo.watcher || configFileExistenceInfo.watcher === noopConfigFileWatcher) { - configFileExistenceInfo.watcher = this.watchFactory.watchFile( - configFileName, - (_fileName, eventKind) => this.onConfigFileChanged(canonicalConfigFilePath, eventKind), - 2e3 /* High */, - this.getWatchOptionsFromProjectWatchOptions((_b = (_a = configFileExistenceInfo == null ? void 0 : configFileExistenceInfo.config) == null ? void 0 : _a.parsedCommandLine) == null ? void 0 : _b.watchOptions), - WatchType.ConfigFile, - forProject - ); + configFileExistenceInfo.watcher = this.watchFactory.watchFile(configFileName, (_fileName, eventKind) => this.onConfigFileChanged(canonicalConfigFilePath, eventKind), 2e3 /* High */, this.getWatchOptionsFromProjectWatchOptions((_b = (_a = configFileExistenceInfo == null ? void 0 : configFileExistenceInfo.config) == null ? void 0 : _a.parsedCommandLine) == null ? void 0 : _b.watchOptions), WatchType.ConfigFile, forProject); } const projects = configFileExistenceInfo.config.projects; projects.set(forProject.canonicalConfigFilePath, projects.get(forProject.canonicalConfigFilePath) || false); @@ -177189,10 +161132,8 @@ ${options.prefix}` : "\n" : options.prefix 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); @@ -177228,7 +161169,7 @@ ${options.prefix}` : "\n" : options.prefix */ stopWatchingConfigFilesForClosedScriptInfo(info) { Debug.assert(!info.isScriptOpen()); - this.forEachConfigFileLocation(info, (canonicalConfigFilePath) => { + this.forEachConfigFileLocation(info, canonicalConfigFilePath => { var _a, _b, _c; const configFileExistenceInfo = this.configFileExistenceInfoCache.get(canonicalConfigFilePath); if (configFileExistenceInfo) { @@ -177254,17 +161195,13 @@ ${options.prefix}` : "\n" : options.prefix 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) + }; this.configFileExistenceInfoCache.set(canonicalConfigFilePath, configFileExistenceInfo); } - (configFileExistenceInfo.openFilesImpactedByConfigFile || (configFileExistenceInfo.openFilesImpactedByConfigFile = /* @__PURE__ */ new Map())).set(info.path, true); - configFileExistenceInfo.watcher || (configFileExistenceInfo.watcher = canWatchDirectoryOrFile(getPathComponents(getDirectoryPath(canonicalConfigFilePath))) ? this.watchFactory.watchFile( - configFileName, - (_filename, eventKind) => this.onConfigFileChanged(canonicalConfigFilePath, eventKind), - 2e3 /* High */, - this.hostConfiguration.watchOptions, - WatchType.ConfigFileForInferredRoot - ) : noopConfigFileWatcher); + (configFileExistenceInfo.openFilesImpactedByConfigFile || (configFileExistenceInfo.openFilesImpactedByConfigFile = /* @__PURE__ */new Map())).set(info.path, true); + configFileExistenceInfo.watcher || (configFileExistenceInfo.watcher = canWatchDirectoryOrFile(getPathComponents(getDirectoryPath(canonicalConfigFilePath))) ? this.watchFactory.watchFile(configFileName, (_filename, eventKind) => this.onConfigFileChanged(canonicalConfigFilePath, eventKind), 2e3 /* High */, this.hostConfiguration.watchOptions, WatchType.ConfigFileForInferredRoot) : noopConfigFileWatcher); }); } /** @@ -177273,7 +161210,7 @@ ${options.prefix}` : "\n" : options.prefix * @internal */ stopWatchingConfigFilesForInferredProjectRoot(info) { - this.forEachConfigFileLocation(info, (canonicalConfigFilePath) => { + 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)) { @@ -177298,8 +161235,7 @@ ${options.prefix}` : "\n" : options.prefix 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(); @@ -177309,19 +161245,16 @@ ${options.prefix}` : "\n" : options.prefix 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()); @@ -177329,8 +161262,7 @@ ${options.prefix}` : "\n" : options.prefix } /** @internal */ findDefaultConfiguredProject(info) { - if (!info.isScriptOpen()) - return void 0; + 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); @@ -177349,8 +161281,7 @@ ${options.prefix}` : "\n" : options.prefix if (isOpenScriptInfo(info)) { Debug.assert(info.isScriptOpen()); const result = this.configFileForOpenFiles.get(info.path); - if (result !== void 0) - return result || void 0; + if (result !== void 0) return result || void 0; } this.logger.info(`Search path: ${getDirectoryPath(info.fileName)}`); const configFileName = this.forEachConfigFileLocation(info, (canonicalConfigFilePath, configFileName2) => this.configFileExists(configFileName2, canonicalConfigFilePath, info)); @@ -177376,7 +161307,7 @@ ${options.prefix}` : "\n" : options.prefix this.openFiles.forEach((projectRootPath, path) => { const info = this.getScriptInfoForPath(path); this.logger.info(` FileName: ${info.fileName} ProjectRootPath: ${projectRootPath}`); - this.logger.info(` Projects: ${info.containingProjects.map((p) => p.getProjectName())}`); + this.logger.info(` Projects: ${info.containingProjects.map(p => p.getProjectName())}`); }); this.logger.endGroup(); } @@ -177398,7 +161329,7 @@ ${options.prefix}` : "\n" : options.prefix } let availableSpace = maxProgramSizeForNonTsFiles; this.projectToSizeMap.set(name, 0); - this.projectToSizeMap.forEach((val) => availableSpace -= val || 0); + this.projectToSizeMap.forEach(val => availableSpace -= val || 0); let totalNonTsFileSize = 0; for (const f of fileNames) { const fileName = propertyReader.getFileName(f); @@ -177407,8 +161338,11 @@ ${options.prefix}` : "\n" : options.prefix } totalNonTsFileSize += this.host.getFileSize(fileName); if (totalNonTsFileSize > maxProgramSizeForNonTsFiles || totalNonTsFileSize > availableSpace) { - const top5LargestFiles = fileNames.map((f2) => propertyReader.getFileName(f2)).filter((name2) => !hasTSFileExtension(name2)).map((name2) => ({ name: name2, size: this.host.getFileSize(name2) })).sort((a, b) => b.size - a.size).slice(0, 5); - this.logger.info(`Non TS file size exceeded limit (${totalNonTsFileSize}). Largest files: ${top5LargestFiles.map((file) => `${file.name}:${file.size}`).join(", ")}`); + const top5LargestFiles = fileNames.map(f2 => propertyReader.getFileName(f2)).filter(name2 => !hasTSFileExtension(name2)).map(name2 => ({ + name: name2, + size: this.host.getFileSize(name2) + })).sort((a, b) => b.size - a.size).slice(0, 5); + this.logger.info(`Non TS file size exceeded limit (${totalNonTsFileSize}). Largest files: ${top5LargestFiles.map(file => `${file.name}:${file.size}`).join(", ")}`); return fileName; } } @@ -177417,18 +161351,9 @@ ${options.prefix}` : "\n" : options.prefix createExternalProject(projectFileName, files, options, typeAcquisition, excludedFiles) { const compilerOptions = convertCompilerOptions(options); const watchOptionsAndErrors = convertWatchOptions(options, getDirectoryPath(normalizeSlashes(projectFileName))); - const project = new ExternalProject2( - projectFileName, - this, - this.documentRegistry, - compilerOptions, - /*lastFileExceededProgramSize*/ - this.getFilenameForExceededTotalSizeLimitForNonTsFiles(projectFileName, compilerOptions, files, externalFilePropertyReader), - options.compileOnSave === void 0 ? true : options.compileOnSave, - /*projectFilePath*/ - void 0, - watchOptionsAndErrors == null ? void 0 : watchOptionsAndErrors.watchOptions - ); + const project = new ExternalProject2(projectFileName, this, this.documentRegistry, compilerOptions, /*lastFileExceededProgramSize*/ + this.getFilenameForExceededTotalSizeLimitForNonTsFiles(projectFileName, compilerOptions, files, externalFilePropertyReader), options.compileOnSave === void 0 ? true : options.compileOnSave, /*projectFilePath*/ + void 0, watchOptionsAndErrors == null ? void 0 : watchOptionsAndErrors.watchOptions); project.setProjectErrors(watchOptionsAndErrors == null ? void 0 : watchOptionsAndErrors.errors); project.excludedFiles = excludedFiles; this.addFilesToNonInferredProject(project, files, externalFilePropertyReader, typeAcquisition); @@ -177450,11 +161375,8 @@ ${options.prefix}` : "\n" : options.prefix setProjectOptionsUsed(project); const data = { projectId: this.host.createSHA256Hash(project.projectName), - fileStats: countEachFileTypes( - project.getScriptInfos(), - /*includeSizes*/ - true - ), + fileStats: countEachFileTypes(project.getScriptInfos(), /*includeSizes*/ + true), compilerOptions: convertCompilerOptionsForTelemetry(project.getCompilationSettings()), typeAcquisition: convertTypeAcquisition2(project.getTypeAcquisition()), extends: projectOptions && projectOptions.configHasExtendsProperty, @@ -177467,14 +161389,21 @@ ${options.prefix}` : "\n" : options.prefix languageServiceEnabled: project.languageServiceEnabled, version }; - this.eventHandler({ eventName: ProjectInfoTelemetryEvent, data }); + this.eventHandler({ + eventName: ProjectInfoTelemetryEvent, + data + }); function configFileName() { if (!isConfiguredProject(project)) { return "other"; } return getBaseConfigFileName(project.getConfigFilePath()) || "other"; } - function convertTypeAcquisition2({ enable: enable2, include, exclude }) { + function convertTypeAcquisition2({ + enable: enable2, + include, + exclude + }) { return { enable: enable2, include: include !== void 0 && include.length !== 0, @@ -177490,29 +161419,28 @@ ${options.prefix}` : "\n" : options.prefix /** @internal */ createConfiguredProject(configFileName) { var _a; - (_a = tracing) == null ? void 0 : _a.instant(tracing.Phase.Session, "createConfiguredProject", { configFilePath: configFileName }); + (_a = tracing) == null ? void 0 : _a.instant(tracing.Phase.Session, "createConfiguredProject", { + configFilePath: configFileName + }); this.logger.info(`Creating configuration project ${configFileName}`); const canonicalConfigFilePath = asNormalizedPath(this.toCanonicalFileName(configFileName)); let configFileExistenceInfo = this.configFileExistenceInfoCache.get(canonicalConfigFilePath); if (!configFileExistenceInfo) { - this.configFileExistenceInfoCache.set(canonicalConfigFilePath, configFileExistenceInfo = { exists: true }); + this.configFileExistenceInfoCache.set(canonicalConfigFilePath, configFileExistenceInfo = { + exists: true + }); } else { configFileExistenceInfo.exists = true; } if (!configFileExistenceInfo.config) { configFileExistenceInfo.config = { cachedDirectoryStructureHost: createCachedDirectoryStructureHost(this.host, this.host.getCurrentDirectory(), this.host.useCaseSensitiveFileNames), - projects: /* @__PURE__ */ new Map(), + projects: /* @__PURE__ */new Map(), updateLevel: 2 /* Full */ }; } - const project = new ConfiguredProject2( - configFileName, - canonicalConfigFilePath, - this, - this.documentRegistry, - configFileExistenceInfo.config.cachedDirectoryStructureHost - ); + + const project = new ConfiguredProject2(configFileName, canonicalConfigFilePath, this, this.documentRegistry, configFileExistenceInfo.config.cachedDirectoryStructureHost); this.configuredProjects.set(canonicalConfigFilePath, project); this.createConfigFileWatcherForParsedConfig(configFileName, canonicalConfigFilePath, project); return project; @@ -177543,15 +161471,12 @@ ${options.prefix}` : "\n" : options.prefix */ loadConfiguredProject(project, reason) { var _a, _b; - (_a = tracing) == null ? void 0 : _a.push(tracing.Phase.Session, "loadConfiguredProject", { configFilePath: project.canonicalConfigFilePath }); + (_a = tracing) == null ? void 0 : _a.push(tracing.Phase.Session, "loadConfiguredProject", { + configFilePath: project.canonicalConfigFilePath + }); this.sendProjectLoadingStartEvent(project, reason); const configFilename = asNormalizedPath(normalizePath(project.getConfigFilePath())); - const configFileExistenceInfo = this.ensureParsedConfigUptoDate( - configFilename, - project.canonicalConfigFilePath, - this.configFileExistenceInfoCache.get(project.canonicalConfigFilePath), - project - ); + const configFileExistenceInfo = this.ensureParsedConfigUptoDate(configFilename, project.canonicalConfigFilePath, this.configFileExistenceInfoCache.get(project.canonicalConfigFilePath), project); const parsedCommandLine = configFileExistenceInfo.config.parsedCommandLine; Debug.assert(!!parsedCommandLine.fileNames); const compilerOptions = parsedCommandLine.options; @@ -177585,108 +161510,78 @@ ${options.prefix}` : "\n" : options.prefix 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; } } const cachedDirectoryStructureHost = ((_a = configFileExistenceInfo.config) == null ? void 0 : _a.cachedDirectoryStructureHost) || createCachedDirectoryStructureHost(this.host, this.host.getCurrentDirectory(), this.host.useCaseSensitiveFileNames); - const configFileContent = tryReadFile(configFilename, (fileName) => this.host.readFile(fileName)); + 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); - const parsedCommandLine = parseJsonSourceFileConfigFileContent( - configFile, - cachedDirectoryStructureHost, - getDirectoryPath(configFilename), - /*existingOptions*/ - {}, - configFilename, - /*resolutionStack*/ - [], - this.hostConfiguration.extraFileExtensions, - this.extendedConfigCache - ); + if (!isString(configFileContent)) configFileErrors.push(configFileContent); + const parsedCommandLine = parseJsonSourceFileConfigFileContent(configFile, cachedDirectoryStructureHost, getDirectoryPath(configFilename), /*existingOptions*/ + {}, configFilename, /*resolutionStack*/ + [], this.hostConfiguration.extraFileExtensions, this.extendedConfigCache); if (parsedCommandLine.errors.length) { configFileErrors.push(...parsedCommandLine.errors); } - this.logger.info(`Config: ${configFilename} : ${JSON.stringify( - { - rootNames: parsedCommandLine.fileNames, - options: parsedCommandLine.options, - watchOptions: parsedCommandLine.watchOptions, - projectReferences: parsedCommandLine.projectReferences - }, - /*replacer*/ - void 0, - " " - )}`); + this.logger.info(`Config: ${configFilename} : ${JSON.stringify({ + rootNames: parsedCommandLine.fileNames, + options: parsedCommandLine.options, + watchOptions: parsedCommandLine.watchOptions, + projectReferences: parsedCommandLine.projectReferences + }, /*replacer*/ + void 0, " ")}`); const oldCommandLine = (_b = configFileExistenceInfo.config) == null ? void 0 : _b.parsedCommandLine; if (!configFileExistenceInfo.config) { - configFileExistenceInfo.config = { parsedCommandLine, cachedDirectoryStructureHost, projects: /* @__PURE__ */ new Map() }; + configFileExistenceInfo.config = { + parsedCommandLine, + cachedDirectoryStructureHost, + projects: /* @__PURE__ */new Map() + }; } else { configFileExistenceInfo.config.parsedCommandLine = parsedCommandLine; configFileExistenceInfo.config.watchedDirectoriesStale = true; configFileExistenceInfo.config.updateLevel = void 0; } if (!oldCommandLine && !isJsonEqual( - // Old options - this.getWatchOptionsFromProjectWatchOptions( - /*projectOptions*/ - void 0 - ), - // New options - this.getWatchOptionsFromProjectWatchOptions(parsedCommandLine.watchOptions) - )) { + // Old options + this.getWatchOptionsFromProjectWatchOptions( /*projectOptions*/ + void 0), + // New options + this.getWatchOptionsFromProjectWatchOptions(parsedCommandLine.watchOptions))) { (_c = configFileExistenceInfo.watcher) == null ? void 0 : _c.close(); configFileExistenceInfo.watcher = void 0; } this.createConfigFileWatcherForParsedConfig(configFilename, canonicalConfigFilePath, forProject); - updateSharedExtendedConfigFileWatcher( - canonicalConfigFilePath, - parsedCommandLine.options, - this.sharedExtendedConfigFileWatchers, - (extendedConfigFileName, extendedConfigFilePath) => this.watchFactory.watchFile( - extendedConfigFileName, - () => { - var _a2; - cleanExtendedConfigCache(this.extendedConfigCache, extendedConfigFilePath, (fileName) => this.toPath(fileName)); - let ensureProjectsForOpenFiles = false; - (_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(); - }, - 2e3 /* High */, - this.hostConfiguration.watchOptions, - WatchType.ExtendedConfigFile, - configFilename - ), - (fileName) => this.toPath(fileName) - ); + updateSharedExtendedConfigFileWatcher(canonicalConfigFilePath, parsedCommandLine.options, this.sharedExtendedConfigFileWatchers, (extendedConfigFileName, extendedConfigFilePath) => this.watchFactory.watchFile(extendedConfigFileName, () => { + var _a2; + cleanExtendedConfigCache(this.extendedConfigCache, extendedConfigFilePath, fileName => this.toPath(fileName)); + let ensureProjectsForOpenFiles = false; + (_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(); + }, 2e3 /* High */, this.hostConfiguration.watchOptions, WatchType.ExtendedConfigFile, configFilename), fileName => this.toPath(fileName)); return configFileExistenceInfo; } /** @internal */ - watchWildcards(configFileName, { exists, config }, forProject) { + 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()), - new Map(Object.entries(config.parsedCommandLine.wildcardDirectories)), - // Create new directory watcher - (directory, flags) => this.watchWildcardDirectory(directory, flags, configFileName, config) - ); + updateWatchingWildcardDirectories(config.watchedDirectories || (config.watchedDirectories = /* @__PURE__ */new Map()), new Map(Object.entries(config.parsedCommandLine.wildcardDirectories)), + // Create new directory watcher + (directory, flags) => this.watchWildcardDirectory(directory, flags, configFileName, config)); } else { config.watchedDirectoriesStale = false; - if (!config.watchedDirectories) - return; + if (!config.watchedDirectories) return; clearMap(config.watchedDirectories, closeFileWatcherOf); config.watchedDirectories = void 0; } @@ -177698,8 +161593,7 @@ ${options.prefix}` : "\n" : options.prefix 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; @@ -177708,7 +161602,7 @@ ${options.prefix}` : "\n" : options.prefix } updateNonInferredProjectFiles(project, files, propertyReader) { const projectRootFilesMap = project.getRootFilesMap(); - const newRootScriptInfoMap = /* @__PURE__ */ new Map(); + const newRootScriptInfoMap = /* @__PURE__ */new Map(); for (const f of files) { const newRootFile = propertyReader.getFileName(f); const fileName = toNormalizedPath(newRootFile); @@ -177719,29 +161613,21 @@ ${options.prefix}` : "\n" : options.prefix const existingValue = projectRootFilesMap.get(path); if (existingValue) { if (existingValue.info) { - project.removeFile( - existingValue.info, - /*fileExists*/ - false, - /*detachFromProject*/ - true - ); + project.removeFile(existingValue.info, /*fileExists*/ + false, /*detachFromProject*/ + true); existingValue.info = void 0; } existingValue.fileName = fileName; } else { - projectRootFilesMap.set(path, { fileName }); + projectRootFilesMap.set(path, { + fileName + }); } } else { const scriptKind = propertyReader.getScriptKind(f, this.hostConfiguration.extraFileExtensions); const hasMixedContent = propertyReader.hasMixedContent(f, this.hostConfiguration.extraFileExtensions); - const scriptInfo = Debug.checkDefined(this.getOrCreateScriptInfoNotOpenedByClientForNormalizedPath( - fileName, - project.currentDirectory, - scriptKind, - hasMixedContent, - project.directoryStructureHost - )); + const scriptInfo = Debug.checkDefined(this.getOrCreateScriptInfoNotOpenedByClientForNormalizedPath(fileName, project.currentDirectory, scriptKind, hasMixedContent, project.directoryStructureHost)); path = scriptInfo.path; const existingValue = projectRootFilesMap.get(path); if (!existingValue || existingValue.info !== scriptInfo) { @@ -177759,12 +161645,8 @@ ${options.prefix}` : "\n" : options.prefix projectRootFilesMap.forEach((value, path) => { if (!newRootScriptInfoMap.has(path)) { if (value.info) { - project.removeFile( - value.info, - project.fileExists(path), - /*detachFromProject*/ - true - ); + project.removeFile(value.info, project.fileExists(path), /*detachFromProject*/ + true); } else { projectRootFilesMap.delete(path); } @@ -177794,18 +161676,14 @@ ${options.prefix}` : "\n" : options.prefix } /** @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( - configFileSpecs, - getDirectoryPath(configFileName), - config.parsedCommandLine.options, - config.cachedDirectoryStructureHost, - this.hostConfiguration.extraFileExtensions - ); - config.parsedCommandLine = { ...config.parsedCommandLine, fileNames }; + const fileNames = getFileNamesFromConfigSpecs(configFileSpecs, getDirectoryPath(configFileName), config.parsedCommandLine.options, config.cachedDirectoryStructureHost, this.hostConfiguration.extraFileExtensions); + config.parsedCommandLine = { + ...config.parsedCommandLine, + fileNames + }; return fileNames; } /** @internal */ @@ -177819,8 +161697,7 @@ ${options.prefix}` : "\n" : options.prefix */ reloadConfiguredProject(project, reason, isInitialLoad, clearSemanticCache) { const host = project.getCachedDirectoryStructureHost(); - if (clearSemanticCache) - this.clearSemanticCache(project); + if (clearSemanticCache) this.clearSemanticCache(project); host.clearCache(); const configFileName = project.getConfigFilePath(); this.logger.info(`${isInitialLoad ? "Loading" : "Reloading"} configured project ${configFileName}`); @@ -177831,10 +161708,8 @@ ${options.prefix}` : "\n" : options.prefix /** @internal */ clearSemanticCache(project) { project.resolutionCache.clear(); - project.getLanguageService( - /*ensureSynchronized*/ - false - ).cleanupSemanticCache(); + project.getLanguageService( /*ensureSynchronized*/ + false).cleanupSemanticCache(); project.cleanupProgram(); project.markAsDirty(); } @@ -177844,15 +161719,18 @@ ${options.prefix}` : "\n" : options.prefix } const diagnostics = project.getLanguageService().getCompilerOptionsDiagnostics(); diagnostics.push(...project.getAllProjectErrors()); - this.eventHandler( - { - eventName: ConfigFileDiagEvent, - data: { configFileName: project.getConfigFilePath(), diagnostics, triggerFile } + this.eventHandler({ + eventName: ConfigFileDiagEvent, + data: { + configFileName: project.getConfigFilePath(), + diagnostics, + triggerFile } - ); + }); } getOrCreateInferredProjectForProjectRootPathIfEnabled(info, projectRootPath) { - if (!this.useInferredProjectPerProjectRoot || // Its a dynamic info opened without project root + if (!this.useInferredProjectPerProjectRoot || + // Its a dynamic info opened without project root info.isDynamic && projectRootPath === void 0) { return void 0; } @@ -177863,21 +161741,14 @@ ${options.prefix}` : "\n" : options.prefix return project; } } - return this.createInferredProject( - projectRootPath, - /*isSingleInferredProject*/ - false, - projectRootPath - ); + return this.createInferredProject(projectRootPath, /*isSingleInferredProject*/ + false, projectRootPath); } 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; @@ -177889,11 +161760,8 @@ ${options.prefix}` : "\n" : options.prefix if (this.inferredProjects.length > 0 && this.inferredProjects[0].projectRootPath === void 0) { return this.inferredProjects[0]; } - return this.createInferredProject( - "", - /*isSingleInferredProject*/ - true - ); + return this.createInferredProject("", /*isSingleInferredProject*/ + true); } getOrCreateSingleInferredWithoutProjectRoot(currentDirectory) { Debug.assert(!this.useSingleInferredProject); @@ -177931,15 +161799,9 @@ ${options.prefix}` : "\n" : options.prefix } /** @internal */ getOrCreateScriptInfoNotOpenedByClient(uncheckedFileName, currentDirectory, hostToQueryFileExistsOn) { - return this.getOrCreateScriptInfoNotOpenedByClientForNormalizedPath( - toNormalizedPath(uncheckedFileName), - currentDirectory, - /*scriptKind*/ - void 0, - /*hasMixedContent*/ - void 0, - hostToQueryFileExistsOn - ); + return this.getOrCreateScriptInfoNotOpenedByClientForNormalizedPath(toNormalizedPath(uncheckedFileName), currentDirectory, /*scriptKind*/ + void 0, /*hasMixedContent*/ + void 0, hostToQueryFileExistsOn); } getScriptInfo(uncheckedFileName) { return this.getScriptInfoForNormalizedPath(toNormalizedPath(uncheckedFileName)); @@ -177948,14 +161810,16 @@ ${options.prefix}` : "\n" : options.prefix 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; } /** @internal */ logErrorForScriptInfoNotFound(fileName) { - const names = arrayFrom(this.filenameToScriptInfo.entries(), ([path, scriptInfo]) => ({ path, fileName: scriptInfo.fileName })); + const names = arrayFrom(this.filenameToScriptInfo.entries(), ([path, scriptInfo]) => ({ + path, + fileName: scriptInfo.fileName + })); this.logger.msg(`Could not find file ${JSON.stringify(fileName)}. All files are: ${JSON.stringify(names)}`, "Err" /* Err */); } @@ -177995,13 +161859,7 @@ All files are: ${JSON.stringify(names)}`, "Err" /* Err */); if (!info.isDynamicOrHasMixedContent() && (!this.globalCacheLocationDirectoryPath || !startsWith(info.path, this.globalCacheLocationDirectoryPath))) { const indexOfNodeModules = info.path.indexOf("/node_modules/"); if (!this.host.getModifiedTime || indexOfNodeModules === -1) { - info.fileWatcher = this.watchFactory.watchFile( - info.fileName, - (_fileName, eventKind) => this.onSourceFileChanged(info, eventKind), - 500 /* Medium */, - this.hostConfiguration.watchOptions, - WatchType.ClosedScriptInfo - ); + info.fileWatcher = this.watchFactory.watchFile(info.fileName, (_fileName, eventKind) => this.onSourceFileChanged(info, eventKind), 500 /* Medium */, this.hostConfiguration.watchOptions, WatchType.ClosedScriptInfo); } else { info.mTime = this.getModifiedTime(info); info.fileWatcher = this.watchClosedScriptInfoInNodeModules(info.path.substr(0, indexOfNodeModules)); @@ -178009,39 +161867,32 @@ All files are: ${JSON.stringify(names)}`, "Err" /* Err */); } } createNodeModulesWatcher(dir) { - const watcher = this.watchFactory.watchDirectory( - dir, - (fileOrDirectory) => { - var _a; - const fileOrDirectoryPath = removeIgnoredPath(this.toPath(fileOrDirectory)); - 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((projectName) => { - var _a2, _b; - (_b = (_a2 = this.findProject(projectName)) == null ? void 0 : _a2.getModuleSpecifierCache()) == null ? void 0 : _b.clear(); - }); - } - if (result.refreshScriptInfoRefCount) { - if (dir === fileOrDirectoryPath) { - this.refreshScriptInfosInDirectory(dir); - } else { - const info = this.getScriptInfoForPath(fileOrDirectoryPath); - if (info) { - if (isScriptInfoWatchedFromNodeModules(info)) { - this.refreshScriptInfo(info); - } - } else if (!hasExtension(fileOrDirectoryPath)) { - this.refreshScriptInfosInDirectory(fileOrDirectoryPath); + const watcher = this.watchFactory.watchDirectory(dir, fileOrDirectory => { + var _a; + const fileOrDirectoryPath = removeIgnoredPath(this.toPath(fileOrDirectory)); + 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(projectName => { + var _a2, _b; + (_b = (_a2 = this.findProject(projectName)) == null ? void 0 : _a2.getModuleSpecifierCache()) == null ? void 0 : _b.clear(); + }); + } + if (result.refreshScriptInfoRefCount) { + if (dir === fileOrDirectoryPath) { + this.refreshScriptInfosInDirectory(dir); + } else { + const info = this.getScriptInfoForPath(fileOrDirectoryPath); + if (info) { + if (isScriptInfoWatchedFromNodeModules(info)) { + this.refreshScriptInfo(info); } + } else if (!hasExtension(fileOrDirectoryPath)) { + this.refreshScriptInfosInDirectory(fileOrDirectoryPath); } } - }, - 1 /* Recursive */, - this.hostConfiguration.watchOptions, - WatchType.NodeModules - ); + } + }, 1 /* Recursive */, this.hostConfiguration.watchOptions, WatchType.NodeModules); const result = { refreshScriptInfoRefCount: 0, affectedModuleSpecifierCacheProjects: void 0, @@ -178059,7 +161910,7 @@ All files are: ${JSON.stringify(names)}`, "Err" /* Err */); /** @internal */ watchPackageJsonsInNodeModules(dir, project) { const watcher = this.nodeModulesWatchers.get(dir) || this.createNodeModulesWatcher(dir); - (watcher.affectedModuleSpecifierCacheProjects || (watcher.affectedModuleSpecifierCacheProjects = /* @__PURE__ */ new Set())).add(project.getProjectName()); + (watcher.affectedModuleSpecifierCacheProjects || (watcher.affectedModuleSpecifierCacheProjects = /* @__PURE__ */new Set())).add(project.getProjectName()); return { close: () => { var _a; @@ -178092,7 +161943,7 @@ All files are: ${JSON.stringify(names)}`, "Err" /* Err */); } refreshScriptInfosInDirectory(dir) { dir = dir + directorySeparator; - this.filenameToScriptInfo.forEach((info) => { + this.filenameToScriptInfo.forEach(info => { if (isScriptInfoWatchedFromNodeModules(info) && startsWith(info.path, dir)) { this.refreshScriptInfo(info); } @@ -178106,17 +161957,9 @@ All files are: ${JSON.stringify(names)}`, "Err" /* Err */); } getOrCreateScriptInfoNotOpenedByClientForNormalizedPath(fileName, currentDirectory, scriptKind, hasMixedContent, hostToQueryFileExistsOn) { if (isRootedDiskPath(fileName) || isDynamicFileName(fileName)) { - return this.getOrCreateScriptInfoWorker( - fileName, - currentDirectory, - /*openedByClient*/ - false, - /*fileContent*/ - void 0, - scriptKind, - hasMixedContent, - hostToQueryFileExistsOn - ); + return this.getOrCreateScriptInfoWorker(fileName, currentDirectory, /*openedByClient*/ + false, /*fileContent*/ + void 0, scriptKind, hasMixedContent, hostToQueryFileExistsOn); } const info = this.openFilesWithNonRootedDiskPath.get(this.toCanonicalFileName(fileName)); if (info) { @@ -178125,15 +161968,8 @@ All files are: ${JSON.stringify(names)}`, "Err" /* Err */); return void 0; } getOrCreateScriptInfoOpenedByClientForNormalizedPath(fileName, currentDirectory, fileContent, scriptKind, hasMixedContent) { - return this.getOrCreateScriptInfoWorker( - fileName, - currentDirectory, - /*openedByClient*/ - true, - fileContent, - scriptKind, - hasMixedContent - ); + return this.getOrCreateScriptInfoWorker(fileName, currentDirectory, /*openedByClient*/ + true, fileContent, scriptKind, hasMixedContent); } getOrCreateScriptInfoForNormalizedPath(fileName, openedByClient, fileContent, scriptKind, hasMixedContent, hostToQueryFileExistsOn) { return this.getOrCreateScriptInfoWorker(fileName, this.currentDirectory, openedByClient, fileContent, scriptKind, hasMixedContent, hostToQueryFileExistsOn); @@ -178144,11 +161980,26 @@ All files are: ${JSON.stringify(names)}`, "Err" /* Err */); let info = this.getScriptInfoForPath(path); if (!info) { const isDynamic = isDynamicFileName(fileName); - Debug.assert(isRootedDiskPath(fileName) || isDynamic || openedByClient, "", () => `${JSON.stringify({ fileName, currentDirectory, hostCurrentDirectory: this.currentDirectory, openKeys: arrayFrom(this.openFilesWithNonRootedDiskPath.keys()) })} + Debug.assert(isRootedDiskPath(fileName) || isDynamic || openedByClient, "", () => `${JSON.stringify({ + fileName, + currentDirectory, + hostCurrentDirectory: this.currentDirectory, + openKeys: arrayFrom(this.openFilesWithNonRootedDiskPath.keys()) + })} Script info with non-dynamic relative file name can only be open script info or in context of host currentDirectory`); - Debug.assert(!isRootedDiskPath(fileName) || this.currentDirectory === currentDirectory || !this.openFilesWithNonRootedDiskPath.has(this.toCanonicalFileName(fileName)), "", () => `${JSON.stringify({ fileName, currentDirectory, hostCurrentDirectory: this.currentDirectory, openKeys: arrayFrom(this.openFilesWithNonRootedDiskPath.keys()) })} + Debug.assert(!isRootedDiskPath(fileName) || this.currentDirectory === currentDirectory || !this.openFilesWithNonRootedDiskPath.has(this.toCanonicalFileName(fileName)), "", () => `${JSON.stringify({ + fileName, + currentDirectory, + hostCurrentDirectory: this.currentDirectory, + openKeys: arrayFrom(this.openFilesWithNonRootedDiskPath.keys()) + })} Open script files with non rooted disk path opened with current directory context cannot have same canonical names`); - Debug.assert(!isDynamic || this.currentDirectory === currentDirectory || this.useInferredProjectPerProjectRoot, "", () => `${JSON.stringify({ fileName, currentDirectory, hostCurrentDirectory: this.currentDirectory, openKeys: arrayFrom(this.openFilesWithNonRootedDiskPath.keys()) })} + Debug.assert(!isDynamic || this.currentDirectory === currentDirectory || this.useInferredProjectPerProjectRoot, "", () => `${JSON.stringify({ + fileName, + currentDirectory, + hostCurrentDirectory: this.currentDirectory, + openKeys: arrayFrom(this.openFilesWithNonRootedDiskPath.keys()) + })} Dynamic files must always be opened with service's current directory or service should support inferred project per projectRootPath.`); if (!openedByClient && !isDynamic && !(hostToQueryFileExistsOn || this.host).fileExists(fileName)) { return; @@ -178216,17 +162067,15 @@ Dynamic files must always be opened with service's current directory or service } sourceMapFileInfo = mapInfo; 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; - const documentPositionMapper = getDocumentPositionMapper( - { getCanonicalFileName: this.toCanonicalFileName, log: (s) => this.logger.info(s), getSourceFileLike: (f) => this.getSourceFileLike(f, projectName, declarationInfo) }, - declarationInfo.fileName, - declarationInfo.textStorage.getLineInfo(), - readMapFile - ); + const documentPositionMapper = getDocumentPositionMapper({ + getCanonicalFileName: this.toCanonicalFileName, + log: s => this.logger.info(s), + getSourceFileLike: f => this.getSourceFileLike(f, projectName, declarationInfo) + }, declarationInfo.fileName, declarationInfo.textStorage.getLineInfo(), readMapFile); readMapFile = void 0; if (sourceMapFileInfo) { declarationInfo.sourceMapFilePath = sourceMapFileInfo.path; @@ -178235,10 +162084,7 @@ Dynamic files must always be opened with service's current directory or service sourceMapFileInfo.sourceInfos = this.addSourceInfoToSourceMap(sourceFileName, project, sourceMapFileInfo.sourceInfos); } else if (mapFileNameFromDeclarationInfo) { declarationInfo.sourceMapFilePath = { - watcher: this.addMissingSourceMapFile( - project.currentDirectory === this.currentDirectory ? mapFileNameFromDeclarationInfo : getNormalizedAbsolutePath(mapFileNameFromDeclarationInfo, project.currentDirectory), - declarationInfo.path - ), + watcher: this.addMissingSourceMapFile(project.currentDirectory === this.currentDirectory ? mapFileNameFromDeclarationInfo : getNormalizedAbsolutePath(mapFileNameFromDeclarationInfo, project.currentDirectory), declarationInfo.path), sourceInfos: this.addSourceInfoToSourceMap(sourceFileName, project) }; } else { @@ -178249,29 +162095,20 @@ Dynamic files must always be opened with service's current directory or service addSourceInfoToSourceMap(sourceFileName, project, sourceInfos) { if (sourceFileName) { const sourceInfo = this.getOrCreateScriptInfoNotOpenedByClient(sourceFileName, project.currentDirectory, project.directoryStructureHost); - (sourceInfos || (sourceInfos = /* @__PURE__ */ new Set())).add(sourceInfo.path); + (sourceInfos || (sourceInfos = /* @__PURE__ */new Set())).add(sourceInfo.path); } return sourceInfos; } addMissingSourceMapFile(mapFileName, declarationInfoPath) { - const fileWatcher = this.watchFactory.watchFile( - mapFileName, - () => { - const declarationInfo = this.getScriptInfoForPath(declarationInfoPath); - if (declarationInfo && declarationInfo.sourceMapFilePath && !isString(declarationInfo.sourceMapFilePath)) { - this.delayUpdateProjectGraphs( - declarationInfo.containingProjects, - /*clearSourceMapperCache*/ - true - ); - this.delayUpdateSourceInfoProjects(declarationInfo.sourceMapFilePath.sourceInfos); - declarationInfo.closeSourceMapFileWatcher(); - } - }, - 2e3 /* High */, - this.hostConfiguration.watchOptions, - WatchType.MissingSourceMapFile - ); + const fileWatcher = this.watchFactory.watchFile(mapFileName, () => { + const declarationInfo = this.getScriptInfoForPath(declarationInfoPath); + if (declarationInfo && declarationInfo.sourceMapFilePath && !isString(declarationInfo.sourceMapFilePath)) { + this.delayUpdateProjectGraphs(declarationInfo.containingProjects, /*clearSourceMapperCache*/ + true); + this.delayUpdateSourceInfoProjects(declarationInfo.sourceMapFilePath.sourceInfos); + declarationInfo.closeSourceMapFileWatcher(); + } + }, 2e3 /* High */, this.hostConfiguration.watchOptions, WatchType.MissingSourceMapFile); return fileWatcher; } /** @internal */ @@ -178280,29 +162117,29 @@ 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, (project || this).currentDirectory, project ? project.directoryStructureHost : this.host); - 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); + (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() { Debug.fail("shouldnt need text"); return ""; }, - getLineAndCharacterOfPosition: (pos) => { + getLineAndCharacterOfPosition: pos => { const lineOffset = info.positionToLineOffset(pos); - return { line: lineOffset.line - 1, character: lineOffset.offset - 1 }; + return { + line: lineOffset.line - 1, + character: lineOffset.offset - 1 + }; }, getPositionOfLineAndCharacter: (line, character, allowEdits) => info.lineOffsetToPosition(line + 1, character + 1, allowEdits) }; @@ -178327,7 +162164,10 @@ Dynamic files must always be opened with service's current directory or service this.logger.info(`Host information ${args.hostInfo}`); } if (args.formatOptions) { - this.hostConfiguration.formatCodeOptions = { ...this.hostConfiguration.formatCodeOptions, ...convertFormatOptions(args.formatOptions) }; + this.hostConfiguration.formatCodeOptions = { + ...this.hostConfiguration.formatCodeOptions, + ...convertFormatOptions(args.formatOptions) + }; this.logger.info("Format host information updated"); } if (args.preferences) { @@ -178335,19 +162175,20 @@ Dynamic files must always be opened with service's current directory or service lazyConfiguredProjectsFromExternalProject, includePackageJsonAutoImports } = this.hostConfiguration.preferences; - this.hostConfiguration.preferences = { ...this.hostConfiguration.preferences, ...args.preferences }; + this.hostConfiguration.preferences = { + ...this.hostConfiguration.preferences, + ...args.preferences + }; if (lazyConfiguredProjectsFromExternalProject && !this.hostConfiguration.preferences.lazyConfiguredProjectsFromExternalProject) { - this.configuredProjects.forEach((project) => { + this.configuredProjects.forEach(project => { if (project.hasExternalProjectRef() && project.pendingUpdateLevel === 2 /* Full */ && !this.pendingProjectUpdates.has(project.getProjectName())) { project.updateGraph(); } }); } if (includePackageJsonAutoImports !== args.preferences.includePackageJsonAutoImports) { - this.invalidateProjectPackageJson( - /*packageJsonPath*/ - void 0 - ); + this.invalidateProjectPackageJson( /*packageJsonPath*/ + void 0); } } if (args.extraFileExtensions) { @@ -178367,7 +162208,10 @@ Dynamic files must always be opened with service's current directory or service } /** @internal */ getWatchOptionsFromProjectWatchOptions(projectOptions) { - return projectOptions && this.hostConfiguration.watchOptions ? { ...this.hostConfiguration.watchOptions, ...projectOptions } : projectOptions || this.hostConfiguration.watchOptions; + return projectOptions && this.hostConfiguration.watchOptions ? { + ...this.hostConfiguration.watchOptions, + ...projectOptions + } : projectOptions || this.hostConfiguration.watchOptions; } closeLog() { this.logger.close(); @@ -178378,37 +162222,30 @@ 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; + this.filenameToScriptInfo.forEach(info => { + if (this.openFiles.has(info.path)) return; + if (!info.fileWatcher) return; this.onSourceFileChanged(info, this.host.fileExists(info.fileName) ? 1 /* Changed */ : 2 /* Deleted */); }); + this.pendingProjectUpdates.forEach((_project, projectName) => { this.throttledOperations.cancel(projectName); this.pendingProjectUpdates.delete(projectName); }); this.throttledOperations.cancel(ensureProjectForOpenFileSchedule); this.pendingEnsureProjectForOpenFiles = false; - this.configFileExistenceInfoCache.forEach((info) => { - if (info.config) - info.config.updateLevel = 2 /* Full */; + this.configFileExistenceInfoCache.forEach(info => { + if (info.config) info.config.updateLevel = 2 /* Full */; }); - this.reloadConfiguredProjectForFiles( - this.openFiles, - /*clearSemanticCache*/ - true, - /*delayReload*/ - false, - returnTrue, - "User requested reload projects" - ); - this.externalProjects.forEach((project) => { + + this.reloadConfiguredProjectForFiles(this.openFiles, /*clearSemanticCache*/ + true, /*delayReload*/ + false, returnTrue, "User requested reload projects"); + this.externalProjects.forEach(project => { this.clearSemanticCache(project); project.updateGraph(); }); - this.inferredProjects.forEach((project) => this.clearSemanticCache(project)); + this.inferredProjects.forEach(project => this.clearSemanticCache(project)); this.ensureProjectForOpenFiles(); } /** @@ -178419,17 +162256,12 @@ Dynamic files must always be opened with service's current directory or service * reloadForInfo provides a way to filter out files to reload configured project for */ reloadConfiguredProjectForFiles(openFiles, clearSemanticCache, delayReload, shouldReloadProjectFor, reason) { - const updatedProjects = /* @__PURE__ */ new Map(); - const reloadChildProject = (child) => { + const updatedProjects = /* @__PURE__ */new Map(); + const reloadChildProject = child => { if (!updatedProjects.has(child.canonicalConfigFilePath)) { updatedProjects.set(child.canonicalConfigFilePath, true); - this.reloadConfiguredProject( - child, - reason, - /*isInitialLoad*/ - false, - clearSemanticCache - ); + this.reloadConfiguredProject(child, reason, /*isInitialLoad*/ + false, clearSemanticCache); } }; openFiles == null ? void 0 : openFiles.forEach((openFileValue, path) => { @@ -178447,35 +162279,20 @@ Dynamic files must always be opened with service's current directory or service if (delayReload) { project.pendingUpdateLevel = 2 /* Full */; project.pendingUpdateReason = reason; - if (clearSemanticCache) - this.clearSemanticCache(project); + if (clearSemanticCache) this.clearSemanticCache(project); this.delayUpdateProjectGraph(project); } else { - this.reloadConfiguredProject( - project, - reason, - /*isInitialLoad*/ - false, - clearSemanticCache - ); + this.reloadConfiguredProject(project, reason, /*isInitialLoad*/ + false, clearSemanticCache); if (!projectContainsInfoDirectly(project, info)) { - const referencedProject = forEachResolvedProjectReferenceProject( - project, - info.path, - (child) => { - reloadChildProject(child); - return projectContainsInfoDirectly(child, info); - }, - 1 /* FindCreate */ - ); + 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 */ - ); + forEachResolvedProjectReferenceProject(project, /*fileName*/ + void 0, reloadChildProject, 0 /* Find */); } } } @@ -178489,14 +162306,10 @@ Dynamic files must always be opened with service's current directory or service removeRootOfInferredProjectIfNowPartOfOtherProject(info) { Debug.assert(info.containingProjects.length > 0); const firstProject = info.containingProjects[0]; - if (!firstProject.isOrphan() && isInferredProject(firstProject) && firstProject.isRoot(info) && forEach(info.containingProjects, (p) => p !== firstProject && !p.isOrphan())) { - firstProject.removeFile( - info, - /*fileExists*/ - true, - /*detachFromProject*/ - true - ); + if (!firstProject.isOrphan() && isInferredProject(firstProject) && firstProject.isRoot(info) && forEach(info.containingProjects, p => p !== firstProject && !p.isOrphan())) { + firstProject.removeFile(info, /*fileExists*/ + true, /*detachFromProject*/ + true); } } /** @@ -178528,29 +162341,25 @@ Dynamic files must always be opened with service's current directory or service * @param fileContent is a known version of the file content that is more up to date than the one on disk */ openClientFile(fileName, fileContent, scriptKind, projectRootPath) { - return this.openClientFileWithNormalizedPath( - toNormalizedPath(fileName), - fileContent, - scriptKind, - /*hasMixedContent*/ - false, - projectRootPath ? toNormalizedPath(projectRootPath) : void 0 - ); + return this.openClientFileWithNormalizedPath(toNormalizedPath(fileName), fileContent, scriptKind, /*hasMixedContent*/ + false, projectRootPath ? toNormalizedPath(projectRootPath) : void 0); } /** @internal */ getOriginalLocationEnsuringConfiguredProject(project, location) { const isSourceOfProjectReferenceRedirect = project.isSourceOfProjectReferenceRedirect(location.fileName); const originalLocation = isSourceOfProjectReferenceRedirect ? location : project.getSourceMapper().tryGetSourcePosition(location); - if (!originalLocation) - return void 0; - const { fileName } = originalLocation; + if (!originalLocation) return void 0; + const { + fileName + } = originalLocation; const scriptInfo = this.getScriptInfo(fileName); - if (!scriptInfo && !this.host.fileExists(fileName)) - return void 0; - const originalFileInfo = { fileName: toNormalizedPath(fileName), path: this.toPath(fileName) }; + 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; + if (!configFileName) return void 0; let configuredProject = this.findConfiguredProjectByProjectName(configFileName); if (!configuredProject) { if (project.getCompilerOptions().disableReferencedProjectLoad) { @@ -178562,31 +162371,22 @@ Dynamic files must always be opened with service's current directory or service configuredProject = this.createAndLoadConfiguredProject(configFileName, `Creating project for original file: ${originalFileInfo.fileName}${location !== originalLocation ? " for location: " + location.fileName : ""}`); } updateProjectIfDirty(configuredProject); - const projectContainsOriginalInfo = (project2) => { + const projectContainsOriginalInfo = project2 => { const info = this.getScriptInfo(fileName); return info && projectContainsInfoDirectly(project2, info); }; if (configuredProject.isSolution() || !projectContainsOriginalInfo(configuredProject)) { - configuredProject = forEachResolvedProjectReferenceProject( - configuredProject, - fileName, - (child) => { - updateProjectIfDirty(child); - return projectContainsOriginalInfo(child) ? child : void 0; - }, - 2 /* FindCreateLoad */, - `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; + configuredProject = forEachResolvedProjectReferenceProject(configuredProject, fileName, child => { + updateProjectIfDirty(child); + return projectContainsOriginalInfo(child) ? child : void 0; + }, 2 /* FindCreateLoad */, `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; } addOriginalConfiguredProject(configuredProject); const originalScriptInfo = this.getScriptInfo(fileName); - if (!originalScriptInfo || !originalScriptInfo.containingProjects.length) - return void 0; - originalScriptInfo.containingProjects.forEach((project2) => { + if (!originalScriptInfo || !originalScriptInfo.containingProjects.length) return void 0; + originalScriptInfo.containingProjects.forEach(project2 => { if (isConfiguredProject(project2)) { addOriginalConfiguredProject(project2); } @@ -178594,7 +162394,7 @@ Dynamic files must always be opened with service's current directory or service return originalLocation; function addOriginalConfiguredProject(originalProject) { if (!project.originalConfiguredProjects) { - project.originalConfiguredProjects = /* @__PURE__ */ new Set(); + project.originalConfiguredProjects = /* @__PURE__ */new Set(); } project.originalConfiguredProjects.add(originalProject.canonicalConfigFilePath); } @@ -178604,7 +162404,7 @@ Dynamic files must always be opened with service's current directory or service return !!this.getScriptInfoForNormalizedPath(fileName) || this.host.fileExists(fileName); } findExternalProjectContainingOpenScriptInfo(info) { - return find(this.externalProjects, (proj) => { + return find(this.externalProjects, proj => { updateProjectIfDirty(proj); return proj.containsScriptInfo(info); }); @@ -178634,27 +162434,21 @@ Dynamic files must always be opened with service's current directory or service projectForConfigFileDiag = project.containsScriptInfo(info) ? project : void 0; retainProjects = project; if (!projectContainsInfoDirectly(project, info)) { - forEachResolvedProjectReferenceProject( - project, - info.path, - (child) => { - updateProjectIfDirty(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` - ); + forEachResolvedProjectReferenceProject(project, info.path, child => { + updateProjectIfDirty(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(); @@ -178671,7 +162465,7 @@ Dynamic files must always be opened with service's current directory or service info.containingProjects.forEach(updateProjectIfDirty); if (info.isOrphan()) { if (isArray(retainProjects)) { - retainProjects.forEach((project2) => this.sendConfigFileDiagEvent(project2, info.fileName)); + retainProjects.forEach(project2 => this.sendConfigFileDiagEvent(project2, info.fileName)); } else if (retainProjects) { this.sendConfigFileDiagEvent(retainProjects, info.fileName); } @@ -178679,21 +162473,22 @@ Dynamic files must always be opened with service's current directory or service this.assignOrphanScriptInfoToInferredProject(info, this.openFiles.get(info.path)); } Debug.assert(!info.isOrphan()); - return { configFileName, configFileErrors, retainProjects }; + return { + configFileName, + configFileErrors, + retainProjects + }; } createAncestorProjects(info, project) { - if (!info.isAttached(project)) - return; + if (!info.isAttached(project)) return; while (true) { - if (!project.isInitialLoadPending() && (!project.getCompilerOptions().composite || project.getCompilerOptions().disableSolutionSearching)) - return; + 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; + 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); @@ -178703,13 +162498,10 @@ Dynamic files must always be opened with service's current directory or service } /** @internal */ loadAncestorProjectTree(forProjects) { - forProjects = forProjects || mapDefinedEntries( - this.configuredProjects, - (key, project) => !project.isInitialLoadPending() ? [key, true] : void 0 - ); - const seenProjects = /* @__PURE__ */ new Set(); + forProjects = forProjects || mapDefinedEntries(this.configuredProjects, (key, project) => !project.isInitialLoadPending() ? [key, true] : void 0); + const seenProjects = /* @__PURE__ */new Set(); for (const project of arrayFrom(this.configuredProjects.values())) { - if (forEachPotentialProjectReference(project, (potentialRefPath) => forProjects.has(potentialRefPath))) { + if (forEachPotentialProjectReference(project, potentialRefPath => forProjects.has(potentialRefPath))) { updateProjectIfDirty(project); } this.ensureProjectChildren(project, forProjects, seenProjects); @@ -178717,19 +162509,14 @@ 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; - const referencedProject = forEachResolvedProjectReference(child.references, (ref) => forProjects.has(ref.sourceFile.path) ? ref : void 0); - if (!referencedProject) - continue; + if (!child) continue; + const referencedProject = forEachResolvedProjectReference(child.references, ref => forProjects.has(ref.sourceFile.path) ? ref : void 0); + 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}`); updateProjectIfDirty(childProject); @@ -178747,7 +162534,10 @@ 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); + const { + retainProjects, + ...result + } = this.assignProjectToOpenedScriptInfo(info); this.cleanupAfterOpeningFile(retainProjects); this.telemetryOnOpenFile(info); this.printProjects(); @@ -178755,14 +162545,12 @@ Dynamic files must always be opened with service's current directory or service } removeOrphanConfiguredProjects(toRetainConfiguredProjects) { const toRemoveConfiguredProjects = new Map(this.configuredProjects); - const markOriginalProjectsAsUsed = (project) => { + const markOriginalProjectsAsUsed = project => { if (!project.isOrphan() && project.originalConfiguredProjects) { - project.originalConfiguredProjects.forEach( - (_value, configuredProjectPath) => { - const project2 = this.getConfiguredProjectByCanonicalConfigFilePath(configuredProjectPath); - return project2 && retainConfiguredProject(project2); - } - ); + project.originalConfiguredProjects.forEach((_value, configuredProjectPath) => { + const project2 = this.getConfiguredProjectByCanonicalConfigFilePath(configuredProjectPath); + return project2 && retainConfiguredProject(project2); + }); } }; if (toRetainConfiguredProjects) { @@ -178774,17 +162562,14 @@ Dynamic files must always be opened with service's current directory or service } this.inferredProjects.forEach(markOriginalProjectsAsUsed); this.externalProjects.forEach(markOriginalProjectsAsUsed); - this.configuredProjects.forEach((project) => { + this.configuredProjects.forEach(project => { if (project.hasOpenRef()) { retainConfiguredProject(project); } else if (toRemoveConfiguredProjects.has(project.canonicalConfigFilePath)) { - forEachReferencedProject( - project, - (ref) => isRetained(ref) && retainConfiguredProject(project) - ); + forEachReferencedProject(project, ref => isRetained(ref) && retainConfiguredProject(project)); } }); - toRemoveConfiguredProjects.forEach((project) => this.removeProject(project)); + toRemoveConfiguredProjects.forEach(project => this.removeProject(project)); function isRetained(project) { return project.hasOpenRef() || !toRemoveConfiguredProjects.has(project.canonicalConfigFilePath); } @@ -178797,10 +162582,9 @@ Dynamic files must always be opened with service's current directory or service } removeOrphanScriptInfos() { const toRemoveScriptInfos = new Map(this.filenameToScriptInfo); - this.filenameToScriptInfo.forEach((info) => { + this.filenameToScriptInfo.forEach(info => { if (!info.isScriptOpen() && info.isOrphan() && !info.isContainedByBackgroundProject()) { - if (!info.sourceMapFilePath) - return; + if (!info.sourceMapFilePath) return; let sourceInfos; if (isString(info.sourceMapFilePath)) { const sourceMapInfo = this.getScriptInfoForPath(info.sourceMapFilePath); @@ -178808,9 +162592,8 @@ Dynamic files must always be opened with service's current directory or service } else { sourceInfos = info.sourceMapFilePath.sourceInfos; } - if (!sourceInfos) - return; - if (!forEachKey(sourceInfos, (path) => { + if (!sourceInfos) return; + if (!forEachKey(sourceInfos, path => { const info2 = this.getScriptInfoForPath(path); return !!info2 && (info2.isScriptOpen() || !info2.isOrphan()); })) { @@ -178832,7 +162615,7 @@ Dynamic files must always be opened with service's current directory or service } } }); - toRemoveScriptInfos.forEach((info) => { + toRemoveScriptInfos.forEach(info => { this.stopWatchingScriptInfo(info); this.deleteScriptInfo(info); info.closeSourceMapFileWatcher(); @@ -178848,7 +162631,14 @@ Dynamic files must always be opened with service's current directory or service } const sourceFile = project.getSourceFile(scriptInfo.path); const checkJs = !!sourceFile && !!sourceFile.checkJsDirective; - this.eventHandler({ eventName: OpenFileInfoTelemetryEvent, data: { info: { checkJs } } }); + this.eventHandler({ + eventName: OpenFileInfoTelemetryEvent, + data: { + info: { + checkJs + } + } + }); } closeClientFile(uncheckedFileName, skipAssignOrphanScriptInfosToInferredProject) { const info = this.getScriptInfoForNormalizedPath(toNormalizedPath(uncheckedFileName)); @@ -178860,7 +162650,7 @@ Dynamic files must always be opened with service's current directory or service } collectChanges(lastKnownProjectVersions, currentProjects, includeProjectReferenceRedirectInfo, result) { for (const proj of currentProjects) { - const knownProject = find(lastKnownProjectVersions, (p) => p.projectName === proj.getProjectName()); + const knownProject = find(lastKnownProjectVersions, p => p.projectName === proj.getProjectName()); result.push(proj.getChangesSinceVersion(knownProject && knownProject.version, includeProjectReferenceRedirectInfo)); } } @@ -178878,13 +162668,7 @@ Dynamic files must always be opened with service's current directory or service let assignOrphanScriptInfosToInferredProject = false; if (openFiles) { for (const file of openFiles) { - const info = this.getOrCreateOpenScriptInfo( - toNormalizedPath(file.fileName), - file.content, - tryConvertScriptKindName(file.scriptKind), - file.hasMixedContent, - file.projectRootPath ? toNormalizedPath(file.projectRootPath) : void 0 - ); + const info = this.getOrCreateOpenScriptInfo(toNormalizedPath(file.fileName), file.content, tryConvertScriptKindName(file.scriptKind), file.hasMixedContent, file.projectRootPath ? toNormalizedPath(file.projectRootPath) : void 0); (openScriptInfos || (openScriptInfos = [])).push(info); } } @@ -178897,23 +162681,20 @@ Dynamic files must always be opened with service's current directory or service } if (closedFiles) { for (const file of closedFiles) { - assignOrphanScriptInfosToInferredProject = this.closeClientFile( - file, - /*skipAssignOrphanScriptInfosToInferredProject*/ - true - ) || assignOrphanScriptInfosToInferredProject; + assignOrphanScriptInfosToInferredProject = this.closeClientFile(file, /*skipAssignOrphanScriptInfosToInferredProject*/ + true) || assignOrphanScriptInfosToInferredProject; } } let retainProjects; if (openScriptInfos) { - retainProjects = flatMap(openScriptInfos, (info) => this.assignProjectToOpenedScriptInfo(info).retainProjects); + retainProjects = flatMap(openScriptInfos, info => this.assignProjectToOpenedScriptInfo(info).retainProjects); } if (assignOrphanScriptInfosToInferredProject) { this.assignOrphanScriptInfosToInferredProject(); } if (openScriptInfos) { this.cleanupAfterOpeningFile(retainProjects); - openScriptInfos.forEach((info) => this.telemetryOnOpenFile(info)); + openScriptInfos.forEach(info => this.telemetryOnOpenFile(info)); this.printProjects(); } else if (length(closedFiles)) { this.printProjects(); @@ -178951,15 +162732,15 @@ Dynamic files must always be opened with service's current directory or service } } openExternalProjects(projects) { - const projectsToClose = arrayToMap(this.externalProjects, (p) => p.getProjectName(), (_) => true); - forEachKey(this.externalProjectToConfiguredProjectMap, (externalProjectName) => { + const projectsToClose = arrayToMap(this.externalProjects, p => p.getProjectName(), _ => true); + forEachKey(this.externalProjectToConfiguredProjectMap, externalProjectName => { projectsToClose.set(externalProjectName, true); }); for (const externalProject of projects) { this.openExternalProject(externalProject); projectsToClose.delete(externalProject.projectFileName); } - forEachKey(projectsToClose, (externalProjectName) => { + forEachKey(projectsToClose, externalProjectName => { this.closeExternalProject(externalProjectName); }); } @@ -178970,7 +162751,9 @@ Dynamic files must always be opened with service's current directory or service this.safelist = defaultTypeSafeList; } applySafeList(proj) { - const { rootFiles } = proj; + const { + rootFiles + } = proj; const typeAcquisition = proj.typeAcquisition; Debug.assert(!!typeAcquisition, "proj.typeAcquisition should be set by now"); if (typeAcquisition.enable === false || typeAcquisition.disableFilenameBasedTypeAcquisition) { @@ -178978,7 +162761,7 @@ Dynamic files must always be opened with service's current directory or service } const typeAcqInclude = typeAcquisition.include || (typeAcquisition.include = []); const excludeRules = []; - const normalizedNames = rootFiles.map((f) => normalizeSlashes(f.fileName)); + const normalizedNames = rootFiles.map(f => normalizeSlashes(f.fileName)); const excludedFiles = []; for (const name of Object.keys(this.safelist)) { const rule2 = this.safelist[name]; @@ -178995,7 +162778,7 @@ Dynamic files must always be opened with service's current directory or service if (rule2.exclude) { for (const exclude of rule2.exclude) { const processedRule = root.replace(rule2.match, (...groups) => { - return exclude.map((groupNumberOrString) => { + return exclude.map(groupNumberOrString => { if (typeof groupNumberOrString === "number") { if (!isString(groups[groupNumberOrString])) { this.logger.info(`Incorrect RegExp specification in safelist rule ${name} - not enough groups`); @@ -179019,10 +162802,10 @@ Dynamic files must always be opened with service's current directory or service } } } - const excludeRegexes = excludeRules.map((e) => new RegExp(e, "i")); + const excludeRegexes = excludeRules.map(e => new RegExp(e, "i")); const filesToKeep = []; for (let i = 0; i < proj.rootFiles.length; i++) { - if (excludeRegexes.some((re) => re.test(normalizedNames[i]))) { + if (excludeRegexes.some(re => re.test(normalizedNames[i]))) { excludedFiles.push(normalizedNames[i]); } else { let exclude = false; @@ -179059,7 +162842,7 @@ Dynamic files must always be opened with service's current directory or service proj.typeAcquisition.include = proj.typeAcquisition.include || []; proj.typeAcquisition.exclude = proj.typeAcquisition.exclude || []; if (proj.typeAcquisition.enable === void 0) { - proj.typeAcquisition.enable = hasNoTypeScriptSource(proj.rootFiles.map((f) => f.fileName)); + proj.typeAcquisition.enable = hasNoTypeScriptSource(proj.rootFiles.map(f => f.fileName)); } const excludedFiles = this.applySafeList(proj); let tsConfigFiles; @@ -179162,34 +162945,25 @@ Dynamic files must always be opened with service's current directory or service return; } if (this.host.importPlugin) { - const importPromise = Project3.importServicePluginAsync( - pluginConfigEntry, - searchPaths, - this.host, - (s) => this.logger.info(s) - ); - this.pendingPluginEnablements ?? (this.pendingPluginEnablements = /* @__PURE__ */ new Map()); + var _this$pendingPluginEn; + const importPromise = Project3.importServicePluginAsync(pluginConfigEntry, searchPaths, this.host, s => this.logger.info(s)); + (_this$pendingPluginEn = this.pendingPluginEnablements) !== null && _this$pendingPluginEn !== void 0 ? _this$pendingPluginEn : 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; } - this.endEnablePlugin( - project, - Project3.importServicePluginSync( - pluginConfigEntry, - searchPaths, - this.host, - (s) => this.logger.info(s) - ) - ); + this.endEnablePlugin(project, Project3.importServicePluginSync(pluginConfigEntry, searchPaths, this.host, s => this.logger.info(s))); } /** * Performs the remaining steps of enabling a plugin after its module has been instantiated. * @internal */ - endEnablePlugin(project, { pluginConfigEntry, resolvedModule, errorLogs }) { + endEnablePlugin(project, { + pluginConfigEntry, + resolvedModule, + errorLogs + }) { var _a; if (resolvedModule) { const configurationOverride = (_a = this.currentPluginConfigOverrides) == null ? void 0 : _a.get(pluginConfigEntry.name); @@ -179200,7 +162974,7 @@ Dynamic files must always be opened with service's current directory or service } project.enableProxy(resolvedModule, pluginConfigEntry); } else { - forEach(errorLogs, (message) => this.logger.info(message)); + forEach(errorLogs, message => this.logger.info(message)); this.logger.info(`Couldn't find ${pluginConfigEntry.name}`); } } @@ -179261,8 +163035,8 @@ Dynamic files must always be opened with service's current directory or service this.delayUpdateProjectGraph(project); } configurePlugin(args) { - this.forEachEnabledProject((project) => project.onPluginConfigurationChanged(args.pluginName, args.configuration)); - this.currentPluginConfigOverrides = this.currentPluginConfigOverrides || /* @__PURE__ */ new Map(); + this.forEachEnabledProject(project => project.onPluginConfigurationChanged(args.pluginName, args.configuration)); + this.currentPluginConfigOverrides = this.currentPluginConfigOverrides || /* @__PURE__ */new Map(); this.currentPluginConfigOverrides.set(args.pluginName, args.configuration); } /** @internal */ @@ -179271,7 +163045,7 @@ Dynamic files must always be opened with service's current directory or service const rootPath = rootDir && this.toPath(rootDir); const filePath = this.toPath(fileName); const result = []; - const processDirectory = (directory) => { + const processDirectory = directory => { switch (packageJsonCache.directoryHasPackageJson(directory)) { case 3 /* Maybe */: packageJsonCache.searchDirectoryAndAncestors(directory); @@ -179280,8 +163054,7 @@ Dynamic files must always be opened with service's current directory or service const packageJsonFileName = combinePaths(directory, "package.json"); this.watchPackageJsonFile(packageJsonFileName); const info = packageJsonCache.getInDirectory(directory); - if (info) - result.push(info); + if (info) result.push(info); } if (rootPath && rootPath === directory) { return true; @@ -179292,7 +163065,7 @@ Dynamic files must always be opened with service's current directory or service } /** @internal */ getNearestAncestorDirectoryWithPackageJson(fileName) { - return forEachAncestorDirectory(fileName, (directory) => { + return forEachAncestorDirectory(fileName, directory => { switch (this.packageJsonCache.directoryHasPackageJson(this.toPath(directory))) { case -1 /* True */: return directory; @@ -179305,34 +163078,25 @@ Dynamic files must always be opened with service's current directory or service } /** @internal */ watchPackageJsonFile(path) { - const watchers = this.packageJsonFilesMap || (this.packageJsonFilesMap = /* @__PURE__ */ new Map()); + const watchers = this.packageJsonFilesMap || (this.packageJsonFilesMap = /* @__PURE__ */new Map()); if (!watchers.has(path)) { this.invalidateProjectPackageJson(path); - watchers.set( - path, - this.watchFactory.watchFile( - path, - (fileName, eventKind) => { - const path2 = this.toPath(fileName); - switch (eventKind) { - case 0 /* Created */: - return Debug.fail(); - case 1 /* Changed */: - this.packageJsonCache.addOrUpdate(path2); - this.invalidateProjectPackageJson(path2); - break; - case 2 /* Deleted */: - this.packageJsonCache.delete(path2); - this.invalidateProjectPackageJson(path2); - watchers.get(path2).close(); - watchers.delete(path2); - } - }, - 250 /* Low */, - this.hostConfiguration.watchOptions, - WatchType.PackageJson - ) - ); + watchers.set(path, this.watchFactory.watchFile(path, (fileName, eventKind) => { + const path2 = this.toPath(fileName); + switch (eventKind) { + case 0 /* Created */: + return Debug.fail(); + case 1 /* Changed */: + this.packageJsonCache.addOrUpdate(path2); + this.invalidateProjectPackageJson(path2); + break; + case 2 /* Deleted */: + this.packageJsonCache.delete(path2); + this.invalidateProjectPackageJson(path2); + watchers.get(path2).close(); + watchers.delete(path2); + } + }, 250 /* Low */, this.hostConfiguration.watchOptions, WatchType.PackageJson)); } } /** @internal */ @@ -179382,26 +163146,18 @@ Dynamic files must always be opened with service's current directory or service 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) { - ensureCache(fromFileName, preferences, options).set(toFileName2, createInfo( - modulePaths, - moduleSpecifiers, - /*isBlockedByPackageJsonDependencies*/ - false - )); + ensureCache(fromFileName, preferences, options).set(toFileName2, createInfo(modulePaths, moduleSpecifiers, /*isBlockedByPackageJsonDependencies*/ + false)); if (moduleSpecifiers) { for (const p of modulePaths) { if (p.isInNodeModules) { const nodeModulesPath = p.path.substring(0, p.path.indexOf(nodeModulesPathPart) + nodeModulesPathPart.length - 1); if (!(containedNodeModulesWatchers == null ? void 0 : containedNodeModulesWatchers.has(nodeModulesPath))) { - (containedNodeModulesWatchers || (containedNodeModulesWatchers = /* @__PURE__ */ new Map())).set( - nodeModulesPath, - host.watchNodeModulesForPackageJsonChanges(nodeModulesPath) - ); + (containedNodeModulesWatchers || (containedNodeModulesWatchers = /* @__PURE__ */new Map())).set(nodeModulesPath, host.watchNodeModulesForPackageJsonChanges(nodeModulesPath)); } } } @@ -179413,13 +163169,9 @@ Dynamic files must always be opened with service's current directory or service if (info) { info.modulePaths = modulePaths; } else { - cache2.set(toFileName2, createInfo( - modulePaths, - /*moduleSpecifiers*/ - void 0, - /*isBlockedByPackageJsonDependencies*/ - void 0 - )); + cache2.set(toFileName2, createInfo(modulePaths, /*moduleSpecifiers*/ + void 0, /*isBlockedByPackageJsonDependencies*/ + void 0)); } }, setBlockedByPackageJsonDependencies(fromFileName, toFileName2, preferences, options, isBlockedByPackageJsonDependencies) { @@ -179428,17 +163180,13 @@ Dynamic files must always be opened with service's current directory or service if (info) { info.isBlockedByPackageJsonDependencies = isBlockedByPackageJsonDependencies; } else { - cache2.set(toFileName2, createInfo( - /*modulePaths*/ - void 0, - /*moduleSpecifiers*/ - void 0, - isBlockedByPackageJsonDependencies - )); + cache2.set(toFileName2, createInfo( /*modulePaths*/ + void 0, /*moduleSpecifiers*/ + void 0, isBlockedByPackageJsonDependencies)); } }, clear() { - containedNodeModulesWatchers == null ? void 0 : containedNodeModulesWatchers.forEach((watcher) => watcher.close()); + containedNodeModulesWatchers == null ? void 0 : containedNodeModulesWatchers.forEach(watcher => watcher.close()); cache == null ? void 0 : cache.clear(); containedNodeModulesWatchers == null ? void 0 : containedNodeModulesWatchers.clear(); currentKey = void 0; @@ -179448,7 +163196,9 @@ Dynamic files must always be opened with service's current directory or service } }; if (Debug.isDebugging) { - Object.defineProperty(result, "__cache", { get: () => cache }); + Object.defineProperty(result, "__cache", { + get: () => cache + }); } return result; function ensureCache(fromFileName, preferences, options) { @@ -179457,40 +163207,45 @@ Dynamic files must always be opened with service's current directory or service result.clear(); } currentKey = newKey; - return cache || (cache = /* @__PURE__ */ new Map()); + return cache || (cache = /* @__PURE__ */new Map()); } function key(fromFileName, preferences, options) { return `${fromFileName},${preferences.importModuleSpecifierEnding},${preferences.importModuleSpecifierPreference},${options.overrideImportMode}`; } function createInfo(modulePaths, moduleSpecifiers, isBlockedByPackageJsonDependencies) { - return { modulePaths, moduleSpecifiers, isBlockedByPackageJsonDependencies }; + return { + modulePaths, + moduleSpecifiers, + isBlockedByPackageJsonDependencies + }; } } var init_moduleSpecifierCache = __esm({ "src/server/moduleSpecifierCache.ts"() { "use strict"; + init_ts7(); } }); // src/server/packageJsonCache.ts function createPackageJsonCache(host) { - const packageJsons = /* @__PURE__ */ new Map(); - const directoriesWithoutPackageJson = /* @__PURE__ */ new Map(); + const packageJsons = /* @__PURE__ */new Map(); + const directoriesWithoutPackageJson = /* @__PURE__ */new Map(); return { addOrUpdate, forEach: packageJsons.forEach.bind(packageJsons), get: packageJsons.get.bind(packageJsons), - delete: (fileName) => { + delete: fileName => { packageJsons.delete(fileName); directoriesWithoutPackageJson.set(getDirectoryPath(fileName), true); }, - getInDirectory: (directory) => { + getInDirectory: directory => { return packageJsons.get(combinePaths(directory, "package.json")) || void 0; }, directoryHasPackageJson, - searchDirectoryAndAncestors: (directory) => { - forEachAncestorDirectory(directory, (ancestor) => { + searchDirectoryAndAncestors: directory => { + forEachAncestorDirectory(directory, ancestor => { if (directoryHasPackageJson(ancestor) !== 3 /* Maybe */) { return true; } @@ -179512,9 +163267,11 @@ Dynamic files must always be opened with service's current directory or service return packageJsons.has(combinePaths(directory, "package.json")) ? -1 /* True */ : directoriesWithoutPackageJson.has(directory) ? 0 /* False */ : 3 /* Maybe */; } } + var init_packageJsonCache = __esm({ "src/server/packageJsonCache.ts"() { "use strict"; + init_ts7(); } }); @@ -179571,13 +163328,19 @@ Dynamic files must always be opened with service's current directory or service }; } function convertToLocation(lineAndCharacter) { - return { line: lineAndCharacter.line + 1, offset: lineAndCharacter.character + 1 }; + return { + line: lineAndCharacter.line + 1, + offset: lineAndCharacter.character + 1 + }; } function formatDiagnosticToProtocol(diag2, includeFileName) { const start = diag2.file && convertToLocation(getLineAndCharacterOfPosition(diag2.file, diag2.start)); const end = diag2.file && convertToLocation(getLineAndCharacterOfPosition(diag2.file, diag2.start + diag2.length)); const text = flattenDiagnosticMessageText(diag2.messageText, "\n"); - const { code, source } = diag2; + const { + code, + source + } = diag2; const category = diagnosticCategoryName(diag2); const common = { start, @@ -179590,10 +163353,13 @@ Dynamic files must always be opened with service's current directory or service source, relatedInformation: map(diag2.relatedInformation, formatRelatedInformation) }; - return includeFileName ? { ...common, fileName: diag2.file && diag2.file.fileName } : common; + return includeFileName ? { + ...common, + fileName: diag2.file && diag2.file.fileName + } : common; } function allEditsBeforePos(edits, pos) { - return edits.every((edit) => textSpanEnd(edit.span) < pos); + return edits.every(edit => textSpanEnd(edit.span) < pos); } function formatMessage2(msg, logger, byteLength, newLine) { const verboseLogging = logger.hasLevel(3 /* verbose */); @@ -179615,28 +163381,23 @@ ${json}${newLine}`; }; } function combineProjectOutput(defaultValue, getValue, projects, action) { - const outputs = flatMapToMutable(isArray(projects) ? projects : projects.projects, (project) => action(project, defaultValue)); + const outputs = flatMapToMutable(isArray(projects) ? projects : projects.projects, project => action(project, defaultValue)); if (!isArray(projects) && projects.symLinkedProjects) { projects.symLinkedProjects.forEach((projects2, path) => { const value = getValue(path); - outputs.push(...flatMap(projects2, (project) => action(project, value))); + outputs.push(...flatMap(projects2, project => action(project, value))); }); } return deduplicate(outputs, equateValues); } function createDocumentSpanSet() { - return createSet(({ textSpan }) => textSpan.start + 100003 * textSpan.length, documentSpansEqual); + return createSet(({ + textSpan + }) => textSpan.start + 100003 * textSpan.length, documentSpansEqual); } function getRenameLocationsWorker(projects, defaultProject, initialLocation, findInStrings, findInComments, preferences) { - const perProjectResults = getPerProjectReferences( - projects, - defaultProject, - initialLocation, - /*isForRename*/ - true, - (project, position) => project.getLanguageService().findRenameLocations(position.fileName, position.pos, findInStrings, findInComments, preferences), - (renameLocation, cb) => cb(documentSpanLocation(renameLocation)) - ); + const perProjectResults = getPerProjectReferences(projects, defaultProject, initialLocation, /*isForRename*/ + true, (project, position) => project.getLanguageService().findRenameLocations(position.fileName, position.pos, findInStrings, findInComments, preferences), (renameLocation, cb) => cb(documentSpanLocation(renameLocation))); if (isArray(perProjectResults)) { return perProjectResults; } @@ -179653,42 +163414,33 @@ ${json}${newLine}`; return results; } function getDefinitionLocation(defaultProject, initialLocation, isForRename) { - const infos = defaultProject.getLanguageService().getDefinitionAtPosition( - initialLocation.fileName, - initialLocation.pos, - /*searchOtherFilesOnly*/ - false, - /*stopAtAlias*/ - isForRename - ); + const infos = defaultProject.getLanguageService().getDefinitionAtPosition(initialLocation.fileName, initialLocation.pos, /*searchOtherFilesOnly*/ + false, /*stopAtAlias*/ + isForRename); const info = infos && firstOrUndefined(infos); - return info && !info.isLocal ? { fileName: info.fileName, pos: info.textSpan.start } : void 0; + return info && !info.isLocal ? { + fileName: info.fileName, + pos: info.textSpan.start + } : void 0; } function getReferencesWorker(projects, defaultProject, initialLocation, logger) { var _a, _b; - const perProjectResults = getPerProjectReferences( - projects, - defaultProject, - initialLocation, - /*isForRename*/ - false, - (project, position) => { - logger.info(`Finding references to ${position.fileName} position ${position.pos} in project ${project.getProjectName()}`); - return project.getLanguageService().findReferences(position.fileName, position.pos); - }, - (referencedSymbol, cb) => { - cb(documentSpanLocation(referencedSymbol.definition)); - for (const ref of referencedSymbol.references) { - cb(documentSpanLocation(ref)); - } + const perProjectResults = getPerProjectReferences(projects, defaultProject, initialLocation, /*isForRename*/ + false, (project, position) => { + logger.info(`Finding references to ${position.fileName} position ${position.pos} in project ${project.getProjectName()}`); + return project.getLanguageService().findReferences(position.fileName, position.pos); + }, (referencedSymbol, cb) => { + cb(documentSpanLocation(referencedSymbol.definition)); + for (const ref of referencedSymbol.references) { + cb(documentSpanLocation(ref)); } - ); + }); if (isArray(perProjectResults)) { return perProjectResults; } const defaultProjectResults = perProjectResults.get(defaultProject); if (((_b = (_a = defaultProjectResults == null ? void 0 : defaultProjectResults[0]) == null ? void 0 : _a.references[0]) == null ? void 0 : _b.isDefinition) === void 0) { - perProjectResults.forEach((projectResults) => { + perProjectResults.forEach(projectResults => { for (const referencedSymbol of projectResults) { for (const ref of referencedSymbol.references) { delete ref.isDefinition; @@ -179705,24 +163457,21 @@ ${json}${newLine}`; } } } - const updatedProjects = /* @__PURE__ */ new Set(); + const updatedProjects = /* @__PURE__ */new Set(); 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; @@ -179742,9 +163491,12 @@ ${json}${newLine}`; fileName: mappedDefinitionFile.fileName, contextSpan: getMappedContextSpanForProject(referencedSymbol.definition, project) }; - let symbolToAddTo = find(results, (o) => documentSpansEqual(o.definition, definition)); + let symbolToAddTo = find(results, o => documentSpansEqual(o.definition, definition)); if (!symbolToAddTo) { - symbolToAddTo = { definition, references: [] }; + symbolToAddTo = { + definition, + references: [] + }; results.push(symbolToAddTo); } for (const ref of referencedSymbol.references) { @@ -179755,7 +163507,7 @@ ${json}${newLine}`; } } }); - return results.filter((o) => o.references.length !== 0); + return results.filter(o => o.references.length !== 0); } function forEachProjectInProjects(projects, path, cb) { for (const project of isArray(projects) ? projects : projects.projects) { @@ -179770,72 +163522,78 @@ ${json}${newLine}`; } } function getPerProjectReferences(projects, defaultProject, initialLocation, isForRename, getResultsForPosition, forPositionInResult) { - const resultsMap = /* @__PURE__ */ new Map(); + const resultsMap = /* @__PURE__ */new Map(); const queue = createQueue(); - queue.enqueue({ project: defaultProject, location: initialLocation }); + queue.enqueue({ + project: defaultProject, + location: initialLocation + }); forEachProjectInProjects(projects, initialLocation.fileName, (project, path) => { - const location = { fileName: path, pos: initialLocation.pos }; - queue.enqueue({ project, location }); + const location = { + fileName: path, + pos: initialLocation.pos + }; + queue.enqueue({ + project, + location + }); }); const projectService = defaultProject.projectService; const cancellationToken = defaultProject.getCancellationToken(); const defaultDefinition = getDefinitionLocation(defaultProject, initialLocation, isForRename); - const getGeneratedDefinition = memoize( - () => defaultProject.isSourceOfProjectReferenceRedirect(defaultDefinition.fileName) ? defaultDefinition : defaultProject.getLanguageService().getSourceMapper().tryGetGeneratedPosition(defaultDefinition) - ); - const getSourceDefinition = memoize( - () => defaultProject.isSourceOfProjectReferenceRedirect(defaultDefinition.fileName) ? defaultDefinition : defaultProject.getLanguageService().getSourceMapper().tryGetSourcePosition(defaultDefinition) - ); - const searchedProjectKeys = /* @__PURE__ */ new Set(); - onCancellation: + const getGeneratedDefinition = memoize(() => defaultProject.isSourceOfProjectReferenceRedirect(defaultDefinition.fileName) ? defaultDefinition : defaultProject.getLanguageService().getSourceMapper().tryGetGeneratedPosition(defaultDefinition)); + const getSourceDefinition = memoize(() => defaultProject.isSourceOfProjectReferenceRedirect(defaultDefinition.fileName) ? defaultDefinition : defaultProject.getLanguageService().getSourceMapper().tryGetSourcePosition(defaultDefinition)); + const searchedProjectKeys = /* @__PURE__ */new Set(); + onCancellation: while (!queue.isEmpty()) { while (!queue.isEmpty()) { - while (!queue.isEmpty()) { - if (cancellationToken.isCancellationRequested()) - break onCancellation; - const { project, location } = queue.dequeue(); - if (resultsMap.has(project)) - continue; - if (isLocationProjectReferenceRedirect(project, location)) - continue; - updateProjectIfDirty(project); - if (!project.containsFile(toNormalizedPath(location.fileName))) { - continue; - } - const projectResults = searchPosition(project, location); - resultsMap.set(project, projectResults ?? emptyArray2); - searchedProjectKeys.add(getProjectKey(project)); - } - if (defaultDefinition) { - projectService.loadAncestorProjectTree(searchedProjectKeys); - projectService.forEachEnabledProject((project) => { - if (cancellationToken.isCancellationRequested()) - return; - if (resultsMap.has(project)) - return; - const location = mapDefinitionInProject(defaultDefinition, project, getGeneratedDefinition, getSourceDefinition); - if (location) { - queue.enqueue({ project, location }); - } - }); + if (cancellationToken.isCancellationRequested()) break onCancellation; + const { + project, + location + } = queue.dequeue(); + if (resultsMap.has(project)) continue; + if (isLocationProjectReferenceRedirect(project, location)) continue; + updateProjectIfDirty(project); + if (!project.containsFile(toNormalizedPath(location.fileName))) { + continue; } + const projectResults = searchPosition(project, location); + resultsMap.set(project, projectResults !== null && projectResults !== void 0 ? projectResults : emptyArray2); + searchedProjectKeys.add(getProjectKey(project)); } + if (defaultDefinition) { + projectService.loadAncestorProjectTree(searchedProjectKeys); + projectService.forEachEnabledProject(project => { + if (cancellationToken.isCancellationRequested()) return; + if (resultsMap.has(project)) return; + const location = mapDefinitionInProject(defaultDefinition, project, getGeneratedDefinition, getSourceDefinition); + if (location) { + queue.enqueue({ + project, + location + }); + } + }); + } + } if (resultsMap.size === 1) { return firstIterator(resultsMap.values()); } 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) => { + 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)) { - queue.enqueue({ project: project2, location: originalLocation }); + queue.enqueue({ + project: project2, + location: originalLocation + }); } } const symlinkedProjectsMap = projectService.getSymlinkedProjects(originalScriptInfo); @@ -179843,7 +163601,13 @@ ${json}${newLine}`; symlinkedProjectsMap.forEach((symlinkedProjects, symlinkedPath) => { for (const symlinkedProject of symlinkedProjects) { if (!symlinkedProject.isOrphan() && !resultsMap.has(symlinkedProject)) { - queue.enqueue({ project: symlinkedProject, location: { fileName: symlinkedPath, pos: originalLocation.pos } }); + queue.enqueue({ + project: symlinkedProject, + location: { + fileName: symlinkedPath, + pos: originalLocation.pos + } + }); } } }); @@ -179858,34 +163622,37 @@ ${json}${newLine}`; 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); } function getProjectKey(project) { return isConfiguredProject(project) ? project.canonicalConfigFilePath : project.getProjectName(); } - function documentSpanLocation({ fileName, textSpan }) { - return { fileName, pos: textSpan.start }; + function documentSpanLocation({ + fileName, + textSpan + }) { + return { + fileName, + pos: textSpan.start + }; } function getMappedLocationForProject(location, project) { - return getMappedLocation(location, project.getSourceMapper(), (p) => project.projectService.fileExists(p)); + return getMappedLocation(location, project.getSourceMapper(), p => project.projectService.fileExists(p)); } function getMappedDocumentSpanForProject(documentSpan, project) { - return getMappedDocumentSpan(documentSpan, project.getSourceMapper(), (p) => project.projectService.fileExists(p)); + return getMappedDocumentSpan(documentSpan, project.getSourceMapper(), p => project.projectService.fileExists(p)); } function getMappedContextSpanForProject(documentSpan, project) { - return getMappedContextSpan(documentSpan, project.getSourceMapper(), (p) => project.projectService.fileExists(p)); + return getMappedContextSpan(documentSpan, project.getSourceMapper(), p => project.projectService.fileExists(p)); } function toProtocolTextSpan(textSpan, scriptInfo) { return { @@ -179896,54 +163663,103 @@ ${json}${newLine}`; function toProtocolTextSpanWithContext(span, contextSpan, scriptInfo) { const textSpan = toProtocolTextSpan(span, scriptInfo); const contextTextSpan = contextSpan && toProtocolTextSpan(contextSpan, scriptInfo); - return contextTextSpan ? { ...textSpan, contextStart: contextTextSpan.start, contextEnd: contextTextSpan.end } : textSpan; + return contextTextSpan ? { + ...textSpan, + contextStart: contextTextSpan.start, + contextEnd: contextTextSpan.end + } : textSpan; } function convertTextChangeToCodeEdit(change, scriptInfo) { - return { start: positionToLineOffset(scriptInfo, change.span.start), end: positionToLineOffset(scriptInfo, textSpanEnd(change.span)), newText: change.newText }; + return { + start: positionToLineOffset(scriptInfo, change.span.start), + end: positionToLineOffset(scriptInfo, textSpanEnd(change.span)), + newText: change.newText + }; } function positionToLineOffset(info, position) { return isConfigFile(info) ? locationFromLineAndCharacter(info.getLineAndCharacterOfPosition(position)) : info.positionToLineOffset(position); } function convertLinkedEditInfoToRanges(linkedEdit, scriptInfo) { - const ranges = linkedEdit.ranges.map( - (r) => { - return { - start: scriptInfo.positionToLineOffset(r.start), - end: scriptInfo.positionToLineOffset(r.start + r.length) - }; - } - ); - if (!linkedEdit.wordPattern) - return { ranges }; - return { ranges, wordPattern: linkedEdit.wordPattern }; + const ranges = linkedEdit.ranges.map(r => { + return { + start: scriptInfo.positionToLineOffset(r.start), + end: scriptInfo.positionToLineOffset(r.start + r.length) + }; + }); + if (!linkedEdit.wordPattern) return { + ranges + }; + return { + ranges, + wordPattern: linkedEdit.wordPattern + }; } function locationFromLineAndCharacter(lc) { - return { line: lc.line + 1, offset: lc.character + 1 }; + return { + line: lc.line + 1, + offset: lc.character + 1 + }; } function convertNewFileTextChangeToCodeEdit(textChanges2) { Debug.assert(textChanges2.textChanges.length === 1); const change = first(textChanges2.textChanges); Debug.assert(change.span.start === 0 && change.span.length === 0); - return { fileName: textChanges2.fileName, textChanges: [{ start: { line: 0, offset: 0 }, end: { line: 0, offset: 0 }, newText: change.newText }] }; + return { + fileName: textChanges2.fileName, + textChanges: [{ + start: { + line: 0, + offset: 0 + }, + end: { + line: 0, + offset: 0 + }, + newText: change.newText + }] + }; } function getLocationInNewDocument(oldText, renameFilename, renameLocation, edits) { const newText = applyEdits(oldText, renameFilename, edits); - const { line, character } = computeLineAndCharacterOfPosition(computeLineStarts(newText), renameLocation); - return { line: line + 1, offset: character + 1 }; + const { + line, + character + } = computeLineAndCharacterOfPosition(computeLineStarts(newText), renameLocation); + return { + line: line + 1, + offset: character + 1 + }; } function applyEdits(text, textFilename, edits) { - for (const { fileName, textChanges: textChanges2 } of edits) { + for (const { + fileName, + textChanges: textChanges2 + } of edits) { if (fileName !== textFilename) { continue; } for (let i = textChanges2.length - 1; i >= 0; i--) { - const { newText, span: { start, length: length2 } } = textChanges2[i]; + const { + newText, + span: { + start, + length: length2 + } + } = textChanges2[i]; text = text.slice(0, start) + newText + text.slice(start + length2); } } return text; } - function referenceEntryToReferencesResponseItem(projectService, { fileName, textSpan, contextSpan, isWriteAccess: isWriteAccess2, isDefinition }, { disableLineTextInReferences }) { + function referenceEntryToReferencesResponseItem(projectService, { + fileName, + textSpan, + contextSpan, + isWriteAccess: isWriteAccess2, + isDefinition + }, { + disableLineTextInReferences + }) { const scriptInfo = Debug.checkDefined(projectService.getScriptInfo(fileName)); const span = toProtocolTextSpanWithContext(textSpan, contextSpan, scriptInfo); const lineText = disableLineTextInReferences ? void 0 : getLineText(scriptInfo, span); @@ -179966,6 +163782,7 @@ ${json}${newLine}`; var init_session = __esm({ "src/server/session.ts"() { "use strict"; + init_ts7(); init_ts_server3(); init_protocol(); @@ -179995,26 +163812,18 @@ ${json}${newLine}`; immediate(actionType, action) { const requestId = this.requestId; Debug.assert(requestId === this.operationHost.getCurrentRequestId(), "immediate: incorrect request id"); - this.setImmediateId( - this.operationHost.getServerHost().setImmediate(() => { - this.immediateId = void 0; - this.operationHost.executeWithRequestId(requestId, () => this.executeAction(action)); - }, actionType) - ); + this.setImmediateId(this.operationHost.getServerHost().setImmediate(() => { + this.immediateId = void 0; + this.operationHost.executeWithRequestId(requestId, () => this.executeAction(action)); + }, actionType)); } delay(actionType, ms, action) { const requestId = this.requestId; Debug.assert(requestId === this.operationHost.getCurrentRequestId(), "delay: incorrect request id"); - this.setTimerHandle( - this.operationHost.getServerHost().setTimeout( - () => { - this.timerHandle = void 0; - this.operationHost.executeWithRequestId(requestId, () => this.executeAction(action)); - }, - ms, - actionType - ) - ); + this.setTimerHandle(this.operationHost.getServerHost().setTimeout(() => { + this.timerHandle = void 0; + this.operationHost.executeWithRequestId(requestId, () => this.executeAction(action)); + }, ms, actionType)); } executeAction(action) { var _a, _b, _c, _d, _e, _f; @@ -180022,9 +163831,14 @@ ${json}${newLine}`; try { if (this.operationHost.isCancellationRequested()) { stop = true; - (_a = tracing) == null ? void 0 : _a.instant(tracing.Phase.Session, "stepCanceled", { seq: this.requestId, early: true }); + (_a = tracing) == null ? void 0 : _a.instant(tracing.Phase.Session, "stepCanceled", { + seq: this.requestId, + early: true + }); } else { - (_b = tracing) == null ? void 0 : _b.push(tracing.Phase.Session, "stepAction", { seq: this.requestId }); + (_b = tracing) == null ? void 0 : _b.push(tracing.Phase.Session, "stepAction", { + seq: this.requestId + }); action(this); (_c = tracing) == null ? void 0 : _c.pop(); } @@ -180032,9 +163846,14 @@ ${json}${newLine}`; (_d = tracing) == null ? void 0 : _d.popAll(); stop = true; if (e instanceof OperationCanceledException) { - (_e = tracing) == null ? void 0 : _e.instant(tracing.Phase.Session, "stepCanceled", { seq: this.requestId }); + (_e = tracing) == null ? void 0 : _e.instant(tracing.Phase.Session, "stepCanceled", { + seq: this.requestId + }); } else { - (_f = tracing) == null ? void 0 : _f.instant(tracing.Phase.Session, "stepError", { seq: this.requestId, message: e.message }); + (_f = tracing) == null ? void 0 : _f.instant(tracing.Phase.Session, "stepError", { + seq: this.requestId, + message: e.message + }); this.operationHost.logError(e, `delayed processing of request ${this.requestId}`); } } @@ -180058,103 +163877,42 @@ ${json}${newLine}`; return !!this.timerHandle || !!this.immediateId; } }; - invalidPartialSemanticModeCommands = [ - "openExternalProject" /* OpenExternalProject */, - "openExternalProjects" /* OpenExternalProjects */, - "closeExternalProject" /* CloseExternalProject */, - "synchronizeProjectList" /* SynchronizeProjectList */, - "emit-output" /* EmitOutput */, - "compileOnSaveAffectedFileList" /* CompileOnSaveAffectedFileList */, - "compileOnSaveEmitFile" /* CompileOnSaveEmitFile */, - "compilerOptionsDiagnostics-full" /* CompilerOptionsDiagnosticsFull */, - "encodedSemanticClassifications-full" /* EncodedSemanticClassificationsFull */, - "semanticDiagnosticsSync" /* SemanticDiagnosticsSync */, - "suggestionDiagnosticsSync" /* SuggestionDiagnosticsSync */, - "geterrForProject" /* GeterrForProject */, - "reload" /* Reload */, - "reloadProjects" /* ReloadProjects */, - "getCodeFixes" /* GetCodeFixes */, - "getCodeFixes-full" /* GetCodeFixesFull */, - "getCombinedCodeFix" /* GetCombinedCodeFix */, - "getCombinedCodeFix-full" /* GetCombinedCodeFixFull */, - "applyCodeActionCommand" /* ApplyCodeActionCommand */, - "getSupportedCodeFixes" /* GetSupportedCodeFixes */, - "getApplicableRefactors" /* GetApplicableRefactors */, - "getMoveToRefactoringFileSuggestions" /* GetMoveToRefactoringFileSuggestions */, - "getEditsForRefactor" /* GetEditsForRefactor */, - "getEditsForRefactor-full" /* GetEditsForRefactorFull */, - "organizeImports" /* OrganizeImports */, - "organizeImports-full" /* OrganizeImportsFull */, - "getEditsForFileRename" /* GetEditsForFileRename */, - "getEditsForFileRename-full" /* GetEditsForFileRenameFull */, - "prepareCallHierarchy" /* PrepareCallHierarchy */, - "provideCallHierarchyIncomingCalls" /* ProvideCallHierarchyIncomingCalls */, - "provideCallHierarchyOutgoingCalls" /* ProvideCallHierarchyOutgoingCalls */ - ]; - invalidSyntacticModeCommands = [ - ...invalidPartialSemanticModeCommands, - "definition" /* Definition */, - "definition-full" /* DefinitionFull */, - "definitionAndBoundSpan" /* DefinitionAndBoundSpan */, - "definitionAndBoundSpan-full" /* DefinitionAndBoundSpanFull */, - "typeDefinition" /* TypeDefinition */, - "implementation" /* Implementation */, - "implementation-full" /* ImplementationFull */, - "references" /* References */, - "references-full" /* ReferencesFull */, - "rename" /* Rename */, - "renameLocations-full" /* RenameLocationsFull */, - "rename-full" /* RenameInfoFull */, - "quickinfo" /* Quickinfo */, - "quickinfo-full" /* QuickinfoFull */, - "completionInfo" /* CompletionInfo */, - "completions" /* Completions */, - "completions-full" /* CompletionsFull */, - "completionEntryDetails" /* CompletionDetails */, - "completionEntryDetails-full" /* CompletionDetailsFull */, - "signatureHelp" /* SignatureHelp */, - "signatureHelp-full" /* SignatureHelpFull */, - "navto" /* Navto */, - "navto-full" /* NavtoFull */, - "documentHighlights" /* DocumentHighlights */, - "documentHighlights-full" /* DocumentHighlightsFull */ - ]; + invalidPartialSemanticModeCommands = ["openExternalProject" /* OpenExternalProject */, "openExternalProjects" /* OpenExternalProjects */, "closeExternalProject" /* CloseExternalProject */, "synchronizeProjectList" /* SynchronizeProjectList */, "emit-output" /* EmitOutput */, "compileOnSaveAffectedFileList" /* CompileOnSaveAffectedFileList */, "compileOnSaveEmitFile" /* CompileOnSaveEmitFile */, "compilerOptionsDiagnostics-full" /* CompilerOptionsDiagnosticsFull */, "encodedSemanticClassifications-full" /* EncodedSemanticClassificationsFull */, "semanticDiagnosticsSync" /* SemanticDiagnosticsSync */, "suggestionDiagnosticsSync" /* SuggestionDiagnosticsSync */, "geterrForProject" /* GeterrForProject */, "reload" /* Reload */, "reloadProjects" /* ReloadProjects */, "getCodeFixes" /* GetCodeFixes */, "getCodeFixes-full" /* GetCodeFixesFull */, "getCombinedCodeFix" /* GetCombinedCodeFix */, "getCombinedCodeFix-full" /* GetCombinedCodeFixFull */, "applyCodeActionCommand" /* ApplyCodeActionCommand */, "getSupportedCodeFixes" /* GetSupportedCodeFixes */, "getApplicableRefactors" /* GetApplicableRefactors */, "getMoveToRefactoringFileSuggestions" /* GetMoveToRefactoringFileSuggestions */, "getEditsForRefactor" /* GetEditsForRefactor */, "getEditsForRefactor-full" /* GetEditsForRefactorFull */, "organizeImports" /* OrganizeImports */, "organizeImports-full" /* OrganizeImportsFull */, "getEditsForFileRename" /* GetEditsForFileRename */, "getEditsForFileRename-full" /* GetEditsForFileRenameFull */, "prepareCallHierarchy" /* PrepareCallHierarchy */, "provideCallHierarchyIncomingCalls" /* ProvideCallHierarchyIncomingCalls */, "provideCallHierarchyOutgoingCalls" /* ProvideCallHierarchyOutgoingCalls */]; + + invalidSyntacticModeCommands = [...invalidPartialSemanticModeCommands, "definition" /* Definition */, "definition-full" /* DefinitionFull */, "definitionAndBoundSpan" /* DefinitionAndBoundSpan */, "definitionAndBoundSpan-full" /* DefinitionAndBoundSpanFull */, "typeDefinition" /* TypeDefinition */, "implementation" /* Implementation */, "implementation-full" /* ImplementationFull */, "references" /* References */, "references-full" /* ReferencesFull */, "rename" /* Rename */, "renameLocations-full" /* RenameLocationsFull */, "rename-full" /* RenameInfoFull */, "quickinfo" /* Quickinfo */, "quickinfo-full" /* QuickinfoFull */, "completionInfo" /* CompletionInfo */, "completions" /* Completions */, "completions-full" /* CompletionsFull */, "completionEntryDetails" /* CompletionDetails */, "completionEntryDetails-full" /* CompletionDetailsFull */, "signatureHelp" /* SignatureHelp */, "signatureHelp-full" /* SignatureHelpFull */, "navto" /* Navto */, "navto-full" /* NavtoFull */, "documentHighlights" /* DocumentHighlights */, "documentHighlights-full" /* DocumentHighlightsFull */]; + Session3 = class _Session { constructor(opts) { this.changeSeq = 0; this.handlers = new Map(Object.entries({ // TODO(jakebailey): correctly type the handlers ["status" /* Status */]: () => { - const response = { version }; + const response = { + version + }; return this.requiredResponse(response); }, - ["openExternalProject" /* OpenExternalProject */]: (request) => { + ["openExternalProject" /* OpenExternalProject */]: request => { this.projectService.openExternalProject(request.arguments); - return this.requiredResponse( - /*response*/ - true - ); + return this.requiredResponse( /*response*/ + true); }, - ["openExternalProjects" /* OpenExternalProjects */]: (request) => { + ["openExternalProjects" /* OpenExternalProjects */]: request => { this.projectService.openExternalProjects(request.arguments.projects); - return this.requiredResponse( - /*response*/ - true - ); + return this.requiredResponse( /*response*/ + true); }, - ["closeExternalProject" /* CloseExternalProject */]: (request) => { + ["closeExternalProject" /* CloseExternalProject */]: request => { this.projectService.closeExternalProject(request.arguments.projectFileName); - return this.requiredResponse( - /*response*/ - true - ); + return this.requiredResponse( /*response*/ + true); }, - ["synchronizeProjectList" /* SynchronizeProjectList */]: (request) => { + ["synchronizeProjectList" /* SynchronizeProjectList */]: request => { const result = this.projectService.synchronizeProjectList(request.arguments.knownProjects, request.arguments.includeProjectReferenceRedirectInfo); - if (!result.some((p) => p.projectErrors && p.projectErrors.length !== 0)) { + if (!result.some(p => p.projectErrors && p.projectErrors.length !== 0)) { return this.requiredResponse(result); } - const converted = map(result, (p) => { + const converted = map(result, p => { if (!p.projectErrors || p.projectErrors.length === 0) { return p; } @@ -180162,600 +163920,428 @@ ${json}${newLine}`; info: p.info, changes: p.changes, files: p.files, - projectErrors: this.convertToDiagnosticsWithLinePosition( - p.projectErrors, - /*scriptInfo*/ - void 0 - ) + projectErrors: this.convertToDiagnosticsWithLinePosition(p.projectErrors, /*scriptInfo*/ + void 0) }; }); return this.requiredResponse(converted); }, - ["updateOpen" /* UpdateOpen */]: (request) => { + ["updateOpen" /* UpdateOpen */]: request => { this.changeSeq++; - this.projectService.applyChangesInOpenFiles( - request.arguments.openFiles && mapIterator(request.arguments.openFiles, (file) => ({ - fileName: file.file, - content: file.fileContent, - scriptKind: file.scriptKindName, - projectRootPath: file.projectRootPath - })), - request.arguments.changedFiles && mapIterator(request.arguments.changedFiles, (file) => ({ - fileName: file.fileName, - changes: mapDefinedIterator(arrayReverseIterator(file.textChanges), (change) => { - const scriptInfo = Debug.checkDefined(this.projectService.getScriptInfo(file.fileName)); - const start = scriptInfo.lineOffsetToPosition(change.start.line, change.start.offset); - const end = scriptInfo.lineOffsetToPosition(change.end.line, change.end.offset); - return start >= 0 ? { span: { start, length: end - start }, newText: change.newText } : void 0; - }) - })), - request.arguments.closedFiles - ); - return this.requiredResponse( - /*response*/ - true - ); + this.projectService.applyChangesInOpenFiles(request.arguments.openFiles && mapIterator(request.arguments.openFiles, file => ({ + fileName: file.file, + content: file.fileContent, + scriptKind: file.scriptKindName, + projectRootPath: file.projectRootPath + })), request.arguments.changedFiles && mapIterator(request.arguments.changedFiles, file => ({ + fileName: file.fileName, + changes: mapDefinedIterator(arrayReverseIterator(file.textChanges), change => { + const scriptInfo = Debug.checkDefined(this.projectService.getScriptInfo(file.fileName)); + const start = scriptInfo.lineOffsetToPosition(change.start.line, change.start.offset); + const end = scriptInfo.lineOffsetToPosition(change.end.line, change.end.offset); + return start >= 0 ? { + span: { + start, + length: end - start + }, + newText: change.newText + } : void 0; + }) + })), request.arguments.closedFiles); + return this.requiredResponse( /*response*/ + true); }, - ["applyChangedToOpenFiles" /* ApplyChangedToOpenFiles */]: (request) => { + ["applyChangedToOpenFiles" /* ApplyChangedToOpenFiles */]: request => { this.changeSeq++; - this.projectService.applyChangesInOpenFiles( - request.arguments.openFiles, - request.arguments.changedFiles && mapIterator(request.arguments.changedFiles, (file) => ({ - fileName: file.fileName, - // apply changes in reverse order - changes: arrayReverseIterator(file.changes) - })), - request.arguments.closedFiles - ); - return this.requiredResponse( - /*response*/ - true - ); + this.projectService.applyChangesInOpenFiles(request.arguments.openFiles, request.arguments.changedFiles && mapIterator(request.arguments.changedFiles, file => ({ + fileName: file.fileName, + // apply changes in reverse order + changes: arrayReverseIterator(file.changes) + })), request.arguments.closedFiles); + return this.requiredResponse( /*response*/ + true); }, ["exit" /* Exit */]: () => { this.exit(); return this.notRequired(); }, - ["definition" /* Definition */]: (request) => { - return this.requiredResponse(this.getDefinition( - request.arguments, - /*simplifiedResult*/ - true - )); + ["definition" /* Definition */]: request => { + return this.requiredResponse(this.getDefinition(request.arguments, /*simplifiedResult*/ + true)); }, - ["definition-full" /* DefinitionFull */]: (request) => { - return this.requiredResponse(this.getDefinition( - request.arguments, - /*simplifiedResult*/ - false - )); + ["definition-full" /* DefinitionFull */]: request => { + return this.requiredResponse(this.getDefinition(request.arguments, /*simplifiedResult*/ + false)); }, - ["definitionAndBoundSpan" /* DefinitionAndBoundSpan */]: (request) => { - return this.requiredResponse(this.getDefinitionAndBoundSpan( - request.arguments, - /*simplifiedResult*/ - true - )); + ["definitionAndBoundSpan" /* DefinitionAndBoundSpan */]: request => { + return this.requiredResponse(this.getDefinitionAndBoundSpan(request.arguments, /*simplifiedResult*/ + true)); }, - ["definitionAndBoundSpan-full" /* DefinitionAndBoundSpanFull */]: (request) => { - return this.requiredResponse(this.getDefinitionAndBoundSpan( - request.arguments, - /*simplifiedResult*/ - false - )); + ["definitionAndBoundSpan-full" /* DefinitionAndBoundSpanFull */]: request => { + return this.requiredResponse(this.getDefinitionAndBoundSpan(request.arguments, /*simplifiedResult*/ + false)); }, - ["findSourceDefinition" /* FindSourceDefinition */]: (request) => { + ["findSourceDefinition" /* FindSourceDefinition */]: request => { return this.requiredResponse(this.findSourceDefinition(request.arguments)); }, - ["emit-output" /* EmitOutput */]: (request) => { + ["emit-output" /* EmitOutput */]: request => { return this.requiredResponse(this.getEmitOutput(request.arguments)); }, - ["typeDefinition" /* TypeDefinition */]: (request) => { + ["typeDefinition" /* TypeDefinition */]: request => { return this.requiredResponse(this.getTypeDefinition(request.arguments)); }, - ["implementation" /* Implementation */]: (request) => { - return this.requiredResponse(this.getImplementation( - request.arguments, - /*simplifiedResult*/ - true - )); + ["implementation" /* Implementation */]: request => { + return this.requiredResponse(this.getImplementation(request.arguments, /*simplifiedResult*/ + true)); }, - ["implementation-full" /* ImplementationFull */]: (request) => { - return this.requiredResponse(this.getImplementation( - request.arguments, - /*simplifiedResult*/ - false - )); + ["implementation-full" /* ImplementationFull */]: request => { + return this.requiredResponse(this.getImplementation(request.arguments, /*simplifiedResult*/ + false)); }, - ["references" /* References */]: (request) => { - return this.requiredResponse(this.getReferences( - request.arguments, - /*simplifiedResult*/ - true - )); + ["references" /* References */]: request => { + return this.requiredResponse(this.getReferences(request.arguments, /*simplifiedResult*/ + true)); }, - ["references-full" /* ReferencesFull */]: (request) => { - return this.requiredResponse(this.getReferences( - request.arguments, - /*simplifiedResult*/ - false - )); + ["references-full" /* ReferencesFull */]: request => { + return this.requiredResponse(this.getReferences(request.arguments, /*simplifiedResult*/ + false)); }, - ["rename" /* Rename */]: (request) => { - return this.requiredResponse(this.getRenameLocations( - request.arguments, - /*simplifiedResult*/ - true - )); + ["rename" /* Rename */]: request => { + return this.requiredResponse(this.getRenameLocations(request.arguments, /*simplifiedResult*/ + true)); }, - ["renameLocations-full" /* RenameLocationsFull */]: (request) => { - return this.requiredResponse(this.getRenameLocations( - request.arguments, - /*simplifiedResult*/ - false - )); + ["renameLocations-full" /* RenameLocationsFull */]: request => { + return this.requiredResponse(this.getRenameLocations(request.arguments, /*simplifiedResult*/ + false)); }, - ["rename-full" /* RenameInfoFull */]: (request) => { + ["rename-full" /* RenameInfoFull */]: request => { return this.requiredResponse(this.getRenameInfo(request.arguments)); }, - ["open" /* Open */]: (request) => { - this.openClientFile( - toNormalizedPath(request.arguments.file), - request.arguments.fileContent, - convertScriptKindName(request.arguments.scriptKindName), - // TODO: GH#18217 - request.arguments.projectRootPath ? toNormalizedPath(request.arguments.projectRootPath) : void 0 - ); + ["open" /* Open */]: request => { + this.openClientFile(toNormalizedPath(request.arguments.file), request.arguments.fileContent, convertScriptKindName(request.arguments.scriptKindName), + // TODO: GH#18217 + request.arguments.projectRootPath ? toNormalizedPath(request.arguments.projectRootPath) : void 0); return this.notRequired(); }, - ["quickinfo" /* Quickinfo */]: (request) => { - return this.requiredResponse(this.getQuickInfoWorker( - request.arguments, - /*simplifiedResult*/ - true - )); + ["quickinfo" /* Quickinfo */]: request => { + return this.requiredResponse(this.getQuickInfoWorker(request.arguments, /*simplifiedResult*/ + true)); }, - ["quickinfo-full" /* QuickinfoFull */]: (request) => { - return this.requiredResponse(this.getQuickInfoWorker( - request.arguments, - /*simplifiedResult*/ - false - )); + ["quickinfo-full" /* QuickinfoFull */]: request => { + return this.requiredResponse(this.getQuickInfoWorker(request.arguments, /*simplifiedResult*/ + false)); }, - ["getOutliningSpans" /* GetOutliningSpans */]: (request) => { - return this.requiredResponse(this.getOutliningSpans( - request.arguments, - /*simplifiedResult*/ - true - )); + ["getOutliningSpans" /* GetOutliningSpans */]: request => { + return this.requiredResponse(this.getOutliningSpans(request.arguments, /*simplifiedResult*/ + true)); }, - ["outliningSpans" /* GetOutliningSpansFull */]: (request) => { - return this.requiredResponse(this.getOutliningSpans( - request.arguments, - /*simplifiedResult*/ - false - )); + ["outliningSpans" /* GetOutliningSpansFull */]: request => { + return this.requiredResponse(this.getOutliningSpans(request.arguments, /*simplifiedResult*/ + false)); }, - ["todoComments" /* TodoComments */]: (request) => { + ["todoComments" /* TodoComments */]: request => { return this.requiredResponse(this.getTodoComments(request.arguments)); }, - ["indentation" /* Indentation */]: (request) => { + ["indentation" /* Indentation */]: request => { return this.requiredResponse(this.getIndentation(request.arguments)); }, - ["nameOrDottedNameSpan" /* NameOrDottedNameSpan */]: (request) => { + ["nameOrDottedNameSpan" /* NameOrDottedNameSpan */]: request => { return this.requiredResponse(this.getNameOrDottedNameSpan(request.arguments)); }, - ["breakpointStatement" /* BreakpointStatement */]: (request) => { + ["breakpointStatement" /* BreakpointStatement */]: request => { return this.requiredResponse(this.getBreakpointStatement(request.arguments)); }, - ["braceCompletion" /* BraceCompletion */]: (request) => { + ["braceCompletion" /* BraceCompletion */]: request => { return this.requiredResponse(this.isValidBraceCompletion(request.arguments)); }, - ["docCommentTemplate" /* DocCommentTemplate */]: (request) => { + ["docCommentTemplate" /* DocCommentTemplate */]: request => { return this.requiredResponse(this.getDocCommentTemplate(request.arguments)); }, - ["getSpanOfEnclosingComment" /* GetSpanOfEnclosingComment */]: (request) => { + ["getSpanOfEnclosingComment" /* GetSpanOfEnclosingComment */]: request => { return this.requiredResponse(this.getSpanOfEnclosingComment(request.arguments)); }, - ["fileReferences" /* FileReferences */]: (request) => { - return this.requiredResponse(this.getFileReferences( - request.arguments, - /*simplifiedResult*/ - true - )); + ["fileReferences" /* FileReferences */]: request => { + return this.requiredResponse(this.getFileReferences(request.arguments, /*simplifiedResult*/ + true)); }, - ["fileReferences-full" /* FileReferencesFull */]: (request) => { - return this.requiredResponse(this.getFileReferences( - request.arguments, - /*simplifiedResult*/ - false - )); + ["fileReferences-full" /* FileReferencesFull */]: request => { + return this.requiredResponse(this.getFileReferences(request.arguments, /*simplifiedResult*/ + false)); }, - ["format" /* Format */]: (request) => { + ["format" /* Format */]: request => { return this.requiredResponse(this.getFormattingEditsForRange(request.arguments)); }, - ["formatonkey" /* Formatonkey */]: (request) => { + ["formatonkey" /* Formatonkey */]: request => { return this.requiredResponse(this.getFormattingEditsAfterKeystroke(request.arguments)); }, - ["format-full" /* FormatFull */]: (request) => { + ["format-full" /* FormatFull */]: request => { return this.requiredResponse(this.getFormattingEditsForDocumentFull(request.arguments)); }, - ["formatonkey-full" /* FormatonkeyFull */]: (request) => { + ["formatonkey-full" /* FormatonkeyFull */]: request => { return this.requiredResponse(this.getFormattingEditsAfterKeystrokeFull(request.arguments)); }, - ["formatRange-full" /* FormatRangeFull */]: (request) => { + ["formatRange-full" /* FormatRangeFull */]: request => { return this.requiredResponse(this.getFormattingEditsForRangeFull(request.arguments)); }, - ["completionInfo" /* CompletionInfo */]: (request) => { + ["completionInfo" /* CompletionInfo */]: request => { return this.requiredResponse(this.getCompletions(request.arguments, "completionInfo" /* CompletionInfo */)); }, - ["completions" /* Completions */]: (request) => { + + ["completions" /* Completions */]: request => { return this.requiredResponse(this.getCompletions(request.arguments, "completions" /* Completions */)); }, - ["completions-full" /* CompletionsFull */]: (request) => { + + ["completions-full" /* CompletionsFull */]: request => { return this.requiredResponse(this.getCompletions(request.arguments, "completions-full" /* CompletionsFull */)); }, - ["completionEntryDetails" /* CompletionDetails */]: (request) => { - return this.requiredResponse(this.getCompletionEntryDetails( - request.arguments, - /*fullResult*/ - false - )); + + ["completionEntryDetails" /* CompletionDetails */]: request => { + return this.requiredResponse(this.getCompletionEntryDetails(request.arguments, /*fullResult*/ + false)); }, - ["completionEntryDetails-full" /* CompletionDetailsFull */]: (request) => { - return this.requiredResponse(this.getCompletionEntryDetails( - request.arguments, - /*fullResult*/ - true - )); + ["completionEntryDetails-full" /* CompletionDetailsFull */]: request => { + return this.requiredResponse(this.getCompletionEntryDetails(request.arguments, /*fullResult*/ + true)); }, - ["compileOnSaveAffectedFileList" /* CompileOnSaveAffectedFileList */]: (request) => { + ["compileOnSaveAffectedFileList" /* CompileOnSaveAffectedFileList */]: request => { return this.requiredResponse(this.getCompileOnSaveAffectedFileList(request.arguments)); }, - ["compileOnSaveEmitFile" /* CompileOnSaveEmitFile */]: (request) => { + ["compileOnSaveEmitFile" /* CompileOnSaveEmitFile */]: request => { return this.requiredResponse(this.emitFile(request.arguments)); }, - ["signatureHelp" /* SignatureHelp */]: (request) => { - return this.requiredResponse(this.getSignatureHelpItems( - request.arguments, - /*simplifiedResult*/ - true - )); + ["signatureHelp" /* SignatureHelp */]: request => { + return this.requiredResponse(this.getSignatureHelpItems(request.arguments, /*simplifiedResult*/ + true)); }, - ["signatureHelp-full" /* SignatureHelpFull */]: (request) => { - return this.requiredResponse(this.getSignatureHelpItems( - request.arguments, - /*simplifiedResult*/ - false - )); + ["signatureHelp-full" /* SignatureHelpFull */]: request => { + return this.requiredResponse(this.getSignatureHelpItems(request.arguments, /*simplifiedResult*/ + false)); }, - ["compilerOptionsDiagnostics-full" /* CompilerOptionsDiagnosticsFull */]: (request) => { + ["compilerOptionsDiagnostics-full" /* CompilerOptionsDiagnosticsFull */]: request => { return this.requiredResponse(this.getCompilerOptionsDiagnostics(request.arguments)); }, - ["encodedSyntacticClassifications-full" /* EncodedSyntacticClassificationsFull */]: (request) => { + ["encodedSyntacticClassifications-full" /* EncodedSyntacticClassificationsFull */]: request => { return this.requiredResponse(this.getEncodedSyntacticClassifications(request.arguments)); }, - ["encodedSemanticClassifications-full" /* EncodedSemanticClassificationsFull */]: (request) => { + ["encodedSemanticClassifications-full" /* EncodedSemanticClassificationsFull */]: request => { return this.requiredResponse(this.getEncodedSemanticClassifications(request.arguments)); }, ["cleanup" /* Cleanup */]: () => { this.cleanup(); - return this.requiredResponse( - /*response*/ - true - ); + return this.requiredResponse( /*response*/ + true); }, - ["semanticDiagnosticsSync" /* SemanticDiagnosticsSync */]: (request) => { + ["semanticDiagnosticsSync" /* SemanticDiagnosticsSync */]: request => { return this.requiredResponse(this.getSemanticDiagnosticsSync(request.arguments)); }, - ["syntacticDiagnosticsSync" /* SyntacticDiagnosticsSync */]: (request) => { + ["syntacticDiagnosticsSync" /* SyntacticDiagnosticsSync */]: request => { return this.requiredResponse(this.getSyntacticDiagnosticsSync(request.arguments)); }, - ["suggestionDiagnosticsSync" /* SuggestionDiagnosticsSync */]: (request) => { + ["suggestionDiagnosticsSync" /* SuggestionDiagnosticsSync */]: request => { return this.requiredResponse(this.getSuggestionDiagnosticsSync(request.arguments)); }, - ["geterr" /* Geterr */]: (request) => { - this.errorCheck.startNew((next) => this.getDiagnostics(next, request.arguments.delay, request.arguments.files)); + ["geterr" /* Geterr */]: request => { + this.errorCheck.startNew(next => this.getDiagnostics(next, request.arguments.delay, request.arguments.files)); return this.notRequired(); }, - ["geterrForProject" /* GeterrForProject */]: (request) => { - this.errorCheck.startNew((next) => this.getDiagnosticsForProject(next, request.arguments.delay, request.arguments.file)); + ["geterrForProject" /* GeterrForProject */]: request => { + this.errorCheck.startNew(next => this.getDiagnosticsForProject(next, request.arguments.delay, request.arguments.file)); return this.notRequired(); }, - ["change" /* Change */]: (request) => { + ["change" /* Change */]: request => { this.change(request.arguments); return this.notRequired(); }, - ["configure" /* Configure */]: (request) => { + ["configure" /* Configure */]: request => { this.projectService.setHostConfiguration(request.arguments); - this.doOutput( - /*info*/ - void 0, - "configure" /* Configure */, - request.seq, - /*success*/ - true - ); + this.doOutput( /*info*/ + void 0, "configure" /* Configure */, request.seq, /*success*/ + true); return this.notRequired(); }, - ["reload" /* Reload */]: (request) => { + ["reload" /* Reload */]: request => { this.reload(request.arguments, request.seq); - return this.requiredResponse({ reloadFinished: true }); + return this.requiredResponse({ + reloadFinished: true + }); }, - ["saveto" /* Saveto */]: (request) => { + ["saveto" /* Saveto */]: request => { const savetoArgs = request.arguments; this.saveToTmp(savetoArgs.file, savetoArgs.tmpfile); return this.notRequired(); }, - ["close" /* Close */]: (request) => { + ["close" /* Close */]: request => { const closeArgs = request.arguments; this.closeClientFile(closeArgs.file); return this.notRequired(); }, - ["navto" /* Navto */]: (request) => { - return this.requiredResponse(this.getNavigateToItems( - request.arguments, - /*simplifiedResult*/ - true - )); + ["navto" /* Navto */]: request => { + return this.requiredResponse(this.getNavigateToItems(request.arguments, /*simplifiedResult*/ + true)); }, - ["navto-full" /* NavtoFull */]: (request) => { - return this.requiredResponse(this.getNavigateToItems( - request.arguments, - /*simplifiedResult*/ - false - )); + ["navto-full" /* NavtoFull */]: request => { + return this.requiredResponse(this.getNavigateToItems(request.arguments, /*simplifiedResult*/ + false)); }, - ["brace" /* Brace */]: (request) => { - return this.requiredResponse(this.getBraceMatching( - request.arguments, - /*simplifiedResult*/ - true - )); + ["brace" /* Brace */]: request => { + return this.requiredResponse(this.getBraceMatching(request.arguments, /*simplifiedResult*/ + true)); }, - ["brace-full" /* BraceFull */]: (request) => { - return this.requiredResponse(this.getBraceMatching( - request.arguments, - /*simplifiedResult*/ - false - )); + ["brace-full" /* BraceFull */]: request => { + return this.requiredResponse(this.getBraceMatching(request.arguments, /*simplifiedResult*/ + false)); }, - ["navbar" /* NavBar */]: (request) => { - return this.requiredResponse(this.getNavigationBarItems( - request.arguments, - /*simplifiedResult*/ - true - )); + ["navbar" /* NavBar */]: request => { + return this.requiredResponse(this.getNavigationBarItems(request.arguments, /*simplifiedResult*/ + true)); }, - ["navbar-full" /* NavBarFull */]: (request) => { - return this.requiredResponse(this.getNavigationBarItems( - request.arguments, - /*simplifiedResult*/ - false - )); + ["navbar-full" /* NavBarFull */]: request => { + return this.requiredResponse(this.getNavigationBarItems(request.arguments, /*simplifiedResult*/ + false)); }, - ["navtree" /* NavTree */]: (request) => { - return this.requiredResponse(this.getNavigationTree( - request.arguments, - /*simplifiedResult*/ - true - )); + ["navtree" /* NavTree */]: request => { + return this.requiredResponse(this.getNavigationTree(request.arguments, /*simplifiedResult*/ + true)); }, - ["navtree-full" /* NavTreeFull */]: (request) => { - return this.requiredResponse(this.getNavigationTree( - request.arguments, - /*simplifiedResult*/ - false - )); + ["navtree-full" /* NavTreeFull */]: request => { + return this.requiredResponse(this.getNavigationTree(request.arguments, /*simplifiedResult*/ + false)); }, - ["documentHighlights" /* DocumentHighlights */]: (request) => { - return this.requiredResponse(this.getDocumentHighlights( - request.arguments, - /*simplifiedResult*/ - true - )); + ["documentHighlights" /* DocumentHighlights */]: request => { + return this.requiredResponse(this.getDocumentHighlights(request.arguments, /*simplifiedResult*/ + true)); }, - ["documentHighlights-full" /* DocumentHighlightsFull */]: (request) => { - return this.requiredResponse(this.getDocumentHighlights( - request.arguments, - /*simplifiedResult*/ - false - )); + ["documentHighlights-full" /* DocumentHighlightsFull */]: request => { + return this.requiredResponse(this.getDocumentHighlights(request.arguments, /*simplifiedResult*/ + false)); }, - ["compilerOptionsForInferredProjects" /* CompilerOptionsForInferredProjects */]: (request) => { + ["compilerOptionsForInferredProjects" /* CompilerOptionsForInferredProjects */]: request => { this.setCompilerOptionsForInferredProjects(request.arguments); - return this.requiredResponse( - /*response*/ - true - ); + return this.requiredResponse( /*response*/ + true); }, - ["projectInfo" /* ProjectInfo */]: (request) => { + ["projectInfo" /* ProjectInfo */]: request => { return this.requiredResponse(this.getProjectInfo(request.arguments)); }, ["reloadProjects" /* ReloadProjects */]: () => { this.projectService.reloadProjects(); return this.notRequired(); }, - ["jsxClosingTag" /* JsxClosingTag */]: (request) => { + ["jsxClosingTag" /* JsxClosingTag */]: request => { return this.requiredResponse(this.getJsxClosingTag(request.arguments)); }, - ["linkedEditingRange" /* LinkedEditingRange */]: (request) => { + ["linkedEditingRange" /* LinkedEditingRange */]: request => { return this.requiredResponse(this.getLinkedEditingRange(request.arguments)); }, - ["getCodeFixes" /* GetCodeFixes */]: (request) => { - return this.requiredResponse(this.getCodeFixes( - request.arguments, - /*simplifiedResult*/ - true - )); + ["getCodeFixes" /* GetCodeFixes */]: request => { + return this.requiredResponse(this.getCodeFixes(request.arguments, /*simplifiedResult*/ + true)); }, - ["getCodeFixes-full" /* GetCodeFixesFull */]: (request) => { - return this.requiredResponse(this.getCodeFixes( - request.arguments, - /*simplifiedResult*/ - false - )); + ["getCodeFixes-full" /* GetCodeFixesFull */]: request => { + return this.requiredResponse(this.getCodeFixes(request.arguments, /*simplifiedResult*/ + false)); }, - ["getCombinedCodeFix" /* GetCombinedCodeFix */]: (request) => { - return this.requiredResponse(this.getCombinedCodeFix( - request.arguments, - /*simplifiedResult*/ - true - )); + ["getCombinedCodeFix" /* GetCombinedCodeFix */]: request => { + return this.requiredResponse(this.getCombinedCodeFix(request.arguments, /*simplifiedResult*/ + true)); }, - ["getCombinedCodeFix-full" /* GetCombinedCodeFixFull */]: (request) => { - return this.requiredResponse(this.getCombinedCodeFix( - request.arguments, - /*simplifiedResult*/ - false - )); + ["getCombinedCodeFix-full" /* GetCombinedCodeFixFull */]: request => { + return this.requiredResponse(this.getCombinedCodeFix(request.arguments, /*simplifiedResult*/ + false)); }, - ["applyCodeActionCommand" /* ApplyCodeActionCommand */]: (request) => { + ["applyCodeActionCommand" /* ApplyCodeActionCommand */]: request => { return this.requiredResponse(this.applyCodeActionCommand(request.arguments)); }, - ["getSupportedCodeFixes" /* GetSupportedCodeFixes */]: (request) => { + ["getSupportedCodeFixes" /* GetSupportedCodeFixes */]: request => { return this.requiredResponse(this.getSupportedCodeFixes(request.arguments)); }, - ["getApplicableRefactors" /* GetApplicableRefactors */]: (request) => { + ["getApplicableRefactors" /* GetApplicableRefactors */]: request => { return this.requiredResponse(this.getApplicableRefactors(request.arguments)); }, - ["getEditsForRefactor" /* GetEditsForRefactor */]: (request) => { - return this.requiredResponse(this.getEditsForRefactor( - request.arguments, - /*simplifiedResult*/ - true - )); + ["getEditsForRefactor" /* GetEditsForRefactor */]: request => { + return this.requiredResponse(this.getEditsForRefactor(request.arguments, /*simplifiedResult*/ + true)); }, - ["getMoveToRefactoringFileSuggestions" /* GetMoveToRefactoringFileSuggestions */]: (request) => { + ["getMoveToRefactoringFileSuggestions" /* GetMoveToRefactoringFileSuggestions */]: request => { return this.requiredResponse(this.getMoveToRefactoringFileSuggestions(request.arguments)); }, - ["getEditsForRefactor-full" /* GetEditsForRefactorFull */]: (request) => { - return this.requiredResponse(this.getEditsForRefactor( - request.arguments, - /*simplifiedResult*/ - false - )); + ["getEditsForRefactor-full" /* GetEditsForRefactorFull */]: request => { + return this.requiredResponse(this.getEditsForRefactor(request.arguments, /*simplifiedResult*/ + false)); }, - ["organizeImports" /* OrganizeImports */]: (request) => { - return this.requiredResponse(this.organizeImports( - request.arguments, - /*simplifiedResult*/ - true - )); + ["organizeImports" /* OrganizeImports */]: request => { + return this.requiredResponse(this.organizeImports(request.arguments, /*simplifiedResult*/ + true)); }, - ["organizeImports-full" /* OrganizeImportsFull */]: (request) => { - return this.requiredResponse(this.organizeImports( - request.arguments, - /*simplifiedResult*/ - false - )); + ["organizeImports-full" /* OrganizeImportsFull */]: request => { + return this.requiredResponse(this.organizeImports(request.arguments, /*simplifiedResult*/ + false)); }, - ["getEditsForFileRename" /* GetEditsForFileRename */]: (request) => { - return this.requiredResponse(this.getEditsForFileRename( - request.arguments, - /*simplifiedResult*/ - true - )); + ["getEditsForFileRename" /* GetEditsForFileRename */]: request => { + return this.requiredResponse(this.getEditsForFileRename(request.arguments, /*simplifiedResult*/ + true)); }, - ["getEditsForFileRename-full" /* GetEditsForFileRenameFull */]: (request) => { - return this.requiredResponse(this.getEditsForFileRename( - request.arguments, - /*simplifiedResult*/ - false - )); + ["getEditsForFileRename-full" /* GetEditsForFileRenameFull */]: request => { + return this.requiredResponse(this.getEditsForFileRename(request.arguments, /*simplifiedResult*/ + false)); }, - ["configurePlugin" /* ConfigurePlugin */]: (request) => { + ["configurePlugin" /* ConfigurePlugin */]: request => { this.configurePlugin(request.arguments); - this.doOutput( - /*info*/ - void 0, - "configurePlugin" /* ConfigurePlugin */, - request.seq, - /*success*/ - true - ); + this.doOutput( /*info*/ + void 0, "configurePlugin" /* ConfigurePlugin */, request.seq, /*success*/ + true); return this.notRequired(); }, - ["selectionRange" /* SelectionRange */]: (request) => { - return this.requiredResponse(this.getSmartSelectionRange( - request.arguments, - /*simplifiedResult*/ - true - )); + ["selectionRange" /* SelectionRange */]: request => { + return this.requiredResponse(this.getSmartSelectionRange(request.arguments, /*simplifiedResult*/ + true)); }, - ["selectionRange-full" /* SelectionRangeFull */]: (request) => { - return this.requiredResponse(this.getSmartSelectionRange( - request.arguments, - /*simplifiedResult*/ - false - )); + ["selectionRange-full" /* SelectionRangeFull */]: request => { + return this.requiredResponse(this.getSmartSelectionRange(request.arguments, /*simplifiedResult*/ + false)); }, - ["prepareCallHierarchy" /* PrepareCallHierarchy */]: (request) => { + ["prepareCallHierarchy" /* PrepareCallHierarchy */]: request => { return this.requiredResponse(this.prepareCallHierarchy(request.arguments)); }, - ["provideCallHierarchyIncomingCalls" /* ProvideCallHierarchyIncomingCalls */]: (request) => { + ["provideCallHierarchyIncomingCalls" /* ProvideCallHierarchyIncomingCalls */]: request => { return this.requiredResponse(this.provideCallHierarchyIncomingCalls(request.arguments)); }, - ["provideCallHierarchyOutgoingCalls" /* ProvideCallHierarchyOutgoingCalls */]: (request) => { + ["provideCallHierarchyOutgoingCalls" /* ProvideCallHierarchyOutgoingCalls */]: request => { return this.requiredResponse(this.provideCallHierarchyOutgoingCalls(request.arguments)); }, - ["toggleLineComment" /* ToggleLineComment */]: (request) => { - return this.requiredResponse(this.toggleLineComment( - request.arguments, - /*simplifiedResult*/ - true - )); + ["toggleLineComment" /* ToggleLineComment */]: request => { + return this.requiredResponse(this.toggleLineComment(request.arguments, /*simplifiedResult*/ + true)); }, - ["toggleLineComment-full" /* ToggleLineCommentFull */]: (request) => { - return this.requiredResponse(this.toggleLineComment( - request.arguments, - /*simplifiedResult*/ - false - )); + ["toggleLineComment-full" /* ToggleLineCommentFull */]: request => { + return this.requiredResponse(this.toggleLineComment(request.arguments, /*simplifiedResult*/ + false)); }, - ["toggleMultilineComment" /* ToggleMultilineComment */]: (request) => { - return this.requiredResponse(this.toggleMultilineComment( - request.arguments, - /*simplifiedResult*/ - true - )); + ["toggleMultilineComment" /* ToggleMultilineComment */]: request => { + return this.requiredResponse(this.toggleMultilineComment(request.arguments, /*simplifiedResult*/ + true)); }, - ["toggleMultilineComment-full" /* ToggleMultilineCommentFull */]: (request) => { - return this.requiredResponse(this.toggleMultilineComment( - request.arguments, - /*simplifiedResult*/ - false - )); + ["toggleMultilineComment-full" /* ToggleMultilineCommentFull */]: request => { + return this.requiredResponse(this.toggleMultilineComment(request.arguments, /*simplifiedResult*/ + false)); }, - ["commentSelection" /* CommentSelection */]: (request) => { - return this.requiredResponse(this.commentSelection( - request.arguments, - /*simplifiedResult*/ - true - )); + ["commentSelection" /* CommentSelection */]: request => { + return this.requiredResponse(this.commentSelection(request.arguments, /*simplifiedResult*/ + true)); }, - ["commentSelection-full" /* CommentSelectionFull */]: (request) => { - return this.requiredResponse(this.commentSelection( - request.arguments, - /*simplifiedResult*/ - false - )); + ["commentSelection-full" /* CommentSelectionFull */]: request => { + return this.requiredResponse(this.commentSelection(request.arguments, /*simplifiedResult*/ + false)); }, - ["uncommentSelection" /* UncommentSelection */]: (request) => { - return this.requiredResponse(this.uncommentSelection( - request.arguments, - /*simplifiedResult*/ - true - )); + ["uncommentSelection" /* UncommentSelection */]: request => { + return this.requiredResponse(this.uncommentSelection(request.arguments, /*simplifiedResult*/ + true)); }, - ["uncommentSelection-full" /* UncommentSelectionFull */]: (request) => { - return this.requiredResponse(this.uncommentSelection( - request.arguments, - /*simplifiedResult*/ - false - )); + ["uncommentSelection-full" /* UncommentSelectionFull */]: request => { + return this.requiredResponse(this.uncommentSelection(request.arguments, /*simplifiedResult*/ + false)); }, - ["provideInlayHints" /* ProvideInlayHints */]: (request) => { + ["provideInlayHints" /* ProvideInlayHints */]: request => { return this.requiredResponse(this.provideInlayHints(request.arguments)); } })); @@ -180768,14 +164354,16 @@ ${json}${newLine}`; this.canUseEvents = opts.canUseEvents; this.suppressDiagnosticEvents = opts.suppressDiagnosticEvents; this.noGetErrOnBackgroundUpdate = opts.noGetErrOnBackgroundUpdate; - const { throttleWaitMilliseconds } = opts; - this.eventHandler = this.canUseEvents ? opts.eventHandler || ((event) => this.defaultEventHandler(event)) : void 0; + const { + throttleWaitMilliseconds + } = opts; + this.eventHandler = this.canUseEvents ? opts.eventHandler || (event => this.defaultEventHandler(event)) : void 0; const multistepOperationHost = { executeWithRequestId: (requestId, action) => this.executeWithRequestId(requestId, action), getCurrentRequestId: () => this.currentRequestId, getServerHost: () => this.host, logError: (err, cmd) => this.logError(err, cmd), - sendRequestCompletedEvent: (requestId) => this.sendRequestCompletedEvent(requestId), + sendRequestCompletedEvent: requestId => this.sendRequestCompletedEvent(requestId), isCancellationRequested: () => this.cancellationToken.isCancellationRequested() }; this.errorCheck = new MultistepOperation(multistepOperationHost); @@ -180800,41 +164388,36 @@ ${json}${newLine}`; }; this.projectService = new ProjectService3(settings); this.projectService.setPerformanceEventHandler(this.performanceEventHandler.bind(this)); - this.gcTimer = new GcTimer( - this.host, - /*delay*/ - 7e3, - this.logger - ); + this.gcTimer = new GcTimer(this.host, /*delay*/ + 7e3, this.logger); switch (this.projectService.serverMode) { case 0 /* Semantic */: break; case 1 /* PartialSemantic */: - invalidPartialSemanticModeCommands.forEach( - (commandName) => this.handlers.set(commandName, (request) => { - throw new Error(`Request: ${request.command} not allowed in LanguageServiceMode.PartialSemantic`); - }) - ); + invalidPartialSemanticModeCommands.forEach(commandName => this.handlers.set(commandName, request => { + throw new Error(`Request: ${request.command} not allowed in LanguageServiceMode.PartialSemantic`); + })); break; case 2 /* Syntactic */: - invalidSyntacticModeCommands.forEach( - (commandName) => this.handlers.set(commandName, (request) => { - throw new Error(`Request: ${request.command} not allowed in LanguageServiceMode.Syntactic`); - }) - ); + invalidSyntacticModeCommands.forEach(commandName => this.handlers.set(commandName, request => { + throw new Error(`Request: ${request.command} not allowed in LanguageServiceMode.Syntactic`); + })); break; default: Debug.assertNever(this.projectService.serverMode); } } sendRequestCompletedEvent(requestId) { - this.event({ request_seq: requestId }, "requestCompleted"); + this.event({ + request_seq: requestId + }, "requestCompleted"); } addPerformanceData(key, value) { + var _this$performanceData; if (!this.performanceData) { this.performanceData = {}; } - this.performanceData[key] = (this.performanceData[key] ?? 0) + value; + this.performanceData[key] = ((_this$performanceData = this.performanceData[key]) !== null && _this$performanceData !== void 0 ? _this$performanceData : 0) + value; } performanceEventHandler(event) { switch (event.kind) { @@ -180872,41 +164455,35 @@ ${json}${newLine}`; this.event({ triggerFile: event.data.triggerFile, configFile: event.data.configFileName, - diagnostics: map(event.data.diagnostics, (diagnostic) => formatDiagnosticToProtocol( - diagnostic, - /*includeFileName*/ - true - )) + diagnostics: map(event.data.diagnostics, diagnostic => formatDiagnosticToProtocol(diagnostic, /*includeFileName*/ + true)) }, event.eventName); break; - case ProjectLanguageServiceStateEvent: { - this.event({ - projectName: event.data.project.getProjectName(), - languageServiceEnabled: event.data.languageServiceEnabled - }, event.eventName); - break; - } - case ProjectInfoTelemetryEvent: { - const eventName = "telemetry"; - this.event({ - telemetryEventName: event.eventName, - payload: event.data - }, eventName); - break; - } + case ProjectLanguageServiceStateEvent: + { + this.event({ + projectName: event.data.project.getProjectName(), + languageServiceEnabled: event.data.languageServiceEnabled + }, event.eventName); + break; + } + case ProjectInfoTelemetryEvent: + { + const eventName = "telemetry"; + this.event({ + telemetryEventName: event.eventName, + payload: event.data + }, eventName); + break; + } } } projectsUpdatedInBackgroundEvent(openFiles) { this.projectService.logger.info(`got projects updated in background, updating diagnostics for ${openFiles}`); if (openFiles.length) { if (!this.suppressDiagnosticEvents && !this.noGetErrOnBackgroundUpdate) { - this.errorCheck.startNew((next) => this.updateErrorCheck( - next, - openFiles, - 100, - /*requireOpen*/ - true - )); + this.errorCheck.startNew(next => this.updateErrorCheck(next, openFiles, 100, /*requireOpen*/ + true)); } this.event({ openFiles @@ -180927,7 +164504,10 @@ ${json}${newLine}`; if (this.logger.hasLevel(3 /* verbose */)) { if (fileRequest) { try { - const { file, project } = this.getFileAndProject(fileRequest); + const { + file, + project + } = this.getFileAndProject(fileRequest); const scriptInfo = project.getScriptInfoForNormalizedPath(file); if (scriptInfo) { const text = getSnapshotText(scriptInfo.getSnapshot()); @@ -180936,8 +164516,7 @@ ${json}${newLine}`; File text of ${fileRequest.file}:${indent2(text)} `; } - } catch { - } + } catch {} } if (err.ProgramFiles) { msg += ` @@ -180949,14 +164528,12 @@ Program files: ${JSON.stringify(err.ProgramFiles)} Projects:: `; let counter = 0; - const addProjectInfo = (project) => { + const addProjectInfo = project => { msg += ` Project '${project.projectName}' (${ProjectKind[project.projectKind]}) ${counter} `; - msg += project.filesToString( - /*writeProjectFileNames*/ - true - ); + msg += project.filesToString( /*writeProjectFileNames*/ + true); msg += "\n-----------------------------------------------\n"; counter++; }; @@ -180967,6 +164544,7 @@ Project '${project.projectName}' (${ProjectKind[project.projectKind]}) ${counter } this.logger.msg(msg, "Err" /* Err */); } + send(msg) { if (msg.type === "event" && !this.canUseEvents) { if (this.logger.hasLevel(3 /* verbose */)) { @@ -181003,7 +164581,10 @@ Project '${project.projectName}' (${ProjectKind[project.projectKind]}) ${counter delete info.metadata; } else if (typeof info === "object") { if (info.metadata) { - const { metadata: infoMetadata, ...body } = info; + const { + metadata: infoMetadata, + ...body + } = info; res.body = body; metadata = infoMetadata; } else { @@ -181012,8 +164593,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); } @@ -181024,26 +164604,38 @@ Project '${project.projectName}' (${ProjectKind[project.projectKind]}) ${counter } semanticCheck(file, project) { var _a, _b; - (_a = tracing) == null ? void 0 : _a.push(tracing.Phase.Session, "semanticCheck", { file, configFilePath: project.canonicalConfigFilePath }); - const diags = isDeclarationFileInJSOnlyNonConfiguredProject(project, file) ? emptyArray2 : project.getLanguageService().getSemanticDiagnostics(file).filter((d) => !!d.file); + (_a = tracing) == null ? void 0 : _a.push(tracing.Phase.Session, "semanticCheck", { + file, + configFilePath: project.canonicalConfigFilePath + }); + const diags = isDeclarationFileInJSOnlyNonConfiguredProject(project, file) ? emptyArray2 : project.getLanguageService().getSemanticDiagnostics(file).filter(d => !!d.file); this.sendDiagnosticsEvent(file, project, diags, "semanticDiag"); (_b = tracing) == null ? void 0 : _b.pop(); } syntacticCheck(file, project) { var _a, _b; - (_a = tracing) == null ? void 0 : _a.push(tracing.Phase.Session, "syntacticCheck", { file, configFilePath: project.canonicalConfigFilePath }); + (_a = tracing) == null ? void 0 : _a.push(tracing.Phase.Session, "syntacticCheck", { + file, + configFilePath: project.canonicalConfigFilePath + }); this.sendDiagnosticsEvent(file, project, project.getLanguageService().getSyntacticDiagnostics(file), "syntaxDiag"); (_b = tracing) == null ? void 0 : _b.pop(); } suggestionCheck(file, project) { var _a, _b; - (_a = tracing) == null ? void 0 : _a.push(tracing.Phase.Session, "suggestionCheck", { file, configFilePath: project.canonicalConfigFilePath }); + (_a = tracing) == null ? void 0 : _a.push(tracing.Phase.Session, "suggestionCheck", { + file, + configFilePath: project.canonicalConfigFilePath + }); this.sendDiagnosticsEvent(file, project, project.getLanguageService().getSuggestionDiagnostics(file), "suggestionDiag"); (_b = tracing) == null ? void 0 : _b.pop(); } sendDiagnosticsEvent(file, project, diagnostics, kind) { try { - this.event({ file, diagnostics: diagnostics.map((diag2) => formatDiag(file, project, diag2)) }, kind); + this.event({ + file, + diagnostics: diagnostics.map(diag2 => formatDiag(file, project, diag2)) + }, kind); } catch (err) { this.logError(err, kind); } @@ -181072,7 +164664,10 @@ Project '${project.projectName}' (${ProjectKind[project.projectKind]}) ${counter return; } } - const { fileName, project } = item; + const { + fileName, + project + } = item; updateProjectIfDirty(project); if (!project.containsFile(fileName, requireOpen)) { return; @@ -181110,10 +164705,8 @@ Project '${project.projectName}' (${ProjectKind[project.projectKind]}) ${counter } this.logger.info(`cleaning ${caption}`); for (const p of projects) { - p.getLanguageService( - /*ensureSynchronized*/ - false - ).cleanupSemanticCache(); + p.getLanguageService( /*ensureSynchronized*/ + false).cleanupSemanticCache(); p.cleanupProgram(); } } @@ -181127,11 +164720,17 @@ Project '${project.projectName}' (${ProjectKind[project.projectKind]}) ${counter } } getEncodedSyntacticClassifications(args) { - const { file, languageService } = this.getFileAndLanguageServiceForSyntacticOperation(args); + const { + file, + languageService + } = this.getFileAndLanguageServiceForSyntacticOperation(args); return languageService.getEncodedSyntacticClassifications(file, args); } getEncodedSemanticClassifications(args) { - const { file, project } = this.getFileAndProject(args); + const { + file, + project + } = this.getFileAndProject(args); const format = args.format === "2020" ? "2020" /* TwentyTwenty */ : "original" /* Original */; return project.getLanguageService().getEncodedSemanticClassifications(file, args, format); } @@ -181149,21 +164748,12 @@ Project '${project.projectName}' (${ProjectKind[project.projectKind]}) ${counter getConfigFileDiagnostics(configFile, project, includeLinePosition) { const projectErrors = project.getAllProjectErrors(); const optionsErrors = project.getLanguageService().getCompilerOptionsDiagnostics(); - const diagnosticsForConfigFile = filter( - concatenate(projectErrors, optionsErrors), - (diagnostic) => !!diagnostic.file && diagnostic.file.fileName === configFile - ); - return includeLinePosition ? this.convertToDiagnosticsWithLinePositionFromDiagnosticFile(diagnosticsForConfigFile) : map( - diagnosticsForConfigFile, - (diagnostic) => formatDiagnosticToProtocol( - diagnostic, - /*includeFileName*/ - false - ) - ); + const diagnosticsForConfigFile = filter(concatenate(projectErrors, optionsErrors), diagnostic => !!diagnostic.file && diagnostic.file.fileName === configFile); + return includeLinePosition ? this.convertToDiagnosticsWithLinePositionFromDiagnosticFile(diagnosticsForConfigFile) : map(diagnosticsForConfigFile, diagnostic => formatDiagnosticToProtocol(diagnostic, /*includeFileName*/ + false)); } convertToDiagnosticsWithLinePositionFromDiagnosticFile(diagnostics) { - return diagnostics.map((d) => ({ + return diagnostics.map(d => ({ message: flattenDiagnosticMessageText(d.messageText, this.host.newLine), start: d.start, // TODO: GH#18217 @@ -181183,50 +164773,48 @@ Project '${project.projectName}' (${ProjectKind[project.projectKind]}) ${counter } getCompilerOptionsDiagnostics(args) { const project = this.getProject(args.projectFileName); - return this.convertToDiagnosticsWithLinePosition( - filter( - project.getLanguageService().getCompilerOptionsDiagnostics(), - (diagnostic) => !diagnostic.file - ), - /*scriptInfo*/ - void 0 - ); + return this.convertToDiagnosticsWithLinePosition(filter(project.getLanguageService().getCompilerOptionsDiagnostics(), diagnostic => !diagnostic.file), /*scriptInfo*/ + void 0); } convertToDiagnosticsWithLinePosition(diagnostics, scriptInfo) { - return diagnostics.map( - (d) => ({ - message: flattenDiagnosticMessageText(d.messageText, this.host.newLine), - start: d.start, - length: d.length, - category: diagnosticCategoryName(d), - code: d.code, - source: d.source, - startLocation: scriptInfo && scriptInfo.positionToLineOffset(d.start), - // TODO: GH#18217 - endLocation: scriptInfo && scriptInfo.positionToLineOffset(d.start + d.length), - reportsUnnecessary: d.reportsUnnecessary, - reportsDeprecated: d.reportsDeprecated, - relatedInformation: map(d.relatedInformation, formatRelatedInformation) - }) - ); + return diagnostics.map(d => ({ + message: flattenDiagnosticMessageText(d.messageText, this.host.newLine), + start: d.start, + length: d.length, + category: diagnosticCategoryName(d), + code: d.code, + source: d.source, + startLocation: scriptInfo && scriptInfo.positionToLineOffset(d.start), + // TODO: GH#18217 + endLocation: scriptInfo && scriptInfo.positionToLineOffset(d.start + d.length), + reportsUnnecessary: d.reportsUnnecessary, + reportsDeprecated: d.reportsDeprecated, + relatedInformation: map(d.relatedInformation, formatRelatedInformation) + })); } getDiagnosticsWorker(args, isSemantic, selector, includeLinePosition) { - const { project, file } = this.getFileAndProject(args); + const { + project, + file + } = this.getFileAndProject(args); if (isSemantic && isDeclarationFileInJSOnlyNonConfiguredProject(project, file)) { return emptyArray2; } const scriptInfo = project.getScriptInfoForNormalizedPath(file); const diagnostics = selector(project, file); - return includeLinePosition ? this.convertToDiagnosticsWithLinePosition(diagnostics, scriptInfo) : diagnostics.map((d) => formatDiag(file, project, d)); + return includeLinePosition ? this.convertToDiagnosticsWithLinePosition(diagnostics, scriptInfo) : diagnostics.map(d => formatDiag(file, project, d)); } getDefinition(args, simplifiedResult) { - const { file, project } = this.getFileAndProject(args); + const { + file, + project + } = this.getFileAndProject(args); const position = this.getPositionInFile(args, file); const definitions = this.mapDefinitionInfoLocations(project.getLanguageService().getDefinitionAtPosition(file, position) || emptyArray2, project); return simplifiedResult ? this.mapDefinitionInfo(definitions, project) : definitions.map(_Session.mapToOriginalLocation); } mapDefinitionInfoLocations(definitions, project) { - return definitions.map((info) => { + return definitions.map(info => { const newDocumentSpan = getMappedDocumentSpanForProject(info, project); return !newDocumentSpan ? info : { ...newDocumentSpan, @@ -181235,12 +164823,17 @@ Project '${project.projectName}' (${ProjectKind[project.projectKind]}) ${counter kind: info.kind, name: info.name, failedAliasResolution: info.failedAliasResolution, - ...info.unverified && { unverified: info.unverified } + ...(info.unverified && { + unverified: info.unverified + }) }; }); } getDefinitionAndBoundSpan(args, simplifiedResult) { - const { file, project } = this.getFileAndProject(args); + const { + file, + project + } = this.getFileAndProject(args); const position = this.getPositionInFile(args, file); const scriptInfo = Debug.checkDefined(project.getScriptInfo(file)); const unmappedDefinitionAndBoundSpan = project.getLanguageService().getDefinitionAndBoundSpan(file, position); @@ -181251,8 +164844,11 @@ Project '${project.projectName}' (${ProjectKind[project.projectKind]}) ${counter // TODO: GH#18217 }; } + const definitions = this.mapDefinitionInfoLocations(unmappedDefinitionAndBoundSpan.definitions, project); - const { textSpan } = unmappedDefinitionAndBoundSpan; + const { + textSpan + } = unmappedDefinitionAndBoundSpan; if (simplifiedResult) { return { definitions: this.mapDefinitionInfo(definitions, project), @@ -181266,24 +164862,22 @@ Project '${project.projectName}' (${ProjectKind[project.projectKind]}) ${counter } findSourceDefinition(args) { var _a; - const { file, project } = this.getFileAndProject(args); + const { + file, + project + } = this.getFileAndProject(args); const position = this.getPositionInFile(args, file); const unmappedDefinitions = project.getLanguageService().getDefinitionAtPosition(file, position); let definitions = this.mapDefinitionInfoLocations(unmappedDefinitions || emptyArray2, project).slice(); - const needsJsResolution = this.projectService.serverMode === 0 /* Semantic */ && (!some(definitions, (d) => toNormalizedPath(d.fileName) !== file && !d.isAmbient) || some(definitions, (d) => !!d.failedAliasResolution)); + const needsJsResolution = this.projectService.serverMode === 0 /* Semantic */ && (!some(definitions, d => toNormalizedPath(d.fileName) !== file && !d.isAmbient) || some(definitions, d => !!d.failedAliasResolution)); if (needsJsResolution) { - const definitionSet = createSet((d) => d.textSpan.start, documentSpansEqual); - definitions == null ? void 0 : definitions.forEach((d) => definitionSet.add(d)); + const definitionSet = createSet(d => d.textSpan.start, documentSpansEqual); + definitions == null ? void 0 : definitions.forEach(d => definitionSet.add(d)); const noDtsProject = project.getNoDtsResolutionProject(file); const ls = noDtsProject.getLanguageService(); - const jsDefinitions = (_a = ls.getDefinitionAtPosition( - file, - position, - /*searchOtherFilesOnly*/ - true, - /*stopAtAlias*/ - false - )) == null ? void 0 : _a.filter((d) => toNormalizedPath(d.fileName) !== file); + const jsDefinitions = (_a = ls.getDefinitionAtPosition(file, position, /*searchOtherFilesOnly*/ + true, /*stopAtAlias*/ + false)) == null ? void 0 : _a.filter(d => toNormalizedPath(d.fileName) !== file); if (some(jsDefinitions)) { for (const jsDefinition of jsDefinitions) { if (jsDefinition.unverified) { @@ -181298,18 +164892,12 @@ Project '${project.projectName}' (${ProjectKind[project.projectKind]}) ${counter definitionSet.add(jsDefinition); } } else { - const ambientCandidates = definitions.filter((d) => toNormalizedPath(d.fileName) !== file && d.isAmbient); + 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; - const info = this.projectService.getOrCreateScriptInfoNotOpenedByClient( - fileNameToSearch, - noDtsProject.currentDirectory, - noDtsProject.directoryStructureHost - ); - if (!info) - continue; + if (!fileNameToSearch) continue; + const info = this.projectService.getOrCreateScriptInfoNotOpenedByClient(fileNameToSearch, noDtsProject.currentDirectory, noDtsProject.directoryStructureHost); + if (!info) continue; if (!noDtsProject.containsScriptInfo(info)) { noDtsProject.addRoot(info); noDtsProject.updateGraph(); @@ -181323,7 +164911,7 @@ Project '${project.projectName}' (${ProjectKind[project.projectKind]}) ${counter } definitions = arrayFrom(definitionSet.values()); } - definitions = definitions.filter((d) => !d.isAmbient && !d.failedAliasResolution); + definitions = definitions.filter(d => !d.isAmbient && !d.failedAliasResolution); return this.mapDefinitionInfo(definitions, project); function findImplementationFileFromDtsFileName(fileName, resolveFromFile, auxiliaryProject) { var _a2, _b, _c; @@ -181333,21 +164921,14 @@ 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; - const entrypoints = getEntrypointsFromPackageJsonInfo( - packageJson, - { moduleResolution: 2 /* Node10 */ }, - project, - project.getModuleResolutionCache() - ); - const packageNamePathPart = fileName.substring( - nodeModulesPathParts.topLevelPackageNameIndex + 1, - nodeModulesPathParts.packageRootIndex - ); + if (!packageJson) return void 0; + const entrypoints = getEntrypointsFromPackageJsonInfo(packageJson, { + moduleResolution: 2 /* Node10 */ + }, project, project.getModuleResolutionCache()); + const packageNamePathPart = fileName.substring(nodeModulesPathParts.topLevelPackageNameIndex + 1, nodeModulesPathParts.packageRootIndex); const packageName = getPackageNameFromTypesPackageName(unmangleScopedPackageName(packageNamePathPart)); const path = project.toPath(fileName); - if (entrypoints && some(entrypoints, (e) => project.toPath(e) === path)) { + if (entrypoints && some(entrypoints, e => project.toPath(e) === path)) { return (_b = auxiliaryProject.resolutionCache.resolveSingleModuleNameWithoutWatching(packageName, resolveFromFile).resolvedModule) == null ? void 0 : _b.resolvedFileName; } else { const pathToFileInPackage = fileName.substring(nodeModulesPathParts.packageRootIndex + 1); @@ -181362,18 +164943,12 @@ Project '${project.projectName}' (${ProjectKind[project.projectKind]}) ${counter const program = ls.getProgram(); const initialNode = getTouchingPropertyName(program.getSourceFile(file), position); if ((isStringLiteralLike(initialNode) || isIdentifier(initialNode)) && isAccessExpression(initialNode.parent)) { - return forEachNameInAccessChainWalkingLeft(initialNode, (nameInChain) => { + return forEachNameInAccessChainWalkingLeft(initialNode, nameInChain => { var _a2; - if (nameInChain === initialNode) - return void 0; - const candidates = (_a2 = ls.getDefinitionAtPosition( - file, - nameInChain.getStart(), - /*searchOtherFilesOnly*/ - true, - /*stopAtAlias*/ - false - )) == null ? void 0 : _a2.filter((d) => toNormalizedPath(d.fileName) !== file && d.isAmbient).map((d) => ({ + if (nameInChain === initialNode) return void 0; + const candidates = (_a2 = ls.getDefinitionAtPosition(file, nameInChain.getStart(), /*searchOtherFilesOnly*/ + true, /*stopAtAlias*/ + false)) == null ? void 0 : _a2.filter(d => toNormalizedPath(d.fileName) !== file && d.isAmbient).map(d => ({ fileName: d.fileName, name: getTextOfIdentifierOrLiteral(initialNode) })); @@ -181393,50 +164968,47 @@ 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); } function searchForDeclaration(declarationName, fileToSearch, noDtsProgram) { const matches = ts_FindAllReferences_exports.Core.getTopMostDeclarationNamesInFile(declarationName, fileToSearch); - return mapDefined(matches, (match) => { + return mapDefined(matches, match => { const symbol = noDtsProgram.getTypeChecker().getSymbolAtLocation(match); const decl = getDeclarationFromName(match); if (symbol && decl) { - return ts_GoToDefinition_exports.createDefinitionInfo( - decl, - noDtsProgram.getTypeChecker(), - symbol, - decl, - /*unverified*/ - true - ); + return ts_GoToDefinition_exports.createDefinitionInfo(decl, noDtsProgram.getTypeChecker(), symbol, decl, /*unverified*/ + true); } }); } } getEmitOutput(args) { - const { file, project } = this.getFileAndProject(args); + const { + file, + project + } = this.getFileAndProject(args); if (!project.shouldEmitFile(project.getScriptInfo(file))) { - return { emitSkipped: true, outputFiles: [], diagnostics: [] }; + return { + emitSkipped: true, + outputFiles: [], + diagnostics: [] + }; } const result = project.getLanguageService().getEmitOutput(file); return args.richResponse ? { ...result, - diagnostics: args.includeLinePosition ? this.convertToDiagnosticsWithLinePositionFromDiagnosticFile(result.diagnostics) : result.diagnostics.map((d) => formatDiagnosticToProtocol( - d, - /*includeFileName*/ - true - )) + diagnostics: args.includeLinePosition ? this.convertToDiagnosticsWithLinePositionFromDiagnosticFile(result.diagnostics) : result.diagnostics.map(d => formatDiagnosticToProtocol(d, /*includeFileName*/ + true)) } : result; } mapJSDocTagInfo(tags, project, richResponse) { - return tags ? tags.map((tag) => { + return tags ? tags.map(tag => { var _a; return { ...tag, - text: richResponse ? this.mapDisplayParts(tag.text, project) : (_a = tag.text) == null ? void 0 : _a.map((part) => part.text).join("") + text: richResponse ? this.mapDisplayParts(tag.text, project) : (_a = tag.text) == null ? void 0 : _a.map(part => part.text).join("") }; }) : []; } @@ -181444,23 +165016,29 @@ Project '${project.projectName}' (${ProjectKind[project.projectKind]}) ${counter if (!parts) { return []; } - return parts.map( - (part) => part.kind !== "linkName" ? part : { - ...part, - target: this.toFileSpan(part.target.fileName, part.target.textSpan, project) - } - ); + return parts.map(part => part.kind !== "linkName" ? part : { + ...part, + target: this.toFileSpan(part.target.fileName, part.target.textSpan, project) + }); } mapSignatureHelpItems(items, project, richResponse) { - return items.map((item) => ({ + return items.map(item => ({ ...item, documentation: this.mapDisplayParts(item.documentation, project), - parameters: item.parameters.map((p) => ({ ...p, documentation: this.mapDisplayParts(p.documentation, project) })), + parameters: item.parameters.map(p => ({ + ...p, + documentation: this.mapDisplayParts(p.documentation, project) + })), tags: this.mapJSDocTagInfo(item.tags, project, richResponse) })); } mapDefinitionInfo(definitions, project) { - return definitions.map((def) => ({ ...this.toFileSpanWithContext(def.fileName, def.textSpan, def.contextSpan, project), ...def.unverified && { unverified: def.unverified } })); + return definitions.map(def => ({ + ...this.toFileSpanWithContext(def.fileName, def.textSpan, def.contextSpan, project), + ...(def.unverified && { + unverified: def.unverified + }) + })); } /* * When we map a .d.ts location to .ts, Visual Studio gets confused because there's no associated Roslyn Document in @@ -181490,23 +165068,36 @@ Project '${project.projectName}' (${ProjectKind[project.projectKind]}) ${counter const end = ls.toLineColumnOffset(fileName, textSpanEnd(textSpan)); return { file: fileName, - start: { line: start.line + 1, offset: start.character + 1 }, - end: { line: end.line + 1, offset: end.character + 1 } + start: { + line: start.line + 1, + offset: start.character + 1 + }, + end: { + line: end.line + 1, + offset: end.character + 1 + } }; } toFileSpanWithContext(fileName, textSpan, contextSpan, project) { const fileSpan = this.toFileSpan(fileName, textSpan, project); const context = contextSpan && this.toFileSpan(fileName, contextSpan, project); - return context ? { ...fileSpan, contextStart: context.start, contextEnd: context.end } : fileSpan; + return context ? { + ...fileSpan, + contextStart: context.start, + contextEnd: context.end + } : fileSpan; } getTypeDefinition(args) { - const { file, project } = this.getFileAndProject(args); + const { + file, + project + } = this.getFileAndProject(args); const position = this.getPositionInFile(args, file); const definitions = this.mapDefinitionInfoLocations(project.getLanguageService().getTypeDefinitionAtPosition(file, position) || emptyArray2, project); return this.mapDefinitionInfo(definitions, project); } mapImplementationLocations(implementations, project) { - return implementations.map((info) => { + return implementations.map(info => { const newDocumentSpan = getMappedDocumentSpanForProject(info, project); return !newDocumentSpan ? info : { ...newDocumentSpan, @@ -181516,78 +165107,93 @@ Project '${project.projectName}' (${ProjectKind[project.projectKind]}) ${counter }); } getImplementation(args, simplifiedResult) { - const { file, project } = this.getFileAndProject(args); + const { + file, + project + } = this.getFileAndProject(args); const position = this.getPositionInFile(args, file); const implementations = this.mapImplementationLocations(project.getLanguageService().getImplementationAtPosition(file, position) || emptyArray2, project); - return simplifiedResult ? implementations.map(({ fileName, textSpan, contextSpan }) => this.toFileSpanWithContext(fileName, textSpan, contextSpan, project)) : implementations.map(_Session.mapToOriginalLocation); + return simplifiedResult ? implementations.map(({ + fileName, + textSpan, + contextSpan + }) => this.toFileSpanWithContext(fileName, textSpan, contextSpan, project)) : implementations.map(_Session.mapToOriginalLocation); } getSyntacticDiagnosticsSync(args) { - const { configFile } = this.getConfigFileAndProject(args); + const { + configFile + } = this.getConfigFileAndProject(args); if (configFile) { return emptyArray2; } - return this.getDiagnosticsWorker( - args, - /*isSemantic*/ - false, - (project, file) => project.getLanguageService().getSyntacticDiagnostics(file), - !!args.includeLinePosition - ); + return this.getDiagnosticsWorker(args, /*isSemantic*/ + false, (project, file) => project.getLanguageService().getSyntacticDiagnostics(file), !!args.includeLinePosition); } getSemanticDiagnosticsSync(args) { - const { configFile, project } = this.getConfigFileAndProject(args); + const { + configFile, + project + } = this.getConfigFileAndProject(args); if (configFile) { return this.getConfigFileDiagnostics(configFile, project, !!args.includeLinePosition); } - return this.getDiagnosticsWorker( - args, - /*isSemantic*/ - true, - (project2, file) => project2.getLanguageService().getSemanticDiagnostics(file).filter((d) => !!d.file), - !!args.includeLinePosition - ); + return this.getDiagnosticsWorker(args, /*isSemantic*/ + true, (project2, file) => project2.getLanguageService().getSemanticDiagnostics(file).filter(d => !!d.file), !!args.includeLinePosition); } getSuggestionDiagnosticsSync(args) { - const { configFile } = this.getConfigFileAndProject(args); + const { + configFile + } = this.getConfigFileAndProject(args); if (configFile) { return emptyArray2; } - return this.getDiagnosticsWorker( - args, - /*isSemantic*/ - true, - (project, file) => project.getLanguageService().getSuggestionDiagnostics(file), - !!args.includeLinePosition - ); + return this.getDiagnosticsWorker(args, /*isSemantic*/ + true, (project, file) => project.getLanguageService().getSuggestionDiagnostics(file), !!args.includeLinePosition); } getJsxClosingTag(args) { - const { file, languageService } = this.getFileAndLanguageServiceForSyntacticOperation(args); + const { + file, + languageService + } = this.getFileAndLanguageServiceForSyntacticOperation(args); const position = this.getPositionInFile(args, file); const tag = languageService.getJsxClosingTagAtPosition(file, position); - return tag === void 0 ? void 0 : { newText: tag.newText, caretOffset: 0 }; + return tag === void 0 ? void 0 : { + newText: tag.newText, + caretOffset: 0 + }; } getLinkedEditingRange(args) { - const { file, languageService } = this.getFileAndLanguageServiceForSyntacticOperation(args); + const { + file, + languageService + } = this.getFileAndLanguageServiceForSyntacticOperation(args); 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 { + 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; - return documentHighlights.map(({ fileName, highlightSpans }) => { + if (!documentHighlights) return emptyArray2; + if (!simplifiedResult) return documentHighlights; + return documentHighlights.map(({ + fileName, + highlightSpans + }) => { const scriptInfo = project.getScriptInfo(fileName); return { file: fileName, - highlightSpans: highlightSpans.map(({ textSpan, kind, contextSpan }) => ({ + highlightSpans: highlightSpans.map(({ + textSpan, + kind, + contextSpan + }) => ({ ...toProtocolTextSpanWithContext(textSpan, contextSpan, scriptInfo), kind })) @@ -181595,15 +165201,25 @@ Project '${project.projectName}' (${ProjectKind[project.projectKind]}) ${counter }); } provideInlayHints(args) { - const { file, project } = this.getFileAndProject(args); + const { + file, + project + } = this.getFileAndProject(args); const scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file); const hints = project.getLanguageService().provideInlayHints(file, args, this.getPreferences(file)); - return hints.map((hint) => { - const { position, displayParts } = hint; + return hints.map(hint => { + const { + position, + displayParts + } = hint; return { ...hint, position: scriptInfo.positionToLineOffset(position), - displayParts: displayParts == null ? void 0 : displayParts.map(({ text, span, file: file2 }) => { + displayParts: displayParts == null ? void 0 : displayParts.map(({ + text, + span, + file: file2 + }) => { if (span) { Debug.assertIsDefined(file2, "Target file should be defined together with its span."); const scriptInfo2 = this.projectService.getScriptInfo(file2); @@ -181616,7 +165232,9 @@ Project '${project.projectName}' (${ProjectKind[project.projectKind]}) ${counter } }; } else { - return { text }; + return { + text + }; } }) }; @@ -181626,30 +165244,27 @@ Project '${project.projectName}' (${ProjectKind[project.projectKind]}) ${counter this.projectService.setCompilerOptionsForInferredProjects(args.options, args.projectRootPath); } getProjectInfo(args) { - return this.getProjectInfoWorker( - args.file, - args.projectFileName, - args.needFileNameList, - /*excludeConfigFiles*/ - false - ); + return this.getProjectInfoWorker(args.file, args.projectFileName, args.needFileNameList, /*excludeConfigFiles*/ + false); } getProjectInfoWorker(uncheckedFileName, projectFileName, needFileNameList, excludeConfigFiles) { - const { project } = this.getFileAndProjectWorker(uncheckedFileName, projectFileName); + const { + project + } = this.getFileAndProjectWorker(uncheckedFileName, projectFileName); updateProjectIfDirty(project); const projectInfo = { configFileName: project.getProjectName(), languageServiceDisabled: !project.languageServiceEnabled, - fileNames: needFileNameList ? project.getFileNames( - /*excludeFilesFromExternalLibraries*/ - false, - excludeConfigFiles - ) : void 0 + fileNames: needFileNameList ? project.getFileNames( /*excludeFilesFromExternalLibraries*/ + false, excludeConfigFiles) : void 0 }; return projectInfo; } getRenameInfo(args) { - const { file, project } = this.getFileAndProject(args); + const { + file, + project + } = this.getFileAndProject(args); const position = this.getPositionInFile(args, file); const preferences = this.getPreferences(file); return project.getLanguageService().getRenameInfo(file, position, preferences); @@ -181665,8 +165280,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) { @@ -181675,12 +165289,16 @@ Project '${project.projectName}' (${ProjectKind[project.projectKind]}) ${counter projects = scriptInfo.containingProjects; symLinkedProjects = this.projectService.getSymlinkedProjects(scriptInfo); } - projects = filter(projects, (p) => p.languageServiceEnabled && !p.isOrphan()); + projects = filter(projects, p => p.languageServiceEnabled && !p.isOrphan()); if (!ignoreNoProjectError && (!projects || !projects.length) && !symLinkedProjects) { - this.projectService.logErrorForScriptInfoNotFound(args.file ?? args.projectFileName); + var _args$file; + this.projectService.logErrorForScriptInfoNotFound((_args$file = args.file) !== null && _args$file !== void 0 ? _args$file : args.projectFileName); return Errors.ThrowNoProject(); } - return symLinkedProjects ? { projects, symLinkedProjects } : projects; + return symLinkedProjects ? { + projects, + symLinkedProjects + } : projects; } getDefaultProject(args) { if (args.projectFileName) { @@ -181701,42 +165319,66 @@ Project '${project.projectName}' (${ProjectKind[project.projectKind]}) ${counter const projects = this.getProjects(args); const defaultProject = this.getDefaultProject(args); const preferences = this.getPreferences(file); - const renameInfo = this.mapRenameInfo( - defaultProject.getLanguageService().getRenameInfo(file, position, preferences), - Debug.checkDefined(this.projectService.getScriptInfo(file)) - ); - if (!renameInfo.canRename) - return simplifiedResult ? { info: renameInfo, locs: [] } : []; - const locations = getRenameLocationsWorker( - projects, - defaultProject, - { fileName: args.file, pos: position }, - !!args.findInStrings, - !!args.findInComments, - preferences - ); - if (!simplifiedResult) - return locations; - return { info: renameInfo, locs: this.toSpanGroups(locations) }; + const renameInfo = this.mapRenameInfo(defaultProject.getLanguageService().getRenameInfo(file, position, preferences), Debug.checkDefined(this.projectService.getScriptInfo(file))); + if (!renameInfo.canRename) return simplifiedResult ? { + info: renameInfo, + locs: [] + } : []; + const locations = getRenameLocationsWorker(projects, defaultProject, { + fileName: args.file, + pos: position + }, !!args.findInStrings, !!args.findInComments, preferences); + if (!simplifiedResult) return locations; + return { + info: renameInfo, + locs: this.toSpanGroups(locations) + }; } mapRenameInfo(info, scriptInfo) { if (info.canRename) { - const { canRename, fileToRename, displayName, fullDisplayName, kind, kindModifiers, triggerSpan } = info; - return identity( - { canRename, fileToRename, displayName, fullDisplayName, kind, kindModifiers, triggerSpan: toProtocolTextSpan(triggerSpan, scriptInfo) } - ); + const { + canRename, + fileToRename, + displayName, + fullDisplayName, + kind, + kindModifiers, + triggerSpan + } = info; + return identity({ + canRename, + fileToRename, + displayName, + fullDisplayName, + kind, + kindModifiers, + triggerSpan: toProtocolTextSpan(triggerSpan, scriptInfo) + }); } else { return info; } } toSpanGroups(locations) { - const map2 = /* @__PURE__ */ new Map(); - for (const { fileName, textSpan, contextSpan, originalContextSpan: _2, originalTextSpan: _, originalFileName: _1, ...prefixSuffixText } of locations) { + 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 }); + group2.locs.push({ + ...toProtocolTextSpanWithContext(textSpan, contextSpan, scriptInfo), + ...prefixSuffixText + }); } return arrayFrom(map2.values()); } @@ -181744,14 +165386,11 @@ Project '${project.projectName}' (${ProjectKind[project.projectKind]}) ${counter const file = toNormalizedPath(args.file); const projects = this.getProjects(args); const position = this.getPositionInFile(args, file); - const references = getReferencesWorker( - projects, - this.getDefaultProject(args), - { fileName: args.file, pos: position }, - this.logger - ); - if (!simplifiedResult) - return references; + const references = getReferencesWorker(projects, this.getDefaultProject(args), { + fileName: args.file, + pos: position + }, this.logger); + if (!simplifiedResult) return references; const preferences = this.getPreferences(file); const defaultProject = this.getDefaultProject(args); const scriptInfo = defaultProject.getScriptInfoForNormalizedPath(file); @@ -181760,10 +165399,15 @@ Project '${project.projectName}' (${ProjectKind[project.projectKind]}) ${counter const nameSpan = nameInfo && nameInfo.textSpan; const symbolStartOffset = nameSpan ? scriptInfo.positionToLineOffset(nameSpan.start).offset : 0; const symbolName2 = nameSpan ? scriptInfo.getSnapshot().getText(nameSpan.start, textSpanEnd(nameSpan)) : ""; - const refs = flatMap(references, (referencedSymbol) => { - return referencedSymbol.references.map((entry) => referenceEntryToReferencesResponseItem(this.projectService, entry, preferences)); + const refs = flatMap(references, referencedSymbol => { + return referencedSymbol.references.map(entry => referenceEntryToReferencesResponseItem(this.projectService, entry, preferences)); }); - return { refs, symbolName: symbolName2, symbolStartOffset, symbolDisplayString }; + return { + refs, + symbolName: symbolName2, + symbolStartOffset, + symbolDisplayString + }; } getFileReferences(args, simplifiedResult) { const projects = this.getProjects(args); @@ -181771,27 +165415,21 @@ Project '${project.projectName}' (${ProjectKind[project.projectKind]}) ${counter const preferences = this.getPreferences(toNormalizedPath(fileName)); const references = []; const seen = createDocumentSpanSet(); - forEachProjectInProjects( - projects, - /*path*/ - void 0, - (project) => { - if (project.getCancellationToken().isCancellationRequested()) - return; - const projectOutputs = project.getLanguageService().getFileReferences(fileName); - if (projectOutputs) { - for (const referenceEntry of projectOutputs) { - if (!seen.has(referenceEntry)) { - references.push(referenceEntry); - seen.add(referenceEntry); - } + forEachProjectInProjects(projects, /*path*/ + void 0, project => { + if (project.getCancellationToken().isCancellationRequested()) return; + const projectOutputs = project.getLanguageService().getFileReferences(fileName); + if (projectOutputs) { + for (const referenceEntry of projectOutputs) { + if (!seen.has(referenceEntry)) { + references.push(referenceEntry); + seen.add(referenceEntry); } } } - ); - if (!simplifiedResult) - return references; - const refs = references.map((entry) => referenceEntryToReferencesResponseItem(this.projectService, entry, preferences)); + }); + if (!simplifiedResult) return references; + const refs = references.map(entry => referenceEntryToReferencesResponseItem(this.projectService, entry, preferences)); return { refs, symbolName: `"${args.file}"` @@ -181802,14 +165440,8 @@ Project '${project.projectName}' (${ProjectKind[project.projectKind]}) ${counter * @param fileContent is a version of the file content that is known to be more up to date than the one on disk */ openClientFile(fileName, fileContent, scriptKind, projectRootPath) { - this.projectService.openClientFileWithNormalizedPath( - fileName, - fileContent, - scriptKind, - /*hasMixedContent*/ - false, - projectRootPath - ); + this.projectService.openClientFileWithNormalizedPath(fileName, fileContent, scriptKind, /*hasMixedContent*/ + false, projectRootPath); } getPosition(args, scriptInfo) { return args.position !== void 0 ? args.position : scriptInfo.lineOffsetToPosition(args.line, args.offset); @@ -181822,26 +165454,33 @@ Project '${project.projectName}' (${ProjectKind[project.projectKind]}) ${counter return this.getFileAndProjectWorker(args.file, args.projectFileName); } getFileAndLanguageServiceForSyntacticOperation(args) { - const { file, project } = this.getFileAndProject(args); + const { + file, + project + } = this.getFileAndProject(args); return { file, - languageService: project.getLanguageService( - /*ensureSynchronized*/ - false - ) + languageService: project.getLanguageService( /*ensureSynchronized*/ + false) }; } getFileAndProjectWorker(uncheckedFileName, projectFileName) { const file = toNormalizedPath(uncheckedFileName); const project = this.getProject(projectFileName) || this.projectService.ensureDefaultProjectForFile(file); - return { file, project }; + return { + file, + project + }; } getOutliningSpans(args, simplifiedResult) { - const { file, languageService } = this.getFileAndLanguageServiceForSyntacticOperation(args); + const { + file, + languageService + } = this.getFileAndLanguageServiceForSyntacticOperation(args); const spans = languageService.getOutliningSpans(file); if (simplifiedResult) { const scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file); - return spans.map((s) => ({ + return spans.map(s => ({ textSpan: toProtocolTextSpan(s.textSpan, scriptInfo), hintSpan: toProtocolTextSpan(s.hintSpan, scriptInfo), bannerText: s.bannerText, @@ -181853,44 +165492,71 @@ Project '${project.projectName}' (${ProjectKind[project.projectKind]}) ${counter } } getTodoComments(args) { - const { file, project } = this.getFileAndProject(args); + const { + file, + project + } = this.getFileAndProject(args); return project.getLanguageService().getTodoComments(file, args.descriptors); } getDocCommentTemplate(args) { - const { file, languageService } = this.getFileAndLanguageServiceForSyntacticOperation(args); + const { + file, + languageService + } = this.getFileAndLanguageServiceForSyntacticOperation(args); const position = this.getPositionInFile(args, file); return languageService.getDocCommentTemplateAtPosition(file, position, this.getPreferences(file), this.getFormatOptions(file)); } getSpanOfEnclosingComment(args) { - const { file, languageService } = this.getFileAndLanguageServiceForSyntacticOperation(args); + const { + file, + languageService + } = this.getFileAndLanguageServiceForSyntacticOperation(args); const onlyMultiLine = args.onlyMultiLine; const position = this.getPositionInFile(args, file); return languageService.getSpanOfEnclosingComment(file, position, onlyMultiLine); } getIndentation(args) { - const { file, languageService } = this.getFileAndLanguageServiceForSyntacticOperation(args); + const { + file, + languageService + } = this.getFileAndLanguageServiceForSyntacticOperation(args); const position = this.getPositionInFile(args, file); const options = args.options ? convertFormatOptions(args.options) : this.getFormatOptions(file); const indentation = languageService.getIndentationAtPosition(file, position, options); - return { position, indentation }; + return { + position, + indentation + }; } getBreakpointStatement(args) { - const { file, languageService } = this.getFileAndLanguageServiceForSyntacticOperation(args); + const { + file, + languageService + } = this.getFileAndLanguageServiceForSyntacticOperation(args); const position = this.getPositionInFile(args, file); return languageService.getBreakpointStatementAtPosition(file, position); } getNameOrDottedNameSpan(args) { - const { file, languageService } = this.getFileAndLanguageServiceForSyntacticOperation(args); + const { + file, + languageService + } = this.getFileAndLanguageServiceForSyntacticOperation(args); const position = this.getPositionInFile(args, file); return languageService.getNameOrDottedNameSpan(file, position, position); } isValidBraceCompletion(args) { - const { file, languageService } = this.getFileAndLanguageServiceForSyntacticOperation(args); + const { + file, + languageService + } = this.getFileAndLanguageServiceForSyntacticOperation(args); const position = this.getPositionInFile(args, file); return languageService.isValidBraceCompletionAtPosition(file, position, args.openingBrace.charCodeAt(0)); } getQuickInfoWorker(args, simplifiedResult) { - const { file, project } = this.getFileAndProject(args); + const { + file, + project + } = this.getFileAndProject(args); const scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file); const quickInfo = project.getLanguageService().getQuickInfoAtPosition(file, this.getPosition(args, scriptInfo)); if (!quickInfo) { @@ -181911,17 +165577,16 @@ Project '${project.projectName}' (${ProjectKind[project.projectKind]}) ${counter } else { return useDisplayParts ? quickInfo : { ...quickInfo, - tags: this.mapJSDocTagInfo( - quickInfo.tags, - project, - /*richResponse*/ - false - ) + tags: this.mapJSDocTagInfo(quickInfo.tags, project, /*richResponse*/ + false) }; } } getFormattingEditsForRange(args) { - const { file, languageService } = this.getFileAndLanguageServiceForSyntacticOperation(args); + const { + file, + languageService + } = this.getFileAndLanguageServiceForSyntacticOperation(args); const scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file); const startPosition = scriptInfo.lineOffsetToPosition(args.line, args.offset); const endPosition = scriptInfo.lineOffsetToPosition(args.endLine, args.endOffset); @@ -181929,31 +165594,46 @@ Project '${project.projectName}' (${ProjectKind[project.projectKind]}) ${counter if (!edits) { return void 0; } - return edits.map((edit) => this.convertTextChangeToCodeEdit(edit, scriptInfo)); + return edits.map(edit => this.convertTextChangeToCodeEdit(edit, scriptInfo)); } getFormattingEditsForRangeFull(args) { - const { file, languageService } = this.getFileAndLanguageServiceForSyntacticOperation(args); + const { + file, + languageService + } = this.getFileAndLanguageServiceForSyntacticOperation(args); const options = args.options ? convertFormatOptions(args.options) : this.getFormatOptions(file); return languageService.getFormattingEditsForRange(file, args.position, args.endPosition, options); } getFormattingEditsForDocumentFull(args) { - const { file, languageService } = this.getFileAndLanguageServiceForSyntacticOperation(args); + const { + file, + languageService + } = this.getFileAndLanguageServiceForSyntacticOperation(args); const options = args.options ? convertFormatOptions(args.options) : this.getFormatOptions(file); return languageService.getFormattingEditsForDocument(file, options); } getFormattingEditsAfterKeystrokeFull(args) { - const { file, languageService } = this.getFileAndLanguageServiceForSyntacticOperation(args); + const { + file, + languageService + } = this.getFileAndLanguageServiceForSyntacticOperation(args); const options = args.options ? convertFormatOptions(args.options) : this.getFormatOptions(file); return languageService.getFormattingEditsAfterKeystroke(file, args.position, args.key, options); } getFormattingEditsAfterKeystroke(args) { - const { file, languageService } = this.getFileAndLanguageServiceForSyntacticOperation(args); + const { + file, + languageService + } = this.getFileAndLanguageServiceForSyntacticOperation(args); const scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file); const position = scriptInfo.lineOffsetToPosition(args.line, args.offset); const formatOptions = this.getFormatOptions(file); const edits = languageService.getFormattingEditsAfterKeystroke(file, position, args.key, formatOptions); if (args.key === "\n" && (!edits || edits.length === 0 || allEditsBeforePos(edits, position))) { - const { lineText, absolutePosition } = scriptInfo.textStorage.getAbsolutePositionAndLineText(args.line); + const { + lineText, + absolutePosition + } = scriptInfo.textStorage.getAbsolutePositionAndLineText(args.line); if (lineText && lineText.search("\\S") < 0) { const preferredIndent = languageService.getIndentationAtPosition(file, position, formatOptions); let hasIndent = 0; @@ -181979,7 +165659,7 @@ Project '${project.projectName}' (${ProjectKind[project.projectKind]}) ${counter if (!edits) { return void 0; } - return edits.map((edit) => { + return edits.map(edit => { return { start: scriptInfo.positionToLineOffset(edit.span.start), end: scriptInfo.positionToLineOffset(textSpanEnd(edit.span)), @@ -181988,27 +165668,23 @@ Project '${project.projectName}' (${ProjectKind[project.projectKind]}) ${counter }); } getCompletions(args, kind) { - const { file, project } = this.getFileAndProject(args); + const { + file, + project + } = this.getFileAndProject(args); const scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file); const position = this.getPosition(args, scriptInfo); - const completions = project.getLanguageService().getCompletionsAtPosition( - file, - position, - { - ...convertUserPreferences(this.getPreferences(file)), - triggerCharacter: args.triggerCharacter, - triggerKind: args.triggerKind, - includeExternalModuleExports: args.includeExternalModuleExports, - includeInsertTextCompletions: args.includeInsertTextCompletions - }, - project.projectService.getFormatCodeOptions(file) - ); - if (completions === void 0) - return void 0; - if (kind === "completions-full" /* CompletionsFull */) - return completions; + const completions = project.getLanguageService().getCompletionsAtPosition(file, position, { + ...convertUserPreferences(this.getPreferences(file)), + triggerCharacter: args.triggerCharacter, + triggerKind: args.triggerKind, + includeExternalModuleExports: args.includeExternalModuleExports, + includeInsertTextCompletions: args.includeInsertTextCompletions + }, project.projectService.getFormatCodeOptions(file)); + if (completions === void 0) return void 0; + if (kind === "completions-full" /* CompletionsFull */) return completions; const prefix = args.prefix || ""; - const entries = mapDefined(completions.entries, (entry) => { + const entries = mapDefined(completions.entries, entry => { if (completions.isMemberCompletion || startsWith(entry.name.toLowerCase(), prefix.toLowerCase())) { const { name, @@ -182050,8 +165726,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 = { @@ -182062,80 +165737,90 @@ Project '${project.projectName}' (${ProjectKind[project.projectKind]}) ${counter return res; } getCompletionEntryDetails(args, fullResult) { - const { file, project } = this.getFileAndProject(args); + const { + file, + project + } = this.getFileAndProject(args); const scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file); const position = this.getPosition(args, scriptInfo); const formattingOptions = project.projectService.getFormatCodeOptions(file); const useDisplayParts = !!this.getPreferences(file).displayPartsForJSDoc; - const result = mapDefined(args.entryNames, (entryName) => { - const { name, source, data } = typeof entryName === "string" ? { name: entryName, source: void 0, data: void 0 } : entryName; + const result = mapDefined(args.entryNames, entryName => { + const { + name, + source, + data + } = typeof entryName === "string" ? { + name: entryName, + source: void 0, + data: void 0 + } : entryName; return project.getLanguageService().getCompletionEntryDetails(file, position, name, formattingOptions, source, this.getPreferences(file), data ? cast(data, isCompletionEntryData) : void 0); }); - return fullResult ? useDisplayParts ? result : result.map((details) => ({ ...details, tags: this.mapJSDocTagInfo( - details.tags, - project, - /*richResponse*/ - false - ) })) : result.map((details) => ({ + return fullResult ? useDisplayParts ? result : result.map(details => ({ ...details, - codeActions: map(details.codeActions, (action) => this.mapCodeAction(action)), + tags: this.mapJSDocTagInfo(details.tags, project, /*richResponse*/ + false) + })) : result.map(details => ({ + ...details, + codeActions: map(details.codeActions, action => this.mapCodeAction(action)), documentation: this.mapDisplayParts(details.documentation, project), tags: this.mapJSDocTagInfo(details.tags, project, useDisplayParts) })); } getCompileOnSaveAffectedFileList(args) { - const projects = this.getProjects( - args, - /*getScriptInfoEnsuringProjectsUptoDate*/ - true, - /*ignoreNoProjectError*/ - true - ); + const projects = this.getProjects(args, /*getScriptInfoEnsuringProjectsUptoDate*/ + true, /*ignoreNoProjectError*/ + true); const info = this.projectService.getScriptInfo(args.file); if (!info) { return emptyArray2; } - return combineProjectOutput( - info, - (path) => this.projectService.getScriptInfoForPath(path), - projects, - (project, info2) => { - if (!project.compileOnSaveEnabled || !project.languageServiceEnabled || project.isOrphan()) { - return void 0; - } - const compilationSettings = project.getCompilationSettings(); - if (!!compilationSettings.noEmit || isDeclarationFileName(info2.fileName) && !dtsChangeCanAffectEmit(compilationSettings)) { - return void 0; - } - return { - projectFileName: project.getProjectName(), - fileNames: project.getCompileOnSaveAffectedFileList(info2), - projectUsesOutFile: !!outFile(compilationSettings) - }; + return combineProjectOutput(info, path => this.projectService.getScriptInfoForPath(path), projects, (project, info2) => { + if (!project.compileOnSaveEnabled || !project.languageServiceEnabled || project.isOrphan()) { + return void 0; } - ); + const compilationSettings = project.getCompilationSettings(); + if (!!compilationSettings.noEmit || isDeclarationFileName(info2.fileName) && !dtsChangeCanAffectEmit(compilationSettings)) { + return void 0; + } + return { + projectFileName: project.getProjectName(), + fileNames: project.getCompileOnSaveAffectedFileList(info2), + projectUsesOutFile: !!outFile(compilationSettings) + }; + }); } emitFile(args) { - const { file, project } = this.getFileAndProject(args); + const { + file, + project + } = this.getFileAndProject(args); if (!project) { Errors.ThrowNoProject(); } if (!project.languageServiceEnabled) { - return args.richResponse ? { emitSkipped: true, diagnostics: [] } : false; + return args.richResponse ? { + emitSkipped: true, + diagnostics: [] + } : false; } const scriptInfo = project.getScriptInfo(file); - const { emitSkipped, diagnostics } = project.emitFile(scriptInfo, (path, data, writeByteOrderMark) => this.host.writeFile(path, data, writeByteOrderMark)); + const { + emitSkipped, + diagnostics + } = project.emitFile(scriptInfo, (path, data, writeByteOrderMark) => this.host.writeFile(path, data, writeByteOrderMark)); return args.richResponse ? { emitSkipped, - diagnostics: args.includeLinePosition ? this.convertToDiagnosticsWithLinePositionFromDiagnosticFile(diagnostics) : diagnostics.map((d) => formatDiagnosticToProtocol( - d, - /*includeFileName*/ - true - )) + diagnostics: args.includeLinePosition ? this.convertToDiagnosticsWithLinePositionFromDiagnosticFile(diagnostics) : diagnostics.map(d => formatDiagnosticToProtocol(d, /*includeFileName*/ + true)) } : !emitSkipped; } getSignatureHelpItems(args, simplifiedResult) { - const { file, project } = this.getFileAndProject(args); + const { + file, + project + } = this.getFileAndProject(args); const scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file); const position = this.getPosition(args, scriptInfo); const helpItems = project.getLanguageService().getSignatureHelpItems(file, position, args); @@ -182155,19 +165840,21 @@ Project '${project.projectName}' (${ProjectKind[project.projectKind]}) ${counter } else { return { ...helpItems, - items: helpItems.items.map((item) => ({ ...item, tags: this.mapJSDocTagInfo( - item.tags, - project, - /*richResponse*/ - false - ) })) + items: helpItems.items.map(item => ({ + ...item, + tags: this.mapJSDocTagInfo(item.tags, project, /*richResponse*/ + false) + })) }; } } toPendingErrorCheck(uncheckedFileName) { const fileName = toNormalizedPath(uncheckedFileName); const project = this.projectService.tryGetDefaultProjectForFile(fileName); - return project && { fileName, project }; + return project && { + fileName, + project + }; } getDiagnostics(next, delay, fileNames) { if (this.suppressDiagnosticEvents) { @@ -182185,16 +165872,17 @@ Project '${project.projectName}' (${ProjectKind[project.projectKind]}) ${counter const end = scriptInfo.lineOffsetToPosition(args.endLine, args.endOffset); if (start >= 0) { this.changeSeq++; - this.projectService.applyChangesToFile( - scriptInfo, - singleIterator({ - span: { start, length: end - start }, - newText: args.insertString - // TODO: GH#18217 - }) - ); + this.projectService.applyChangesToFile(scriptInfo, singleIterator({ + span: { + start, + length: end - start + }, + newText: args.insertString + // TODO: GH#18217 + })); } } + reload(args, reqSeq) { const file = toNormalizedPath(args.file); const tempFileName = args.tmpfile === void 0 ? void 0 : toNormalizedPath(args.tmpfile); @@ -182202,14 +165890,9 @@ Project '${project.projectName}' (${ProjectKind[project.projectKind]}) ${counter if (info) { this.changeSeq++; if (info.reloadFromFile(tempFileName)) { - this.doOutput( - /*info*/ - void 0, - "reload" /* Reload */, - reqSeq, - /*success*/ - true - ); + this.doOutput( /*info*/ + void 0, "reload" /* Reload */, reqSeq, /*success*/ + true); } } } @@ -182227,17 +165910,20 @@ Project '${project.projectName}' (${ProjectKind[project.projectKind]}) ${counter this.projectService.closeClientFile(file); } mapLocationNavigationBarItems(items, scriptInfo) { - return map(items, (item) => ({ + return map(items, item => ({ text: item.text, kind: item.kind, kindModifiers: item.kindModifiers, - spans: item.spans.map((span) => toProtocolTextSpan(span, scriptInfo)), + spans: item.spans.map(span => toProtocolTextSpan(span, scriptInfo)), childItems: this.mapLocationNavigationBarItems(item.childItems, scriptInfo), indent: item.indent })); } getNavigationBarItems(args, simplifiedResult) { - const { file, languageService } = this.getFileAndLanguageServiceForSyntacticOperation(args); + const { + file, + languageService + } = this.getFileAndLanguageServiceForSyntacticOperation(args); const items = languageService.getNavigationBarItems(file); return !items ? void 0 : simplifiedResult ? this.mapLocationNavigationBarItems(items, this.projectService.getScriptInfoForNormalizedPath(file)) : items; } @@ -182246,82 +165932,91 @@ Project '${project.projectName}' (${ProjectKind[project.projectKind]}) ${counter text: tree.text, kind: tree.kind, kindModifiers: tree.kindModifiers, - spans: tree.spans.map((span) => toProtocolTextSpan(span, scriptInfo)), + spans: tree.spans.map(span => toProtocolTextSpan(span, scriptInfo)), nameSpan: tree.nameSpan && toProtocolTextSpan(tree.nameSpan, scriptInfo), - childItems: map(tree.childItems, (item) => this.toLocationNavigationTree(item, scriptInfo)) + childItems: map(tree.childItems, item => this.toLocationNavigationTree(item, scriptInfo)) }; } getNavigationTree(args, simplifiedResult) { - const { file, languageService } = this.getFileAndLanguageServiceForSyntacticOperation(args); + const { + file, + languageService + } = this.getFileAndLanguageServiceForSyntacticOperation(args); const tree = languageService.getNavigationTree(file); return !tree ? void 0 : simplifiedResult ? this.toLocationNavigationTree(tree, this.projectService.getScriptInfoForNormalizedPath(file)) : tree; } getNavigateToItems(args, simplifiedResult) { const full = this.getFullNavigateToItems(args); - return !simplifiedResult ? flatMap(full, ({ navigateToItems }) => navigateToItems) : flatMap( - full, - ({ project, navigateToItems }) => navigateToItems.map((navItem) => { - const scriptInfo = project.getScriptInfo(navItem.fileName); - const bakedItem = { - name: navItem.name, - kind: navItem.kind, - kindModifiers: navItem.kindModifiers, - isCaseSensitive: navItem.isCaseSensitive, - matchKind: navItem.matchKind, - file: navItem.fileName, - start: scriptInfo.positionToLineOffset(navItem.textSpan.start), - end: scriptInfo.positionToLineOffset(textSpanEnd(navItem.textSpan)) - }; - if (navItem.kindModifiers && navItem.kindModifiers !== "") { - bakedItem.kindModifiers = navItem.kindModifiers; - } - if (navItem.containerName && navItem.containerName.length > 0) { - bakedItem.containerName = navItem.containerName; - } - if (navItem.containerKind && navItem.containerKind.length > 0) { - bakedItem.containerKind = navItem.containerKind; - } - return bakedItem; - }) - ); + return !simplifiedResult ? flatMap(full, ({ + navigateToItems + }) => navigateToItems) : flatMap(full, ({ + project, + navigateToItems + }) => navigateToItems.map(navItem => { + const scriptInfo = project.getScriptInfo(navItem.fileName); + const bakedItem = { + name: navItem.name, + kind: navItem.kind, + kindModifiers: navItem.kindModifiers, + isCaseSensitive: navItem.isCaseSensitive, + matchKind: navItem.matchKind, + file: navItem.fileName, + start: scriptInfo.positionToLineOffset(navItem.textSpan.start), + end: scriptInfo.positionToLineOffset(textSpanEnd(navItem.textSpan)) + }; + if (navItem.kindModifiers && navItem.kindModifiers !== "") { + bakedItem.kindModifiers = navItem.kindModifiers; + } + if (navItem.containerName && navItem.containerName.length > 0) { + bakedItem.containerName = navItem.containerName; + } + if (navItem.containerKind && navItem.containerKind.length > 0) { + bakedItem.containerKind = navItem.containerKind; + } + return bakedItem; + })); } getFullNavigateToItems(args) { - const { currentFileOnly, searchValue, maxResultCount, projectFileName } = args; + const { + currentFileOnly, + searchValue, + maxResultCount, + projectFileName + } = args; if (currentFileOnly) { Debug.assertIsDefined(args.file); - const { file, project } = this.getFileAndProject(args); - return [{ project, navigateToItems: project.getLanguageService().getNavigateToItems(searchValue, maxResultCount, file) }]; + const { + file, + project + } = this.getFileAndProject(args); + return [{ + project, + navigateToItems: project.getLanguageService().getNavigateToItems(searchValue, maxResultCount, file) + }]; } const preferences = this.getHostPreferences(); const outputs = []; - const seenItems = /* @__PURE__ */ new Map(); + const seenItems = /* @__PURE__ */new Map(); if (!args.file && !projectFileName) { this.projectService.loadAncestorProjectTree(); - this.projectService.forEachEnabledProject((project) => addItemsForProject(project)); + this.projectService.forEachEnabledProject(project => addItemsForProject(project)); } else { const projects = this.getProjects(args); - forEachProjectInProjects( - projects, - /*path*/ - void 0, - (project) => addItemsForProject(project) - ); + forEachProjectInProjects(projects, /*path*/ + void 0, project => addItemsForProject(project)); } return outputs; function addItemsForProject(project) { - const projectItems = project.getLanguageService().getNavigateToItems( - searchValue, - maxResultCount, - /*fileName*/ - void 0, - /*excludeDts*/ - project.isNonTsProject(), - /*excludeLibFiles*/ - preferences.excludeLibrarySymbolsInNavTo - ); - const unseenItems = filter(projectItems, (item) => tryAddSeenItem(item) && !getMappedLocationForProject(documentSpanLocation(item), project)); + const projectItems = project.getLanguageService().getNavigateToItems(searchValue, maxResultCount, /*fileName*/ + void 0, /*excludeDts*/ + project.isNonTsProject(), /*excludeLibFiles*/ + preferences.excludeLibrarySymbolsInNavTo); + const unseenItems = filter(projectItems, item => tryAddSeenItem(item) && !getMappedLocationForProject(documentSpanLocation(item), project)); if (unseenItems.length) { - outputs.push({ project, navigateToItems: unseenItems }); + outputs.push({ + project, + navigateToItems: unseenItems + }); } } function tryAddSeenItem(item) { @@ -182350,15 +166045,16 @@ 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); + 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) { @@ -182378,33 +166074,41 @@ Project '${project.projectName}' (${ProjectKind[project.projectKind]}) ${counter } } getRange(args, scriptInfo) { - const { startPosition, endPosition } = this.getStartAndEndPosition(args, scriptInfo); - return { pos: startPosition, end: endPosition }; + const { + startPosition, + endPosition + } = this.getStartAndEndPosition(args, scriptInfo); + return { + pos: startPosition, + end: endPosition + }; } getApplicableRefactors(args) { - const { file, project } = this.getFileAndProject(args); + const { + file, + project + } = this.getFileAndProject(args); const scriptInfo = project.getScriptInfoForNormalizedPath(file); return project.getLanguageService().getApplicableRefactors(file, this.extractPositionOrRange(args, scriptInfo), this.getPreferences(file), args.triggerReason, args.kind, args.includeInteractiveActions); } getEditsForRefactor(args, simplifiedResult) { - const { file, project } = this.getFileAndProject(args); - const scriptInfo = project.getScriptInfoForNormalizedPath(file); - const result = project.getLanguageService().getEditsForRefactor( + const { file, - this.getFormatOptions(file), - this.extractPositionOrRange(args, scriptInfo), - args.refactor, - args.action, - this.getPreferences(file), - args.interactiveRefactorArguments - ); + project + } = this.getFileAndProject(args); + const scriptInfo = project.getScriptInfoForNormalizedPath(file); + const result = project.getLanguageService().getEditsForRefactor(file, this.getFormatOptions(file), this.extractPositionOrRange(args, scriptInfo), args.refactor, args.action, this.getPreferences(file), args.interactiveRefactorArguments); if (result === void 0) { return { edits: [] }; } if (simplifiedResult) { - const { renameFilename, renameLocation, edits } = result; + const { + renameFilename, + renameLocation, + edits + } = result; let mappedRenameLocation; if (renameFilename !== void 0 && renameLocation !== void 0) { const renameScriptInfo = project.getScriptInfoForNormalizedPath(toNormalizedPath(renameFilename)); @@ -182420,22 +166124,25 @@ Project '${project.projectName}' (${ProjectKind[project.projectKind]}) ${counter return result; } getMoveToRefactoringFileSuggestions(args) { - const { file, project } = this.getFileAndProject(args); + const { + file, + project + } = this.getFileAndProject(args); const scriptInfo = project.getScriptInfoForNormalizedPath(file); return project.getLanguageService().getMoveToRefactoringFileSuggestions(file, this.extractPositionOrRange(args, scriptInfo), this.getPreferences(file)); } organizeImports(args, simplifiedResult) { + var _args$mode2; Debug.assert(args.scope.type === "file"); - const { file, project } = this.getFileAndProject(args.scope.args); - const changes = project.getLanguageService().organizeImports( - { - fileName: file, - mode: args.mode ?? (args.skipDestructiveCodeActions ? "SortAndCombine" /* SortAndCombine */ : void 0), - type: "file" - }, - this.getFormatOptions(file), - this.getPreferences(file) - ); + const { + file, + project + } = this.getFileAndProject(args.scope.args); + const changes = project.getLanguageService().organizeImports({ + fileName: file, + mode: (_args$mode2 = args.mode) !== null && _args$mode2 !== void 0 ? _args$mode2 : args.skipDestructiveCodeActions ? "SortAndCombine" /* SortAndCombine */ : void 0, + type: "file" + }, this.getFormatOptions(file), this.getPreferences(file)); if (simplifiedResult) { return this.mapTextChangesToCodeEdits(changes); } else { @@ -182447,10 +166154,10 @@ Project '${project.projectName}' (${ProjectKind[project.projectKind]}) ${counter const newPath = toNormalizedPath(args.newFilePath); const formatOptions = this.getHostFormatOptions(); const preferences = this.getHostPreferences(); - const seenFiles = /* @__PURE__ */ new Set(); + const seenFiles = /* @__PURE__ */new Set(); const textChanges2 = []; this.projectService.loadAncestorProjectTree(); - this.projectService.forEachEnabledProject((project) => { + this.projectService.forEachEnabledProject(project => { const projectTextChanges = project.getLanguageService().getEditsForFileRename(oldPath, newPath, formatOptions, preferences); const projectFiles = []; for (const textChange of projectTextChanges) { @@ -182463,39 +166170,51 @@ Project '${project.projectName}' (${ProjectKind[project.projectKind]}) ${counter seenFiles.add(file); } }); - return simplifiedResult ? textChanges2.map((c) => this.mapTextChangeToCodeEdit(c)) : textChanges2; + return simplifiedResult ? textChanges2.map(c => this.mapTextChangeToCodeEdit(c)) : textChanges2; } getCodeFixes(args, simplifiedResult) { - const { file, project } = this.getFileAndProject(args); + const { + file, + project + } = this.getFileAndProject(args); const scriptInfo = project.getScriptInfoForNormalizedPath(file); - const { startPosition, endPosition } = this.getStartAndEndPosition(args, scriptInfo); + const { + startPosition, + endPosition + } = this.getStartAndEndPosition(args, scriptInfo); let codeActions; try { codeActions = project.getLanguageService().getCodeFixesAtPosition(file, startPosition, endPosition, args.errorCodes, this.getFormatOptions(file), this.getPreferences(file)); } catch (e) { const ls = project.getLanguageService(); - const existingDiagCodes = [ - ...ls.getSyntacticDiagnostics(file), - ...ls.getSemanticDiagnostics(file), - ...ls.getSuggestionDiagnostics(file) - ].map( - (d) => decodedTextSpanIntersectsWith(startPosition, endPosition - startPosition, d.start, d.length) && d.code - ); - const badCode = args.errorCodes.find((c) => !existingDiagCodes.includes(c)); + const existingDiagCodes = [...ls.getSyntacticDiagnostics(file), ...ls.getSemanticDiagnostics(file), ...ls.getSuggestionDiagnostics(file)].map(d => decodedTextSpanIntersectsWith(startPosition, endPosition - startPosition, d.start, d.length) && d.code); + const badCode = args.errorCodes.find(c => !existingDiagCodes.includes(c)); if (badCode !== void 0) { e.message = `BADCLIENT: Bad error code, ${badCode} not found in range ${startPosition}..${endPosition} (found: ${existingDiagCodes.join(", ")}); could have caused this error: ${e.message}`; } throw e; } - return simplifiedResult ? codeActions.map((codeAction) => this.mapCodeFixAction(codeAction)) : codeActions; + return simplifiedResult ? codeActions.map(codeAction => this.mapCodeFixAction(codeAction)) : codeActions; } - getCombinedCodeFix({ scope, fixId: fixId52 }, simplifiedResult) { + getCombinedCodeFix({ + scope, + fixId: fixId52 + }, simplifiedResult) { Debug.assert(scope.type === "file"); - const { file, project } = this.getFileAndProject(scope.args); - const res = project.getLanguageService().getCombinedCodeFix({ type: "file", fileName: file }, fixId52, this.getFormatOptions(file), this.getPreferences(file)); + const { + file, + project + } = this.getFileAndProject(scope.args); + const res = project.getLanguageService().getCombinedCodeFix({ + type: "file", + fileName: file + }, fixId52, this.getFormatOptions(file), this.getPreferences(file)); if (simplifiedResult) { - return { changes: this.mapTextChangesToCodeEdits(res.changes), commands: res.commands }; + return { + changes: this.mapTextChangesToCodeEdits(res.changes), + commands: res.commands + }; } else { return res; } @@ -182503,13 +166222,11 @@ ${e.message}`; applyCodeActionCommand(args) { const commands = args.command; for (const command of toArray(commands)) { - const { file, project } = this.getFileAndProject(command); - project.getLanguageService().applyCodeActionCommand(command, this.getFormatOptions(file)).then( - (_result) => { - }, - (_error) => { - } - ); + const { + file, + project + } = this.getFileAndProject(command); + project.getLanguageService().applyCodeActionCommand(command, this.getFormatOptions(file)).then(_result => {}, _error => {}); } return {}; } @@ -182527,16 +166244,41 @@ ${e.message}`; endPosition = scriptInfo.lineOffsetToPosition(args.endLine, args.endOffset); args.endPosition = endPosition; } - return { startPosition, endPosition }; + return { + startPosition, + endPosition + }; } - mapCodeAction({ description: description3, changes, commands }) { - return { description: description3, changes: this.mapTextChangesToCodeEdits(changes), commands }; + mapCodeAction({ + description: description3, + changes, + commands + }) { + return { + description: description3, + changes: this.mapTextChangesToCodeEdits(changes), + commands + }; } - mapCodeFixAction({ fixName: fixName8, description: description3, changes, commands, fixId: fixId52, fixAllDescription }) { - return { fixName: fixName8, description: description3, changes: this.mapTextChangesToCodeEdits(changes), commands, fixId: fixId52, fixAllDescription }; + mapCodeFixAction({ + fixName: fixName8, + description: description3, + changes, + commands, + fixId: fixId52, + fixAllDescription + }) { + return { + fixName: fixName8, + description: description3, + changes: this.mapTextChangesToCodeEdits(changes), + commands, + fixId: fixId52, + fixAllDescription + }; } mapTextChangesToCodeEdits(textChanges2) { - return textChanges2.map((change) => this.mapTextChangeToCodeEdit(change)); + return textChanges2.map(change => this.mapTextChangeToCodeEdit(change)); } mapTextChangeToCodeEdit(textChanges2) { const scriptInfo = this.projectService.getScriptInfoOrConfig(textChanges2.fileName); @@ -182544,9 +166286,15 @@ ${e.message}`; if (!scriptInfo) { this.projectService.logErrorForScriptInfoNotFound(textChanges2.fileName); } - Debug.fail("Expected isNewFile for (only) new files. " + JSON.stringify({ isNewFile: !!textChanges2.isNewFile, hasScriptInfo: !!scriptInfo })); + Debug.fail("Expected isNewFile for (only) new files. " + JSON.stringify({ + isNewFile: !!textChanges2.isNewFile, + hasScriptInfo: !!scriptInfo + })); } - return scriptInfo ? { fileName: textChanges2.fileName, textChanges: textChanges2.textChanges.map((textChange) => convertTextChangeToCodeEdit(textChange, scriptInfo)) } : convertNewFileTextChangeToCodeEdit(textChanges2); + return scriptInfo ? { + fileName: textChanges2.fileName, + textChanges: textChanges2.textChanges.map(textChange => convertTextChangeToCodeEdit(textChange, scriptInfo)) + } : convertNewFileTextChangeToCodeEdit(textChanges2); } convertTextChangeToCodeEdit(change, scriptInfo) { return { @@ -182556,29 +166304,30 @@ ${e.message}`; }; } getBraceMatching(args, simplifiedResult) { - const { file, languageService } = this.getFileAndLanguageServiceForSyntacticOperation(args); + const { + file, + languageService + } = this.getFileAndLanguageServiceForSyntacticOperation(args); const scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file); const position = this.getPosition(args, scriptInfo); const spans = languageService.getBraceMatchingAtPosition(file, position); - return !spans ? void 0 : simplifiedResult ? spans.map((span) => toProtocolTextSpan(span, scriptInfo)) : spans; + return !spans ? void 0 : simplifiedResult ? spans.map(span => toProtocolTextSpan(span, scriptInfo)) : spans; } getDiagnosticsForProject(next, delay, fileName) { if (this.suppressDiagnosticEvents) { return; } - const { fileNames, languageServiceDisabled } = this.getProjectInfoWorker( - fileName, - /*projectFileName*/ - void 0, - /*needFileNameList*/ - true, - /*excludeConfigFiles*/ - true - ); + const { + fileNames, + languageServiceDisabled + } = this.getProjectInfoWorker(fileName, /*projectFileName*/ + void 0, /*needFileNameList*/ + true, /*excludeConfigFiles*/ + true); if (languageServiceDisabled) { return; } - const fileNamesInProject = fileNames.filter((value) => !value.includes("lib.d.ts")); + const fileNamesInProject = fileNames.filter(value => !value.includes("lib.d.ts")); if (fileNamesInProject.length === 0) { return; } @@ -182605,69 +166354,84 @@ ${e.message}`; } } const sortedFiles = [...highPriorityFiles, ...mediumPriorityFiles, ...lowPriorityFiles, ...veryLowPriorityFiles]; - const checkList = sortedFiles.map((fileName2) => ({ fileName: fileName2, project })); - this.updateErrorCheck( - next, - checkList, - delay, - /*requireOpen*/ - false - ); + const checkList = sortedFiles.map(fileName2 => ({ + fileName: fileName2, + project + })); + this.updateErrorCheck(next, checkList, delay, /*requireOpen*/ + false); } configurePlugin(args) { this.projectService.configurePlugin(args); } getSmartSelectionRange(args, simplifiedResult) { - const { locations } = args; - const { file, languageService } = this.getFileAndLanguageServiceForSyntacticOperation(args); + const { + locations + } = args; + const { + file, + languageService + } = this.getFileAndLanguageServiceForSyntacticOperation(args); const scriptInfo = Debug.checkDefined(this.projectService.getScriptInfo(file)); - return map(locations, (location) => { + return map(locations, location => { const pos = this.getPosition(location, scriptInfo); const selectionRange = languageService.getSmartSelectionRange(file, pos); return simplifiedResult ? this.mapSelectionRange(selectionRange, scriptInfo) : selectionRange; }); } toggleLineComment(args, simplifiedResult) { - const { file, languageService } = this.getFileAndLanguageServiceForSyntacticOperation(args); + const { + file, + languageService + } = this.getFileAndLanguageServiceForSyntacticOperation(args); const scriptInfo = this.projectService.getScriptInfo(file); const textRange = this.getRange(args, scriptInfo); const textChanges2 = languageService.toggleLineComment(file, textRange); if (simplifiedResult) { const scriptInfo2 = this.projectService.getScriptInfoForNormalizedPath(file); - return textChanges2.map((textChange) => this.convertTextChangeToCodeEdit(textChange, scriptInfo2)); + return textChanges2.map(textChange => this.convertTextChangeToCodeEdit(textChange, scriptInfo2)); } return textChanges2; } toggleMultilineComment(args, simplifiedResult) { - const { file, languageService } = this.getFileAndLanguageServiceForSyntacticOperation(args); + const { + file, + languageService + } = this.getFileAndLanguageServiceForSyntacticOperation(args); const scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file); const textRange = this.getRange(args, scriptInfo); const textChanges2 = languageService.toggleMultilineComment(file, textRange); if (simplifiedResult) { const scriptInfo2 = this.projectService.getScriptInfoForNormalizedPath(file); - return textChanges2.map((textChange) => this.convertTextChangeToCodeEdit(textChange, scriptInfo2)); + return textChanges2.map(textChange => this.convertTextChangeToCodeEdit(textChange, scriptInfo2)); } return textChanges2; } commentSelection(args, simplifiedResult) { - const { file, languageService } = this.getFileAndLanguageServiceForSyntacticOperation(args); + const { + file, + languageService + } = this.getFileAndLanguageServiceForSyntacticOperation(args); const scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file); const textRange = this.getRange(args, scriptInfo); const textChanges2 = languageService.commentSelection(file, textRange); if (simplifiedResult) { const scriptInfo2 = this.projectService.getScriptInfoForNormalizedPath(file); - return textChanges2.map((textChange) => this.convertTextChangeToCodeEdit(textChange, scriptInfo2)); + return textChanges2.map(textChange => this.convertTextChangeToCodeEdit(textChange, scriptInfo2)); } return textChanges2; } uncommentSelection(args, simplifiedResult) { - const { file, languageService } = this.getFileAndLanguageServiceForSyntacticOperation(args); + const { + file, + languageService + } = this.getFileAndLanguageServiceForSyntacticOperation(args); const scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file); const textRange = this.getRange(args, scriptInfo); const textChanges2 = languageService.uncommentSelection(file, textRange); if (simplifiedResult) { const scriptInfo2 = this.projectService.getScriptInfoForNormalizedPath(file); - return textChanges2.map((textChange) => this.convertTextChangeToCodeEdit(textChange, scriptInfo2)); + return textChanges2.map(textChange => this.convertTextChangeToCodeEdit(textChange, scriptInfo2)); } return textChanges2; } @@ -182705,48 +166469,61 @@ ${e.message}`; const scriptInfo = this.getScriptInfoFromProjectService(incomingCall.from.file); return { from: this.toProtocolCallHierarchyItem(incomingCall.from), - fromSpans: incomingCall.fromSpans.map((fromSpan) => toProtocolTextSpan(fromSpan, scriptInfo)) + fromSpans: incomingCall.fromSpans.map(fromSpan => toProtocolTextSpan(fromSpan, scriptInfo)) }; } toProtocolCallHierarchyOutgoingCall(outgoingCall, scriptInfo) { return { to: this.toProtocolCallHierarchyItem(outgoingCall.to), - fromSpans: outgoingCall.fromSpans.map((fromSpan) => toProtocolTextSpan(fromSpan, scriptInfo)) + fromSpans: outgoingCall.fromSpans.map(fromSpan => toProtocolTextSpan(fromSpan, scriptInfo)) }; } prepareCallHierarchy(args) { - const { file, project } = this.getFileAndProject(args); + const { + file, + project + } = this.getFileAndProject(args); const scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file); if (scriptInfo) { const position = this.getPosition(args, scriptInfo); const result = project.getLanguageService().prepareCallHierarchy(file, position); - return result && mapOneOrMany(result, (item) => this.toProtocolCallHierarchyItem(item)); + return result && mapOneOrMany(result, item => this.toProtocolCallHierarchyItem(item)); } return void 0; } provideCallHierarchyIncomingCalls(args) { - const { file, project } = this.getFileAndProject(args); + const { + file, + project + } = this.getFileAndProject(args); const scriptInfo = this.getScriptInfoFromProjectService(file); const incomingCalls = project.getLanguageService().provideCallHierarchyIncomingCalls(file, this.getPosition(args, scriptInfo)); - return incomingCalls.map((call) => this.toProtocolCallHierarchyIncomingCall(call)); + return incomingCalls.map(call => this.toProtocolCallHierarchyIncomingCall(call)); } provideCallHierarchyOutgoingCalls(args) { - const { file, project } = this.getFileAndProject(args); + const { + file, + project + } = this.getFileAndProject(args); const scriptInfo = this.getScriptInfoFromProjectService(file); const outgoingCalls = project.getLanguageService().provideCallHierarchyOutgoingCalls(file, this.getPosition(args, scriptInfo)); - return outgoingCalls.map((call) => this.toProtocolCallHierarchyOutgoingCall(call, scriptInfo)); + return outgoingCalls.map(call => this.toProtocolCallHierarchyOutgoingCall(call, scriptInfo)); } getCanonicalFileName(fileName) { const name = this.host.useCaseSensitiveFileNames ? fileName : toFileNameLowerCase(fileName); return normalizePath(name); } - exit() { - } + exit() {} notRequired() { - return { responseRequired: false }; + return { + responseRequired: false + }; } requiredResponse(response) { - return { response, responseRequired: true }; + return { + response, + responseRequired: true + }; } addProtocolHandler(command, handler) { if (this.handlers.has(command)) { @@ -182780,16 +166557,12 @@ ${e.message}`; return response; } else { this.logger.msg(`Unrecognized JSON command:${stringifyIndented(request)}`, "Err" /* Err */); - this.doOutput( - /*info*/ - void 0, - "unknown" /* Unknown */, - request.seq, - /*success*/ - false, - `Unrecognized JSON command: ${request.command}` - ); - return { responseRequired: false }; + this.doOutput( /*info*/ + void 0, "unknown" /* Unknown */, request.seq, /*success*/ + false, `Unrecognized JSON command: ${request.command}`); + return { + responseRequired: false + }; } } onMessage(message) { @@ -182808,16 +166581,20 @@ ${e.message}`; try { request = this.parseMessage(message); relevantFile = request.arguments && request.arguments.file ? request.arguments : void 0; - (_a = tracing) == null ? void 0 : _a.instant(tracing.Phase.Session, "request", { seq: request.seq, command: request.command }); + (_a = tracing) == null ? void 0 : _a.instant(tracing.Phase.Session, "request", { + seq: request.seq, + command: request.command + }); (_b = perfLogger) == null ? void 0 : _b.logStartCommand("" + request.command, this.toStringMessage(message).substring(0, 100)); - (_c = tracing) == null ? void 0 : _c.push( - tracing.Phase.Session, - "executeCommand", - { seq: request.seq, command: request.command }, - /*separateBeginAndEnd*/ - true - ); - const { response, responseRequired } = this.executeCommand(request); + (_c = tracing) == null ? void 0 : _c.push(tracing.Phase.Session, "executeCommand", { + seq: request.seq, + command: request.command + }, /*separateBeginAndEnd*/ + true); + const { + response, + responseRequired + } = this.executeCommand(request); (_d = tracing) == null ? void 0 : _d.pop(); if (this.logger.hasLevel(2 /* requestTime */)) { const elapsedTime = hrTimeToMilliseconds(this.hrtime(start)).toFixed(4); @@ -182828,52 +166605,43 @@ ${e.message}`; } } (_e = perfLogger) == null ? void 0 : _e.logStopCommand("" + request.command, "Success"); - (_f = tracing) == null ? void 0 : _f.instant(tracing.Phase.Session, "response", { seq: request.seq, command: request.command, success: !!response }); + (_f = tracing) == null ? void 0 : _f.instant(tracing.Phase.Session, "response", { + seq: request.seq, + command: request.command, + success: !!response + }); if (response) { - this.doOutput( - response, - request.command, - request.seq, - /*success*/ - true - ); + this.doOutput(response, request.command, request.seq, /*success*/ + true); } else if (responseRequired) { - this.doOutput( - /*info*/ - void 0, - request.command, - request.seq, - /*success*/ - false, - "No content available." - ); + this.doOutput( /*info*/ + void 0, request.command, request.seq, /*success*/ + false, "No content available."); } } catch (err) { (_g = tracing) == null ? void 0 : _g.popAll(); if (err instanceof OperationCanceledException) { (_h = perfLogger) == null ? void 0 : _h.logStopCommand("" + (request && request.command), "Canceled: " + err); - (_i = tracing) == null ? void 0 : _i.instant(tracing.Phase.Session, "commandCanceled", { seq: request == null ? void 0 : request.seq, command: request == null ? void 0 : request.command }); - this.doOutput( - { canceled: true }, - request.command, - request.seq, - /*success*/ - true - ); + (_i = tracing) == null ? void 0 : _i.instant(tracing.Phase.Session, "commandCanceled", { + seq: request == null ? void 0 : request.seq, + command: request == null ? void 0 : request.command + }); + this.doOutput({ + canceled: true + }, request.command, request.seq, /*success*/ + true); return; } this.logErrorWorker(err, this.toStringMessage(message), relevantFile); (_j = perfLogger) == null ? void 0 : _j.logStopCommand("" + (request && request.command), "Error: " + err); - (_k = tracing) == null ? void 0 : _k.instant(tracing.Phase.Session, "commandError", { seq: request == null ? void 0 : request.seq, command: request == null ? void 0 : request.command, message: err.message }); - this.doOutput( - /*info*/ - void 0, - request ? request.command : "unknown" /* Unknown */, - request ? request.seq : 0, - /*success*/ - false, - "Error processing request. " + err.message + "\n" + err.stack - ); + (_k = tracing) == null ? void 0 : _k.instant(tracing.Phase.Session, "commandError", { + seq: request == null ? void 0 : request.seq, + command: request == null ? void 0 : request.command, + message: err.message + }); + this.doOutput( /*info*/ + void 0, request ? request.command : "unknown" /* Unknown */, request ? request.seq : 0, /*success*/ + false, "Error processing request. " + err.message + "\n" + err.stack); } } parseMessage(message) { @@ -182903,10 +166671,11 @@ ${e.message}`; var init_scriptVersionCache = __esm({ "src/server/scriptVersionCache.ts"() { "use strict"; + init_ts7(); init_ts_server3(); lineCollectionCapacity = 4; - CharRangeSection = /* @__PURE__ */ ((CharRangeSection2) => { + CharRangeSection = /* @__PURE__ */(CharRangeSection2 => { CharRangeSection2[CharRangeSection2["PreStart"] = 0] = "PreStart"; CharRangeSection2[CharRangeSection2["Start"] = 1] = "Start"; CharRangeSection2[CharRangeSection2["Entire"] = 2] = "Entire"; @@ -183003,6 +166772,7 @@ ${e.message}`; if (lineCollection === this.lineCollectionAtBranch) { this.state = 4 /* End */; } + this.stack.pop(); } pre(_relativeStart, _relativeLength, lineCollection, _parent, nodeType) { @@ -183016,8 +166786,7 @@ ${e.message}`; function fresh(node) { if (node.isLeaf()) { return new LineLeaf(""); - } else - return new LineNode(); + } else return new LineNode(); } switch (nodeType) { case 0 /* PreStart */: @@ -183153,7 +166922,10 @@ ${e.message}`; } lineToTextSpan(line) { const index = this._getSnapshot().index; - const { lineText, absolutePosition } = index.lineNumberToInfo(line + 1); + const { + lineText, + absolutePosition + } = index.lineNumberToInfo(line + 1); const len = lineText !== void 0 ? lineText.length : index.absolutePositionOfStartOfLine(line + 2) - absolutePosition; return createTextSpan(absolutePosition, len); } @@ -183223,8 +166995,14 @@ ${e.message}`; return this.lineNumberToInfo(oneBasedLine).absolutePosition; } positionToLineOffset(position) { - const { oneBasedLine, zeroBasedColumn } = this.root.charOffsetToLineInfo(1, position); - return { line: oneBasedLine, offset: zeroBasedColumn + 1 }; + const { + oneBasedLine, + zeroBasedColumn + } = this.root.charOffsetToLineInfo(1, position); + return { + line: oneBasedLine, + offset: zeroBasedColumn + 1 + }; } positionToColumnAndLineText(position) { return this.root.charOffsetToLineInfo(1, position); @@ -183235,10 +167013,19 @@ ${e.message}`; lineNumberToInfo(oneBasedLine) { const lineCount = this.getLineCount(); if (oneBasedLine <= lineCount) { - const { position, leaf } = this.root.lineNumberToInfo(oneBasedLine, 0); - return { absolutePosition: position, lineText: leaf && leaf.text }; + const { + position, + leaf + } = this.root.lineNumberToInfo(oneBasedLine, 0); + return { + absolutePosition: position, + lineText: leaf && leaf.text + }; } else { - return { absolutePosition: this.root.charCount(), lineText: void 0 }; + return { + absolutePosition: this.root.charCount(), + lineText: void 0 + }; } } load(lines) { @@ -183315,7 +167102,10 @@ ${e.message}`; suppressTrailingText = true; } else if (deleteLength > 0) { const e = pos + deleteLength; - const { zeroBasedColumn, lineText } = this.positionToColumnAndLineText(e); + const { + zeroBasedColumn, + lineText + } = this.positionToColumnAndLineText(e); if (zeroBasedColumn === 0) { deleteLength += lineText.length; newText = newText ? newText + lineText : lineText; @@ -183346,7 +167136,10 @@ ${e.message}`; static linesFromText(text) { const lineMap = computeLineStarts(text); if (lineMap.length === 0) { - return { lines: [], lineMap }; + return { + lines: [], + lineMap + }; } const lines = new Array(lineMap.length); const lc = lineMap.length - 1; @@ -183359,7 +167152,10 @@ ${e.message}`; } else { lines.pop(); } - return { lines, lineMap }; + return { + lines, + lineMap + }; } }; LineNode = class _LineNode { @@ -183367,8 +167163,7 @@ ${e.message}`; this.children = children; this.totalChars = 0; this.totalLines = 0; - if (children.length) - this.updateCounts(); + if (children.length) this.updateCounts(); } isLeaf() { return false; @@ -183450,12 +167245,20 @@ ${e.message}`; // Output line number is absolute. charOffsetToLineInfo(lineNumberAccumulator, relativePosition) { if (this.children.length === 0) { - return { oneBasedLine: lineNumberAccumulator, zeroBasedColumn: relativePosition, lineText: void 0 }; + return { + oneBasedLine: lineNumberAccumulator, + zeroBasedColumn: relativePosition, + lineText: void 0 + }; } for (const child of this.children) { if (child.charCount() > relativePosition) { if (child.isLeaf()) { - return { oneBasedLine: lineNumberAccumulator, zeroBasedColumn: relativePosition, lineText: child.text }; + return { + oneBasedLine: lineNumberAccumulator, + zeroBasedColumn: relativePosition, + lineText: child.text + }; } else { return child.charOffsetToLineInfo(lineNumberAccumulator, relativePosition); } @@ -183466,10 +167269,18 @@ ${e.message}`; } const lineCount = this.lineCount(); if (lineCount === 0) { - return { oneBasedLine: 1, zeroBasedColumn: 0, lineText: void 0 }; + return { + oneBasedLine: 1, + zeroBasedColumn: 0, + lineText: void 0 + }; } const leaf = Debug.checkDefined(this.lineNumberToInfo(lineCount, 0).leaf); - return { oneBasedLine: lineCount, zeroBasedColumn: leaf.charCount(), lineText: void 0 }; + return { + oneBasedLine: lineCount, + zeroBasedColumn: leaf.charCount(), + lineText: void 0 + }; } /** * Input line number is relative to the start of this node. @@ -183480,13 +167291,19 @@ ${e.message}`; for (const child of this.children) { const childLineCount = child.lineCount(); if (childLineCount >= relativeOneBasedLine) { - return child.isLeaf() ? { position: positionAccumulator, leaf: child } : child.lineNumberToInfo(relativeOneBasedLine, positionAccumulator); + return child.isLeaf() ? { + position: positionAccumulator, + leaf: child + } : child.lineNumberToInfo(relativeOneBasedLine, positionAccumulator); } else { relativeOneBasedLine -= childLineCount; positionAccumulator += child.charCount(); } } - return { position: positionAccumulator, leaf: void 0 }; + return { + position: positionAccumulator, + leaf: void 0 + }; } splitAfter(childIndex) { let splitNode; @@ -183703,6 +167520,7 @@ ${e.message}`; var init_ts_server3 = __esm({ "src/server/_namespaces/ts.server.ts"() { "use strict"; + init_ts_server(); init_ts_server2(); init_types4(); @@ -186014,6 +169832,7 @@ ${e.message}`; var init_ts7 = __esm({ "src/server/_namespaces/ts.ts"() { "use strict"; + init_ts2(); init_ts3(); init_ts4(); @@ -186123,6 +169942,7 @@ ${e.message}`; var init_ts_server4 = __esm({ "src/typescript/_namespaces/ts.server.ts"() { "use strict"; + init_ts_server(); init_ts_server3(); } @@ -188422,6 +172242,7 @@ ${e.message}`; var init_ts8 = __esm({ "src/typescript/_namespaces/ts.ts"() { "use strict"; + init_ts2(); init_ts3(); init_ts4(); @@ -188456,6 +172277,6 @@ ${e.message}`; }); return require_typescript(); })(); - -if (typeof module !== "undefined" && module.exports) { module.exports = ts; } -//# sourceMappingURL=typescript.js.map +if (typeof module !== "undefined" && module.exports) { + module.exports = ts; +} \ No newline at end of file